WHERE command in SQL to use conditions

SQL

WHERE clause is used to filter records based on a specified condition. It allows you to narrow down the data you retrieve by setting conditions. Only rows that meet the specified criteria will be included in the result.

Let’s begin by understanding the basic syntax of the WHERE statement:

SELECT column1, column2, ...
FROM table
WHERE condition;

Here, SELECT specifies the columns to be retrieved, FROM indicates the table, and WHERE sets the conditions for filtering.

Basic Examples

Example 1: Filtering by Equality

Consider a table named students:

IDNameAgeGrade
1Alice21A
2Bob22B
3Carol20C

To retrieve students with the name ‘Alice,’ the WHERE statement can be used:

SELECT * FROM students
WHERE Name = 'Alice';

Output:

IDNameAgeGrade
1Alice21A

Example 2: Using Comparison Operators

Extend your understanding with comparison operators like <, >, <=, and >=:

SELECT * FROM students
WHERE Age >= 21;

Output:

IDNameAgeGrade
1Alice21A
2Bob22B

Common Operators

Now, let’s introduce common operators like <> (not equal) and LIKE for more complex conditions.

Example 3: Filtering by Inequality

SELECT * FROM students
WHERE Grade <> 'A';

Output:

IDNameAgeGrade
2Bob22B
3Carol20C

Example 4: Using the LIKE Operator

SELECT * FROM students
WHERE Name LIKE 'Ca%';

Output:

IDNameAgeGrade
3Carol20C

Combining Conditions

Combine multiple conditions using logical operators (AND, OR, NOT) for more precise filtering.

Example 5: Using AND

SELECT * FROM students
WHERE Age >= 20 AND Grade = 'C';

Output:

IDNameAgeGrade
3Carol20C

Now, let’s apply the WHERE statement to a real-world scenario. Consider a more extensive database, and let’s formulate conditions and execute queries.

Imagine we have a more complex database named employees:

IDNameDepartmentSalary
1JohnMarketing50000
2SarahIT60000
3MichaelFinance55000
4EmilyHR48000

Example 6: Filtering by Department and Salary

Let’s say we want to find employees in the IT department with a salary greater than $55,000:

SELECT * FROM employees
WHERE Department = 'IT' AND Salary > 55000

Output:

IDNameDepartmentSalary
2SarahIT60000

Consider indexing columns used in WHERE conditions for faster query performance.

Using wildcards like %value% at the start of the LIKE condition can slow down queries. Prefer %value or value% for better optimization.