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
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 (opens in a new tab) 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:
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 zoo;
CREATE DATABASE
\c zoo
You are now connected to database "zoo" as user "postgres".
Create the table and add three animals:
CREATE TABLE animals (name text, legs integer);
CREATE TABLE
INSERT INTO animals (name, legs) VALUES ('penguin', 2);
INSERT 0 1
INSERT INTO animals (name, legs) VALUES ('zebra', 4);
INSERT 0 1
INSERT INTO animals (name, legs) VALUES ('spider', 8);
INSERT 0 1
Step 2: Select Every Column
SELECT * FROM animals;
name | legs
---------+------
penguin | 2
zebra | 4
spider | 8
(3 rows)
psql ends with the number of rows.
Step 3: Select One Column
SELECT name FROM animals;
name
---------
penguin
zebra
spider
(3 rows)
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 zoo;
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 (opens in a new tab) 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.
0 comments