Filtering Data in SQL

Learn how to filter data in SQL using the WHERE clause, comparison operators, and logical operators.

1. Using the WHERE Clause

The WHERE clause is used to filter records in a SQL query based on specific conditions. Example:

SELECT * FROM users WHERE age > 25;

This query retrieves all users where the `age` is greater than 25.

ID Name Age City
1 John Doe 30 New York

Additional Example:

SELECT * FROM orders WHERE order_date = '2024-10-01';

This query retrieves all orders that were placed on October 1, 2024.

Order ID Order Date Amount
101 2024-10-01 $1200

Example with Multiple Conditions:

SELECT * FROM employees WHERE department = 'IT' AND salary > 50000;

This query retrieves all employees who work in the IT department and earn more than 50,000.

Employee ID Name Department Salary
1 David IT $80,000

2. Comparison Operators

SQL supports several comparison operators to filter data. Commonly used operators include:

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

Example using comparison operators:

SELECT * FROM products WHERE price >= 100;

This query retrieves all products with a price of 100 or more.

Product ID Product Name Price
201 Laptop $1200
202 Smartphone $800

Example with Range of Values:

SELECT * FROM customers WHERE age BETWEEN 30 AND 40;

This query retrieves all customers whose age is between 30 and 40.

Customer ID Name Age
1 John Doe 35

3. Logical Operators: AND, OR, NOT

SQL also provides logical operators to combine multiple conditions. The most common logical operators are:

  • AND: Returns records that meet all conditions.
  • OR: Returns records that meet at least one condition.
  • NOT: Excludes records that meet the condition.

AND Operator Example:

SELECT * FROM users WHERE age > 25 AND city = 'New York';

This query retrieves all users who are older than 25 and live in New York.

ID Name Age City
1 John Doe 30 New York

OR Operator Example:

SELECT * FROM users WHERE age < 18 OR age > 65;

This query retrieves all users who are either younger than 18 or older than 65.

ID Name Age
2 Jane Doe 70

NOT Operator Example:

SELECT * FROM users WHERE NOT city = 'Los Angeles';

This query retrieves all users who do not live in Los Angeles.

ID Name City
1 John Doe New York

Conclusion

Filtering data is essential for retrieving specific records from your database. By using the WHERE clause, comparison operators, and logical operators, you can efficiently narrow down the data to meet your requirements.