Reading Data with SELECT
Filter, order, rename, and limit rows in a prepared PostgreSQL query.
database, sql, postgresql, select, filter, orderAsk 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:
| book | pages |
|---|---|
| Tide | 200 |
| Kite | 120 |
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
- Source (current)
- Filter
- Rank
- Keep two
- Display
| id | title | pages |
|---|---|---|
| 1 | Kite | 120 |
| 2 | Oak | NULL |
| 3 | Tide | 200 |
| 4 | Fern | 120 |
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.
