SQL Querying Basics
10 examples to get you started with SQL querying in PostgreSQL - 7 basic and 3 intermediate.
Search across all documentation pages
10 examples to get you started with SQL querying in PostgreSQL - 7 basic and 3 intermediate.
Working app.customers table from PostgreSQL Basics or equivalent sample data.
# Local dev with Docker (PostgreSQL 18)
docker run -d --name pg18 -e POSTGRES_PASSWORD=dev -p 5432:5432 postgres:18
psql postgres://postgres:dev@localhost:5432/postgresList the columns your API or report needs.
SELECT id, email, created_at
FROM app.customers
WHERE id = 1;Predicates reduce rows before sort and join.
SELECT id, email
FROM app.customers
WHERE created_at >= now() - interval '30 days';ORDER BY defines deterministic ordering.
SELECT id, email, created_at
FROM app.customers
ORDER BY created_at DESC, id DESC;Cap rows returned to clients.
SELECT id, email
FROM app.customers
ORDER BY id
LIMIT 50 OFFSET 100;Remove duplicate combinations.
SELECT DISTINCT email
FROM app.customers;Compute derived values in SELECT.
SELECT email, lower(email) AS email_normalized,
created_at::date AS signup_date
FROM app.customers;One clause per line for reviewability.
SELECT
c.id,
c.email,
c.created_at
FROM app.customers AS c
WHERE c.email LIKE '%@example.com'
ORDER BY c.created_at DESC
LIMIT 20;CASE and COALESCE in projections.
SELECT id,
CASE WHEN email LIKE '%@example.com' THEN 'corp' ELSE 'other' END AS segment
FROM app.customers;Single-value subselect in SELECT list.
SELECT id, email,
(SELECT count(*) FROM app.orders o WHERE o.customer_id = c.id) AS order_count
FROM app.customers c;See planner choices before tuning.
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT id FROM app.customers WHERE email = 'ada@example.com';Stack versions: This page was written for PostgreSQL 18.4 (stable 18, maintenance 17), pgvector 0.8+, PgBouncer 1.x, Patroni 3.x, and PostGIS 3.5+.
Reviewed by Chris St. John·Last updated Jul 19, 2026