Topic 7 – SQL Operators – Mastering Data Filtering & Calculations

image 2

Play Store Application link – SQL in 18 steps – App on Google Play

Introduction

SQL Operators help in performing calculations, filtering data, and making comparisons. Think of them as tools that refine search results, just like using filters while shopping online!


1. Arithmetic Operators – Performing Calculations

These operators help in performing basic math calculations.

OperatorDescriptionExample
+AdditionSELECT 10 + 5; β†’ 15
-SubtractionSELECT 10 - 5; β†’ 5
*MultiplicationSELECT 10 * 5; β†’ 50
/DivisionSELECT 10 / 5; β†’ 2
%Modulus (Remainder)SELECT 10 % 3; β†’ 1

Example: Calculate Total Price in Orders Table

SELECT product_name, quantity, price, quantity * price AS total_price
FROM Orders;


2. Comparison Operators – Filtering Data

These operators help compare values.

OperatorMeaning
=Equal to
!= or <>Not equal to
<Less than
>Greater than
<=Less than or equal to
>=Greater than or equal to

Example: Find Students Aged 18 and Above

SELECT * FROM Students WHERE age >= 18;

Example: Find Products That Are Not Laptops

SELECT * FROM Products WHERE category != 'Laptop';


3. Logical Operators – Combining Conditions

Logical operators help in applying multiple conditions.

OperatorDescription
ANDBoth conditions must be true
ORAt least one condition must be true
NOTNegates a condition

Example: Find Employees Aged 25-35 with Salary Above 50,000

SELECT * FROM Employees WHERE age BETWEEN 25 AND 35 AND salary > 50000;

Example: Find Orders That Are Not Delivered

SELECT * FROM Orders WHERE NOT status = 'Delivered';


4. Wildcard Operators – Searching Patterns

Used with LIKE to find partial matches.

WildcardMeaning
%Represents zero or more characters
_Represents a single character

Example: Find Names Starting with ‘A’

SELECT * FROM Customers WHERE name LIKE 'A%';

Example: Find 5-Letter Names Starting with ‘J’

SELECT * FROM Customers WHERE name LIKE 'J____';


5. IN, BETWEEN, and EXISTS – Advanced Filtering

Using IN – Match Multiple Values

Find employees from specific departments:

SELECT * FROM Employees WHERE department IN ('HR', 'Finance', 'IT');

Using BETWEEN – Find Values in a Range

Find products priced between 500 and 1000:

SELECT * FROM Products WHERE price BETWEEN 500 AND 1000;

Using EXISTS – Check If Related Data Exists

Find customers who have placed orders:

SELECT * FROM Customers WHERE EXISTS (SELECT 1 FROM Orders WHERE Orders.customer_id = Customers.customer_id);


Conclusion

SQL operators help in refining queries, making searches efficient, and performing calculations. Mastering them ensures effective database interactions.

Leave a Reply

Your email address will not be published. Required fields are marked *