PostgreSQL WHERE

The WHERE clause in a SELECT statement is where you filter out records you don't want to see. Here is the basic syntax of a WHERE clause:

SELECT * FROM table_name WHERE column_name = 'some value';

In addition to SELECT statements, the WHERE clause can be applied to UPDATE and DELETE statements with the same goal of filtering records. When your SQL statement has a WHERE clause you must (most of the time) include a comparison operator like equals and not equals. Here is a list of comparison operators.

OperatorDescription
=Equal to
<> or !=Not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to
ANDLogical operator AND
ORLogical operator OR
IS NULLIs a NULL value
IS NOT NULLIs NOT NULL value

Below are some examples using a WHERE clause in SELECT, UPDATE and DELETE statements. If you wanted to see the employees in the Engineering department you might use a WHERE clause like this:

SELECT *
FROM employee
WHERE dept = 'Engineering';

+----+------------+-----------+-------------+---------+------------+
| id | first_name | last_name |    dept     | salary  | hire_date  |
+----+------------+-----------+-------------+---------+------------+
|  3 | Lisa       | Teal      | Engineering | 2496.78 | 2019-03-10 |
|  4 | Gunner     | Greenburg | Engineering | 2169.32 | 2017-09-22 |
+----+------------+-----------+-------------+---------+------------+

You can also combine WHERE clauses with an AND or an OR. Here are a couple of examples.

SELECT *
FROM employee
WHERE dept = 'Engineering'
  AND first_name = 'Lisa';

+----+------------+-----------+-------------+---------+------------+
| id | first_name | last_name |    dept     | salary  | hire_date  |
+----+------------+-----------+-------------+---------+------------+
|  3 | Lisa       | Teal      | Engineering | 2496.78 | 2019-03-10 |
+----+------------+-----------+-------------+---------+------------+

SELECT *
FROM employee
WHERE dept = 'Engineering'
  OR first_name = 'Joe';

+----+------------+-----------+-------------+---------+------------+
| id | first_name | last_name |    dept     | salary  | hire_date  |
+----+------------+-----------+-------------+---------+------------+
|  1 | Joe        | Jones     | Sales       | 1034.23 | 2015-01-15 |
|  3 | Lisa       | Teal      | Engineering | 2496.78 | 2019-03-10 |
|  4 | Gunner     | Greenburg | Engineering | 2169.32 | 2017-09-22 |
+----+------------+-----------+-------------+---------+------------+

Be careful when trying to combine an AND and an OR clause in the same SQL statement. The order of operations is important.

Next: PostgreSQL LIMIT