SELECT … FROM reads data from a table in PostgreSQL. SELECT * returns every column; name the columns you want to get only those.
Every command and output on this page is real, from PostgreSQL 19 on macOS.
Syntax
Syntax
SELECT * FROM table_name;
SELECT column1, column2 FROM table_name;
*: every column, in the table’s order.column1, column2: only these columns, in this order.FROM table_name: the table to read.
See SELECT in the PostgreSQL documentation.
The Example
A zoo’s animals, with the number of legs each has.
Step 1: Create a Test Database
Open Terminal and connect to your PostgreSQL server with psql as the postgres user:
Terminal
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:
postgres=#
CREATE DATABASE zoo;
Output
CREATE DATABASE
postgres=#
\c zoo
Output
You are now connected to database "zoo" as user "postgres".
Create the table and add three animals:
zoo=#
CREATE TABLE animals (name text, legs integer);
Output
CREATE TABLE
zoo=#
INSERT INTO animals (name, legs) VALUES ('penguin', 2);
Output
INSERT 0 1
zoo=#
INSERT INTO animals (name, legs) VALUES ('zebra', 4);
Output
INSERT 0 1
zoo=#
INSERT INTO animals (name, legs) VALUES ('spider', 8);
Output
INSERT 0 1
Step 2: Select Every Column
zoo=#
SELECT * FROM animals;
Output
name | legs
---------+------
penguin | 2
zebra | 4
spider | 8
(3 rows)
psql ends with the number of rows.
Step 3: Select One Column
zoo=#
SELECT name FROM animals;
Output
name
---------
penguin
zebra
spider
(3 rows)
Clean Up
To remove the example, connect to another database and drop the test database:
zoo=#
\c postgres
Output
You are now connected to database "postgres" as user "postgres".
postgres=#
DROP DATABASE zoo;
Output
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 |
|---|---|---|
| A table name that’s slightly wrong | ERROR: relation "animal" does not exist | Check the name, including the plural. |
FAQ
In what order do the rows come?
In no particular order: without ORDER BY, the documentation says rows come in whatever order the system finds fastest.
Conclusion
SELECT * FROM and a table’s name return all its rows and columns. List column names instead of * to get only those columns.
Additional Resources
Postgres, PostgreSQL and the Slonik Logo are trademarks or registered trademarks of the PostgreSQL Community Association of Canada, and used with their permission.
