Sub topic 10
Running your first SELECT
This chapter assumes you have PostgreSQL running, can open psql, and have created the books table in firstdb with the three rows from the previous chapter. If you are not connected to firstdb, run \c firstdb first. Check the prompt: it should read firstdb=#.
What SELECT does
SELECT reads data. It never changes a table, so you can run it as often as you like. A query that returns rows is a result set. The result set is a temporary table that exists only for that query. The stored table is untouched.
The simplest useful form names the columns you want and the table to read them from:
SELECT * FROM books;The * means "all columns". psql prints the result as an aligned text table:
id | title | author | published_year
----+-------------+----------------+----------------
1 | Dune | Frank Herbert | 1965
2 | Neuromancer | William Gibson | 1984
3 | Emma | Jane Austen | 1815
(3 rows)Note these details of the output:
- The header row shows column names, and the footer reports the row count.
- Text is left-aligned and numbers are right-aligned.
- A
NULLvalue (a missing value) prints as an empty cell. Without theNULL, an empty cell would look the same as an empty string. - The
idvalues were generated for you by the identity column.
The parts of a query
A statement ends with a semicolon. psql does not send the statement to the server until it sees one. If you forget it, the prompt changes to show that the statement is unfinished:
firstdb=# SELECT * FROM books
firstdb-#The -# prompt means "still waiting". Type ; and press Enter to finish the statement. Keywords such as SELECT and FROM are case-insensitive. Most people write them in uppercase so they stand out from table and column names.
You can also spread a statement across lines. The line breaks are only for readability:
SELECT title,
author
FROM books;Choosing columns
Listing columns by name returns only those columns, in the order you write them:
SELECT title, author FROM books; title | author
-------------+----------------
Dune | Frank Herbert
Neuromancer | William Gibson
Emma | Jane Austen
(3 rows)You can reorder columns freely. SELECT author, title FROM books; is valid and swaps them in the output.
SELECT * is convenient while you explore. In application code it is risky, because the result changes whenever someone adds or reorders a column in the table. It also fetches data you may not need. Name the columns you want in anything you plan to keep.
Expressions and aliases
A select list can contain expressions, not only column names. The server computes them once per row:
SELECT title, 2026 - published_year AS years_ago
FROM books; title | years_ago
-------------+-----------
Dune | 61
Neuromancer | 42
Emma | 211
(3 rows)AS years_ago is an alias. It gives the computed column a name. Without it, PostgreSQL labels the column ?column?, which is hard to read. AS is optional but makes the intent clear.
An alias containing spaces or capital letters needs double quotes:
SELECT title AS "Book title" FROM books;Aliases exist only in the result. They do not rename anything in the table. You also cannot use a select-list alias in a WHERE clause. The next section explains why.
SELECT without a table
FROM is optional in PostgreSQL. A query with no FROM clause produces a single row. It is a quick way to test expressions and functions:
SELECT 1 + 1 AS sum, upper('dune') AS shout, current_date AS today;You used this form earlier with SELECT version();. Here version() is a function call. Functions work in the select list just like columns.
Counting and limiting rows
An aggregate function collapses many rows into one value. count(*) returns the number of rows:
SELECT count(*) FROM books; count
-------
3
(1 row)LIMIT caps how many rows come back. This is useful on large tables, where SELECT * could print millions of lines:
SELECT title FROM books LIMIT 2;How the server reads a query
You write SELECT first, but the server does not process it first. It works in a logical order that explains several rules, including the alias rule above.
The table is chosen first, then rows are filtered, and only after that are columns and aliases computed. A WHERE clause runs before the aliases exist, so it cannot refer to them. ORDER BY runs after, so it can. The real executor may reorder steps for speed, but the results always match this logical order.
Reading results in psql
Some psql settings help when output gets wide or you are checking details.
\xtoggles expanded display, which prints each row as a vertical list of column/value pairs. Use it when a row is wider than your terminal. Run\xagain to turn it off.\timingprints how long each statement took.\pset null '(null)'makesNULLvalues visible instead of blank.
Try them:
\x
SELECT * FROM books LIMIT 1;
\x-[ RECORD 1 ]--+--------------
id | 1
title | Dune
author | Frank Herbert
published_year | 1965Common errors
Each of these is easy to trigger, and each message points at the cause.
SELECT * FROM book;ERROR: relation "book" does not exist
LINE 1: SELECT * FROM book;
^PostgreSQL calls tables "relations" in this message. The name is misspelled here: it should be books. If the spelling is right, you may be connected to the wrong database. Check the prompt, or run SELECT current_database();.
SELECT name FROM books;ERROR: column "name" does not existThe table has title and author, not name. Run \d books to see the real column names.
SELECT * FROM books WHERE title = "Dune";ERROR: column "Dune" does not existIn SQL, single quotes mark text values ('Dune') and double quotes mark identifiers such as column names. Double quotes made PostgreSQL look for a column called Dune.
Summary of forms
| Goal | Statement |
|---|---|
| All rows, all columns | `SELECT * FROM books;` |
| Chosen columns | `SELECT title, author FROM books;` |
| Computed column with a name | `SELECT 2026 - published_year AS years_ago FROM books;` |
| Test an expression | `SELECT 1 + 1;` |
| Number of rows | `SELECT count(*) FROM books;` |
| First few rows | `SELECT title FROM books LIMIT 2;` |
Exercise
Write a query that returns each book's title and author, with the columns labelled "Book" and "Writer" (capital first letters), limited to 2 rows. Why might the two rows you get differ from run to run in a real application?
Show answer
SELECT title AS "Book", author AS "Writer" FROM books LIMIT 2; The aliases need double quotes to keep their capitals. Without an ORDER BY clause, PostgreSQL does not guarantee row order, so LIMIT 2 returns any two rows, and which two can change after updates or other changes to storage.
Exercise
You run SELECT * FROM books; and see the prompt change to firstdb-# with no output. What happened, and how do you fix it?
Show answer
The statement has no terminating semicolon, so psql is waiting for more input. Type ; and press Enter to send it.