Reading preferences
Concept

Reading Data with SELECT

Filter, order, rename, and limit rows in a prepared PostgreSQL query.

database, sql, postgresql, select, filter, order

Ask a question of a table

SELECT chooses output columns. FROM names the source, WHERE filters rows, ORDER BY specifies their result order, and LIMIT caps how many are returned. An alias gives an output column a label without changing the table. These operations read data; this query does not modify the source.

SQL illustration

Run this setup in a separate PostgreSQL session if you want to experiment. Use a fresh session with no transaction already open. It creates a temporary table containing only fictional data:

BEGIN;
CREATE TEMP TABLE books (
  id integer PRIMARY KEY,
  title text NOT NULL,
  pages integer
);
INSERT INTO books (id, title, pages) VALUES
  (1, 'Kite', 120), (2, 'Oak', NULL),
  (3, 'Tide', 200), (4, 'Fern', 120);
COMMIT;
SELECT title AS book, pages
FROM books
WHERE pages >= 100
ORDER BY pages DESC, id ASC
LIMIT 2;

Prepared result — not live execution:

bookpages
Tide200
Kite120

Oak's NULL page count makes the comparison unknown, so WHERE does not keep it. Tide is first by descending page count. Kite and Fern both have 120 pages; ascending id breaks the tie, so Kite is second. The limit returns those two rows. The alias book changes only the result's heading.

See the reasoning

Follow a SELECT

Follow one way to reason about the result, not the database's execution order. This is prepared; Intuvo does not run SQL.

Start with the source

FROM books

A way to reason about this result
  1. Source (current)
  2. Filter
  3. Rank
  4. Keep two
  5. Display
idtitlepages
1Kite120
2OakNULL
3Tide200
4Fern120

The query starts from the four fictional books.

Read safely and deliberately

Without ORDER BY, row order is not guaranteed. If a limit matters, use ordering that resolves ties, for example a unique ID. Use IS NULL to find unknown page counts and IS NOT NULL to exclude them. AND, OR, and parentheses combine conditions; check their meaning before relying on a result. Use fictional or authorised data rather than copying private data into demonstrations. Querying large tables can still consume resources even when the result is limited.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. Which rows does WHERE pages >= 100 keep?
2. What does title AS book change in this query?
3. Why order by pages descending and then id ascending?
4. How can you find rows with no known page count?

References and further reading