WHERE keeps only the rows that match a condition: SELECT * FROM cities WHERE country = 'France'; returns the French cities. Here’s how to filter rows with WHERE in PostgreSQL.
Every command and output on this page is real, from PostgreSQL 19 on macOS.
Syntax
SELECT columns FROM table_name WHERE condition;
condition: a test for each row, such ascountry = 'France'. Only the rows where it’s true come back.- Text in a condition goes in single quotes; numbers don’t.
See The WHERE Clause (opens in a new tab) in the PostgreSQL documentation.
The Example
A table of cities and the countries they’re in.
Step 1: Create a Test Database
Open Terminal and connect to your PostgreSQL server with psql as the postgres user:
psql -U postgres
Type the user’s password when psql asks for it. psql connects you to the postgres database, and its prompt is postgres=#.
Create a database for the example and connect to it:
CREATE DATABASE atlas;
CREATE DATABASE
\c atlas
You are now connected to database "atlas" as user "postgres".
Create the table and add three cities:
CREATE TABLE cities (name text, country text);
CREATE TABLE
INSERT INTO cities (name, country) VALUES ('Lyon', 'France');
INSERT 0 1
INSERT INTO cities (name, country) VALUES ('Porto', 'Portugal');
INSERT 0 1
INSERT INTO cities (name, country) VALUES ('Nice', 'France');
INSERT 0 1
Step 2: Filter the Rows
SELECT * FROM cities WHERE country = 'France';
name | country
------+---------
Lyon | France
Nice | France
(2 rows)
Porto is left out, because its country isn’t France.
Step 3: A Condition No Row Matches
SELECT * FROM cities WHERE country = 'Spain';
name | country
------+---------
(0 rows)
No row matches, so you get (0 rows). That’s an answer, not an error.
Clean Up
To remove the example, connect to another database and drop the test database:
\c postgres
You are now connected to database "postgres" as user "postgres".
DROP DATABASE atlas;
DROP DATABASE
Warning: DROP DATABASE deletes the database and everything in it, and it can’t be undone.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Text without quotes: WHERE country = France | ERROR: column "france" does not exist | Put text in single quotes: 'France'. Without them, PostgreSQL reads a column name. |
FAQ
Why does the error say france, in lowercase?
Because PostgreSQL read France as a column name, and it turns names typed without quotes into lowercase.
Conclusion
Add WHERE and a condition to a SELECT to get only the rows you want, with text values in single quotes.
Additional Resources
- PostgreSQL 19 documentation: The WHERE Clause (opens in a new tab)
- PostgreSQL 19 documentation: Comparison Functions and Operators (opens in a new tab)
Postgres, PostgreSQL and the Slonik Logo are trademarks or registered trademarks of the PostgreSQL Community Association of Canada, and used with their permission.
0 comments