Learn WHERE, Logical Operators, ORDER BY & LIMIT/TOP
Master SQL filtering and sorting with this beginner-friendly guide. Learn the WHERE clause, comparison operators (=, <>, >, <, >=, <=), logical operators (AND, OR, NOT), ORDER BY for sorting, and LIMIT/TOP to restrict results. Practice filtering employees by salary, sorting students by marks, and using multiple conditions.
1. Introduction
Filtering and sorting allow you to retrieve only the data you need and present it in a meaningful order.
Key Points:
- Filtering reduces the number of rows returned using conditions.
- Sorting organizes data in ascending or descending order.
- Logical operators allow combining multiple conditions.
2. The WHERE Clause
The WHERE clause filters rows based on specified conditions.
Syntax:
Comparison Operators:
| OperatorMeaningExample | ||
| = | Equal | Salary = 50000 |
| <> | Not equal | Department <> 'IT' |
| > | Greater than | Salary > 50000 |
| < | Less than | Salary < 60000 |
| >= | Greater or equal | Salary >= 50000 |
| <= | Less or equal | Salary <= 60000 |
Example:
3. Logical Operators (AND, OR, NOT)
Combine multiple conditions using:
| OperatorDescription | |
| AND | Both conditions must be true |
| OR | Either condition can be true |
| NOT | Negates a condition |
Examples:
4. ORDER BY Clause
The ORDER BY clause sorts results by one or more columns. Default is ascending (ASC); use descending (DESC) for reverse order.
Syntax:
Examples:
5. LIMIT / TOP
Use LIMIT (MySQL/PostgreSQL) or TOP (SQL Server) to restrict the number of rows returned.
Examples:
6. Practical Exercises
- Filter employees with salary > 50000.
- Sort students by marks in descending order.
- Filter employees in the IT department with salary > 60000.
- Retrieve the top 3 highest-paid employees using LIMIT/TOP.
- Exclude employees from the HR department using NOT.
7. Tips for Beginners
- Test WHERE conditions carefully to avoid unexpected results.
- Use AND/OR operators to combine conditions logically.
- Always use ORDER BY for readable query output.
- Combine WHERE + ORDER BY + LIMIT/TOP for precise data retrieval.