WHERE Clause
Introduction to SQL
Database
SQL Basics
Creating a Database
Using a Database
Creating a Table
Common Data Types
Inserting Data
Selecting Data
WHERE Clause
Comparison Operators
AND, OR, and NOT
ORDER BY Clause
LIMIT Clause
DISTINCT
LIKE Operator
IN, BETWEEN, and IS NULL
Updating Data
Deleting Data
ALTER TABLE
DROP TABLE
PRIMARY KEY and NOT NULL
FOREIGN KEY and Relationships
Aggregate Functions
GROUP BY Clause
HAVING Clause
JOIN Basics
INNER JOIN
LEFT JOIN
Aliases
Subqueries
Indexes
User Permissions and Security
Common Mistakes Beginners Make
Practice Ideas
WHERE Clause
The WHERE Clause
Definition: The WHERE clause is used to filter records. It ensures that only the data meeting a specific condition is retrieved from the database.
Learning Outcome: Filtering is a major milestone in learning SQL. While SELECT shows you columns, WHERE allows you to drill down into specific rows, making it possible to find exact information within thousands of records.
Syntax
The WHERE clause is placed immediately after the FROM statement. It requires a condition (a logical test) to evaluate each row.
SELECT column1, column2 FROM table_name WHERE condition;
Example: Numeric Filtering
If you want to find all students in your database who are older than 20, you would use the "greater than" operator (>):
SELECT * FROM students WHERE age > 20;
Explanation
- Filtering Logic: The database engine looks at the
agecolumn for every row. If the number is 21 or higher, the row is included in the results. If it is 20 or lower, the row is hidden. - The Result: This query returns only the specific students who meet the criteria, providing a targeted subset of your data.
Common Comparison Operators
| Operator | Meaning | Example |
|---|---|---|
= |
Equal to | WHERE city = 'Mysuru' |
> or < |
Greater / Less than | WHERE age < 18 |
>= or <= |
Greater / Less than or equal to | WHERE id >= 10 |
<> or != |
Not equal to | WHERE name != 'Ravi' |
Key Notes
- Text vs Numbers: Remember that text values must be inside single quotes (
'Bengaluru'), but numbers do not need quotes (25). - Multiple Conditions: You can combine multiple filters using
ANDorOR(e.g.,WHERE age > 20 AND city = 'Hassan'). - Performance: Using a
WHEREclause is much more efficient than selecting all data and filtering it manually in another application like Excel.
🏋️ Test Yourself With Exercises
Take our quiz on WHERE Clause to test your knowledge.
Browse Quizzes »