6 SELECT from a Table
Now that fruits has rows, you can read them. SELECT * returns every column; listing column names returns just those, in the order you list them. The result is unordered unless you add ORDER BY — even if it looks ordered today, it may not be tomorrow.
What you’ll learn
SELECT * FROM tablefor all columns- Selecting specific columns and controlling their order in the result
- Combining
SELECTwithWHEREandORDER BY - Why
SELECT *is fine for ad-hoc queries but risky in application code - Result column names and how to override them
Before this lesson, run psql -f source/create-table.sql -f source/insert.sql postgres in your scratch database. These are the files introduced in chapters 16 and 24; the table must exist before the SELECT lessons.
Example
Run this after create-table.sql and insert.sql. SELECT * returns every column in the physical column order. Listing columns gives you total control over the result shape, which matters when the data flows into application code that maps columns by position. AS renames a column in the output without changing anything in the table.
The space character is optional around * and around operators; the SQL parser is generous with whitespace. Multi-line queries are normal and encouraged for anything beyond two columns.
Run the example
To run:
Common pitfalls
SELECT * FROM big_table;will fetch every column of every row across the network — slow and wasteful. List the columns you actually need.- Output column names are not guaranteed unique.
SELECT id, id FROM fruitshas two columns both namedid— application drivers may not handle that gracefully. - In application code, prefer explicit columns over
SELECT *. When the schema adds a column, the shape ofSELECT *changes and may break code that assumes a particular column order or count.
When you’re exploring data, \x in psql toggles expanded display — each row prints one column per line. It is much easier to read a wide row that way.
Run SELECT * FROM fruits WHERE id > 100; to see only the generated rows. Then run SELECT name FROM fruits ORDER BY name; for alphabetical names. Then try SELECT id || ': ' || name AS label FROM fruits; to build a label column with the || string concatenation operator.
Downloads
SQL file: select-from-table.sql · All lesson files · Setup guide