SELECT retrieves rows and columns from one or more PostgreSQL tables, views, or sub-queries.
The SELECT statement returns a custom result set from tables, views, CTEs, or functions. Mastering it lets you filter, sort, join, group, and paginate data efficiently.
PostgreSQL evaluates SELECT in the order: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT/OFFSET. Knowing this helps you place clauses correctly and avoid logic errors.
SELECT [DISTINCT | DISTINCT ON (col)] column_list
FROM source
[WHERE condition]
[GROUP BY grouping_cols]
[HAVING group_condition]
[ORDER BY sort_cols [ASC|DESC] [NULLS FIRST|LAST]]
[LIMIT n] [OFFSET m]
[FOR {UPDATE | SHARE} [OF table_list]];
WHERE eliminates rows before grouping and projection. Combine comparison, logical, pattern-matching, and range operators for precise filters.
Example: WHERE amount > 100 AND status = 'paid'
returns only paid invoices above $100.
WHERE email ILIKE '%@example.com'
performs a case-insensitive search for company emails.
ORDER BY applies after SELECT. Sort by column index, name, alias, or expression: ORDER BY total DESC, created_at ASC
. Use NULLS FIRST|LAST
to control null placement.
LIMIT returns the first n rows; OFFSET skips m. Combine both for paging: LIMIT 20 OFFSET 40
fetches the third 20-row page.
GROUP BY collapses rows sharing the same key so aggregate functions can run. Every non-aggregated column in SELECT must appear in GROUP BY: SELECT country, COUNT(*) FROM users GROUP BY country
.
Use INNER, LEFT, RIGHT, or FULL joins to combine rows. Always qualify columns to avoid ambiguity: SELECT o.id, u.name FROM orders o JOIN users u ON u.id = o.user_id
.
Index columns used in WHERE, JOIN, and ORDER BY. Retrieve only needed columns. Avoid SELECT *. Filter early with WHERE. Prefer LIMIT when exploring. Use EXPLAIN to inspect plans.
Add LIMIT N
: SELECT * FROM logs ORDER BY ts DESC LIMIT 10;
Use SELECT DISTINCT col_list FROM table;
or group rows with MIN/MAX if you need deterministic picks.
Yes. CREATE TABLE new_tbl AS SELECT ...;
copies the result set’s structure and data.
It returns unnecessary columns, increases network load, and breaks apps if the schema changes. List only required columns instead.
Create appropriate indexes, avoid functions on indexed columns in WHERE, analyze tables, and use EXPLAIN to identify full scans or costly sorts.
Yes. Use UNION or UNION ALL to stack compatible result sets.