WHERE: Filtering Data

In SQL, the WHERE clause lets you filter rows based on a condition.
Instead of getting all the data from a table, you ask for just the rows that match a rule.


Syntax

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

Example: Show only employees from the IT department

SELECT name, department FROM employees
WHERE department = 'IT';

Output:

  name  | department 
--------+------------
 Bob    | IT
 Emma   | IT
 Mike   | IT
 Sarah  | IT
 Olivia | IT
 Thomas | IT
(6 rows)

This query returns only the rows where the department is IT.


Example: Show employees older than 30

SELECT name, age FROM employees
WHERE age > 30;

Output:

  name  | age 
--------+-----
 Bob    |  32
 Grace  |  31
 Jack   |  33
 Paul   |  32
 Tina   |  31
 Thomas |  33
(6 rows)

You can use these comparison operators:

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

Tip: Single Quotes for Text

In PostgreSQL, text values always go in single quotes, like 'IT'. Double quotes mean something else: they are used for column and table names. So this query fails:

SELECT name FROM employees
WHERE department = "IT";

Output:

ERROR:  column "IT" does not exist
LINE 2: WHERE department = "IT";
                           ^

PostgreSQL looked for a column named IT and did not find one. Use 'IT' with single quotes, and the query works.


In the exercise, use WHERE to find the employees who are 25 or younger.