This guide is specifically for PostgreSQL syntax.
Learn SQL WHERE Clause with hands-on practice exercises. Each exercise includes the table schema, solution query, expected output, and detailed explanation.
What You'll Practice
These exercises cover WHERE Clause from basic to advanced concepts. Work through each problem to build your SQL skills.
Exercise 1
Question: Select all employees with a salary greater than 50000.
Table Schema
CREATE TABLE employees ( id INT PRIMARY KEY, name VARCHAR(100), salary DECIMAL(10,2) );
Solution
SELECT * FROM employees WHERE salary > 50000;
Expected Output
| id | name | salary | |---|---|---| | 2 | Jane | 60000 | | 3 | Alice | 75000 |
Explanation
The WHERE clause filters rows based on a condition. Comparison operators include: =, <>, <, >, <=, >=
Exercise 2
Question: Find employees in the 'Sales' department with salary between 40000 and 60000.
Table Schema
CREATE TABLE employees ( id INT PRIMARY KEY, name VARCHAR(100), salary DECIMAL(10,2), department VARCHAR(50) );
Solution
SELECT * FROM employees WHERE department = 'Sales' AND salary BETWEEN 40000 AND 60000;
Expected Output
| id | name | salary | department | |---|---|---|---| | 1 | John | 50000 | Sales |
Explanation
Use AND to combine multiple conditions. BETWEEN is inclusive of both endpoints.
Exercise 3
Question: Select employees whose names start with 'J'.
Table Schema
CREATE TABLE employees ( id INT PRIMARY KEY, name VARCHAR(100) );
Solution
SELECT * FROM employees WHERE name LIKE 'J%';
Expected Output
| id | name | |---|---| | 1 | John | | 2 | Jane |
Explanation
LIKE with % wildcard matches any sequence of characters. 'J%' matches strings starting with J.
Exercise 4
Question: Find employees who are NOT in the Engineering or Marketing departments.
Table Schema
CREATE TABLE employees ( id INT PRIMARY KEY, name VARCHAR(100), department VARCHAR(50) );
Solution
SELECT * FROM employees WHERE department NOT IN ('Engineering', 'Marketing');
Expected Output
| id | name | department | |---|---|---| | 1 | John | Sales | | 4 | Mike | HR |
Explanation
NOT IN excludes specified values. This is cleaner than writing multiple AND conditions.
Exercise 5
Question: Select employees where the manager_id is NULL (no manager assigned).
Table Schema
CREATE TABLE employees ( id INT PRIMARY KEY, name VARCHAR(100), manager_id INT );
Solution
SELECT * FROM employees WHERE manager_id IS NULL;
Expected Output
| id | name | manager_id | |---|---|---| | 1 | CEO John | NULL |
Explanation
Use IS NULL to check for NULL values. Using = NULL will not work because NULL represents unknown values.
Common Mistakes to Avoid
- Forgetting to use proper syntax for WHERE Clause
- Not considering NULL values in comparisons
- Confusing similar operators or clauses
Related SQL Exercises
Continue practicing with these related topics:
PostgreSQL-Specific Notes
This page covers PostgreSQL syntax. Other databases may have different syntax for similar operations.