Stage 3. SELECT, Filtering, Sorting, and Result Shape

In this topic, syntax alone is not enough. You need execution logic. A read query works like a pipeline: choose columns, choose source table, filter rows, sort result, limit output size.

SELECT flow diagram

Base skeleton:

SELECT ...
FROM ...
WHERE ...
ORDER BY ...
LIMIT ...;

Below, each block is explained in detail.

Block 1. SELECT: output shape and why it matters

SELECT defines the final response structure.

SELECT id, user_id, amount, status, created_at
FROM orders;

Why explicit columns matter:

  1. Less unnecessary data transfer.
  2. Clear API/report contract.
  3. Lower risk of accidental sensitive-field exposure.

Common beginner mistake: using SELECT * everywhere. Acceptable for quick debugging, not ideal for production endpoints.

Aliases in SELECT

SELECT
  id AS order_id,
  amount AS order_amount
FROM orders;

Aliases improve output readability for frontend and DTO mapping.

Block 2. WHERE: what conditions are and how filtering works

WHERE filters rows and answers: “Which records should remain?”

SELECT id, amount, status
FROM orders
WHERE status = 'PAID';

Only paid orders remain.

Combining conditions

SELECT id, user_id, amount, status, created_at
FROM orders
WHERE status = 'PAID'
  AND amount >= 500
  AND created_at >= DATE '2026-05-01';

All conditions must be true.

Alternative with OR and IN:

WHERE status = 'PAID' OR status = 'SHIPPED'
WHERE status IN ('PAID', 'SHIPPED')

WHERE and NULL

-- wrong
WHERE paid_at = NULL

-- correct
WHERE paid_at IS NULL

WHERE runs before sorting and before LIMIT, so filtering strongly affects performance and result size.

Block 3. ORDER BY: why sorting is critical

ORDER BY defines row order. Without it, order is not guaranteed.

SELECT id, amount, created_at
FROM orders
WHERE status = 'PAID'
ORDER BY created_at DESC;

DESC = newest first, ASC = oldest first.

Why one sort key is often not enough

If several rows have the same created_at, order can be unstable. Add a tie-breaker:

ORDER BY created_at DESC, id DESC

This is essential for stable pagination.

LIMIT: output size control

LIMIT caps number of returned rows.

SELECT id, user_id, amount, status, created_at
FROM orders
WHERE status = 'PAID'
ORDER BY created_at DESC, id DESC
LIMIT 5;

Why LIMIT is useful:

  • protects API from oversized responses;
  • reduces network and client load;
  • keeps list behavior predictable.

Full query walkthrough

SELECT id, user_id, amount, status, created_at
FROM orders
WHERE status = 'PAID'
ORDER BY created_at DESC, id DESC
LIMIT 5;

Logical execution:

  1. Read from orders.
  2. Keep only PAID rows.
  3. Sort newest to oldest.
  4. Break ties by id.
  5. Return first 5 rows.

Example output

id user_id amount status created_at
15 2 900.00 PAID 2026-05-10 12:15
14 1 1200.00 PAID 2026-05-10 11:01
12 2 700.00 PAID 2026-05-10 10:40
9 1 450.00 PAID 2026-05-10 10:05
7 3 300.00 PAID 2026-05-10 09:58

Common beginner mistakes

  1. SELECT * instead of explicit columns.
  2. No ORDER BY for user-facing lists.
  3. Wrong NULL check (= NULL instead of IS NULL).
  4. Too broad WHERE conditions.
  5. Missing LIMIT on large datasets.
Glossary
table
A database structure that stores data in rows and columns.
row
One record inside a database table.
column
A named field in a database table that stores one kind of value.
schema
The structure that defines database objects such as tables, columns, relationships, and constraints.
primary key
A column or group of columns that uniquely identifies each row in a table.
foreign key
A column or group of columns that points to a primary key in another table.
relationship
A connection between data entities, usually represented through keys or object references.
entity
A domain object or persistent class that represents something with identity.
attribute
A property of an entity, usually mapped to a column or field.
aggregate function
A SQL function that calculates one value from many rows, such as count, sum, or average.
index
A data structure that helps a database find rows faster without scanning the whole table.
selectivity
A measure of how well a column or condition narrows data to a smaller result set.
normalization
The process of organizing relational data to reduce duplication and protect consistency.
transaction
A group of operations treated as one unit that should complete fully or not apply at all.
ACID
The database transaction guarantees of atomicity, consistency, isolation, and durability.
isolation level
A database setting that controls how concurrent transactions see each other's changes.
lock
A database or concurrency mechanism that restricts access to shared data while work is in progress.
deadlock
A situation where operations wait on each other in a cycle and cannot continue without intervention.
query plan
The database engine's chosen strategy for executing a query.
EXPLAIN
A SQL command that shows the query plan selected by the database.
sequential scan
A query operation that reads table rows one by one instead of using a targeted index lookup.