Querying

Introduction

SQL reads and changes relational data. This reference covers queries, joins, inserts, updates, schema changes, and transactions. Examples use portable syntax unless noted.

Select columns

SELECT * FROM customers;
SELECT id, name FROM customers;
SELECT name AS customer, email
FROM customers;
SELECT DISTINCT customer_id FROM orders;

* reads every column and AS renames an output column. DISTINCT drops duplicate rows.

See: PostgreSQL SELECT

Filter rows

SELECT * FROM orders
WHERE total >= 50 AND status = 'paid';

SELECT * FROM customers
WHERE name LIKE 'A%' OR email IS NULL;

SELECT * FROM orders
WHERE customer_id IN (1, 2, 3);

SELECT * FROM orders
WHERE placed_at BETWEEN '2026-01-01'
  AND '2026-03-31';

AND and OR combine conditions; IN, BETWEEN, LIKE, and IS NULL cover common tests. Use IS NULL, never = NULL.

See: PostgreSQL WHERE

Sort and limit

SELECT id, total FROM orders
ORDER BY total DESC, id ASC;

SELECT name FROM customers
ORDER BY name
LIMIT 10;

SELECT name FROM customers
ORDER BY name
LIMIT 10 OFFSET 20;

ORDER BY sorts, DESC reverses it, and LIMIT caps rows. OFFSET skips ahead for paging; SQL Server uses OFFSET ... FETCH.

See: PostgreSQL LIMIT

Group and aggregate

SELECT customer_id,
       COUNT(*) AS orders,
       SUM(total) AS spent,
       AVG(total) AS average
FROM orders
GROUP BY customer_id
HAVING SUM(total) > 100
ORDER BY spent DESC;

GROUP BY makes one row per key; aggregates collapse each group. WHERE filters rows before grouping, HAVING filters groups after.

See: PostgreSQL GROUP BY

Joins and subqueries

Join tables

SELECT c.name, o.order_id, o.total
FROM customers AS c
JOIN orders AS o
  ON o.customer_id = c.id;

SELECT c.name, o.order_id, o.total
FROM customers AS c
LEFT JOIN orders AS o
  ON o.customer_id = c.id;

JOIN keeps matching rows; LEFT JOIN keeps every left row and fills missing right columns with NULL.

See: PostgreSQL joins

Subqueries

SELECT name FROM customers
WHERE id IN (
  SELECT customer_id FROM orders
  WHERE total > 100
);

SELECT name FROM customers AS c
WHERE EXISTS (
  SELECT 1 FROM orders AS o
  WHERE o.customer_id = c.id
);

IN compares against a list; EXISTS stops at the first match. Both can replace a join when you only need one side.

See: PostgreSQL subqueries

Changing rows

Insert rows

INSERT INTO customers (name, email)
VALUES ('Ada', 'ada@example.com');

INSERT INTO customers (name, email)
VALUES ('Bob', 'bob@example.com'),
       ('Cy', 'cy@example.com');

INSERT INTO archived_customers (name)
SELECT name FROM customers
WHERE active = FALSE;

List columns explicitly so defaults and generated IDs still work. INSERT ... SELECT copies rows from another query.

See: PostgreSQL INSERT

Update rows

UPDATE accounts
SET balance = balance + 10
WHERE id = 1;

UPDATE accounts
SET balance = 0
WHERE customer_id = 42;

SET assigns new values. Always add WHERE unless you mean every row.

See: PostgreSQL UPDATE

Delete rows

DELETE FROM orders
WHERE placed_at < '2025-01-01';

DELETE FROM orders;

DELETE removes matching rows; without WHERE it empties the table. TRUNCATE is faster but cannot filter.

See: PostgreSQL DELETE

Transactions

BEGIN;
INSERT INTO accounts (id, balance)
VALUES (1, 10);
COMMIT;

BEGIN starts a transaction; COMMIT saves it and ROLLBACK discards it. Keep transactions short.

See: PostgreSQL transactions

Defining tables

Create table

CREATE TABLE accounts (
  id INTEGER PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  balance NUMERIC(12, 2) NOT NULL
    DEFAULT 0 CHECK (balance >= 0),
  customer_id INTEGER
    REFERENCES customers (id)
    ON DELETE CASCADE,
  created_at TIMESTAMP
    DEFAULT CURRENT_TIMESTAMP
);

PRIMARY KEY, UNIQUE, NOT NULL, CHECK, and REFERENCES reject invalid rows. ON DELETE CASCADE removes child rows with their parent. Auto-increment differs: SQLite INTEGER PRIMARY KEY, PostgreSQL GENERATED ALWAYS AS IDENTITY, MySQL AUTO_INCREMENT.

See: PostgreSQL CREATE TABLE

Alter table

ALTER TABLE accounts
  ADD COLUMN last_login TIMESTAMP;

ALTER TABLE accounts
  RENAME COLUMN email TO login;

ALTER TABLE accounts
  ALTER COLUMN balance TYPE NUMERIC(14, 2);

ALTER TABLE accounts
  DROP COLUMN last_login;

ADD, RENAME, ALTER COLUMN, and DROP COLUMN change a table in place. SQLite lacks ALTER COLUMN TYPE; MySQL uses MODIFY COLUMN.

See: PostgreSQL ALTER TABLE

Indexes

CREATE INDEX orders_customer_id_idx
  ON orders (customer_id);

CREATE UNIQUE INDEX customers_email_idx
  ON customers (email);

DROP INDEX orders_customer_id_idx;

Indexes speed up lookups and sorts; CREATE UNIQUE INDEX also enforces uniqueness. MySQL drops with DROP INDEX name ON table.

See: PostgreSQL CREATE INDEX

Drop and truncate

DROP TABLE accounts;
TRUNCATE TABLE orders;

DROP TABLE deletes the table and its data; TRUNCATE clears rows faster but keeps the table. SQLite has no TRUNCATE: use DELETE FROM.

See: PostgreSQL TRUNCATE

Also see

0 Comments for this cheatsheet. Write yours!