SELECT (Query Rows)
Last updated: 2026-11-04
SELECT (Query Rows)
SELECT is the core command for reading data in PostgreSQL, retrieving rows from one or more tables (or views). It supports WHERE filtering, GROUP BY aggregation, HAVING group filtering, ORDER BY sorting, and LIMIT pagination — and nearly every query starts with it.
| Kind | command |
|---|---|
| Example Language | SQL |
📝 Syntax
SELECT [DISTINCT] <column or expression> [AS alias]
FROM <table> [AS alias]
[WHERE <condition>]
[GROUP BY <grouping expression>]
[HAVING <group condition>]
[ORDER BY <sort column> [ASC | DESC]]
[LIMIT <rows> [OFFSET <offset>]]
⚙️ Parameters
| FROM | The table or view the rows come from |
|---|---|
| WHERE | Row-level filter, applied before grouping |
| GROUP BY | Grouping key that sets the aggregation grain |
| HAVING | Filters groups; may reference aggregates |
| ORDER BY | Sort order, ascending by default |
| LIMIT / OFFSET | Caps the row count and skips leading rows |
Returns:A result set of zero or more rows, with columns defined by the select list. No match yields an empty result set (0 rows), not NULL.
▶ Example
Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.
Output:
DROP TABLE
CREATE TABLE
INSERT 0 5
name | dept | salary
------+-------+---------
Carol | sales | 15000.00
Alice | eng | 12000.00
Dave | sales | 11000.00
dept | headcount | avg_salary
------+-----------+-----------
sales | 2 | 13000.00
eng | 2 | 10500.00
📌 Key Points
- Clause evaluation order is FROM → WHERE → GROUP BY → HAVING → ORDER BY → LIMIT; WHERE filters rows before GROUP BY runs.
- ORDER BY puts NULLs last when ascending and first when descending; use NULLS FIRST / NULLS LAST to be explicit.
- Aggregates are not allowed in WHERE (aggregate functions are not allowed in WHERE) — filter groups with HAVING.
- LIMIT n OFFSET m pages through results; a bare OFFSET requires a LIMIT.
- SELECT * changes shape whenever the table changes; explicit column lists are more stable and index-friendly.
💡 Related Cases
More case studies coming soon.
📚 Related Reference
❓ FAQ
QWhat is the difference between WHERE and HAVING?
AWHERE filters rows before grouping, HAVING filters groups after aggregation; only HAVING may reference aggregates such as count() and sum().
QWhy can ORDER BY use a select alias but WHERE cannot?
AAn alias only exists after the select list is evaluated, and ORDER BY runs after that; WHERE runs before it, so it can only reference original columns.