Skip to main content
CodingMarble

Interview questions and cheat sheets

SQL Cheat Sheet for Beginners

This cheat sheet teaches the SQL you use every week, task by task, with every query written against one small customers and orders schema. It uses standard SQL and points out where MySQL, PostgreSQL, SQL Server and SQLite differ.

By CodingMarble · Published · 4 min read

Two colleagues discussing ideas at a whiteboard
Photo: ThisisEngineering on Unsplash

The example schema

Every query on this page uses two tables. customers holds one row per person, and orders holds one row per purchase, linked by customer_id. A customer may have no orders, and that is what makes the join examples interesting.

SQL· Auto-increment syntax differs by database, so it is left out here.
CREATE TABLE customers (
  id         INTEGER PRIMARY KEY,
  name       VARCHAR(100) NOT NULL,
  city       VARCHAR(60),
  created_at DATE NOT NULL
);

CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER NOT NULL REFERENCES customers(id),
  total       DECIMAL(10,2) NOT NULL,
  status      VARCHAR(20) NOT NULL,   -- 'new', 'paid', 'cancelled'
  ordered_at  DATE NOT NULL
);

Keywords are case-insensitive, strings use single quotes, and a statement ends with a semicolon. Double quotes usually mean an identifier, not a string. The primary key makes each row uniquely identifiable, the REFERENCES clause is a foreign key that stops an order from pointing at a customer who does not exist, and NOT NULL forbids empty values in that column.

Reading data: SELECT, WHERE, ORDER BY, LIMIT

SELECT chooses columns, FROM names the table, WHERE filters rows before anything is grouped, ORDER BY sorts the result, and a row limit trims it. Avoid SELECT * in application code, because adding a column later changes your results silently.

SQL
SELECT id, name, city
FROM customers
WHERE city = 'Pune' AND created_at >= '2026-01-01'
ORDER BY name ASC
LIMIT 10;
  • LIMIT 10 works in PostgreSQL, MySQL and SQLite. SQL Server uses SELECT TOP 10, and the standard form is FETCH FIRST 10 ROWS ONLY.
  • IN (...) matches a list, BETWEEN matches an inclusive range, and LIKE 'A%' matches a text pattern where percent means any characters.
  • DISTINCT removes duplicate rows from the result, for example SELECT DISTINCT city FROM customers.
  • Without ORDER BY the database may return rows in any order, so never rely on insertion order.
  • OFFSET skips rows and pairs with LIMIT for paging, but large offsets get slow because the database still reads the skipped rows.
  • Column aliases written with AS, such as total AS order_total, make results easier to read, and most databases let ORDER BY use the alias.

Evaluation order matters when a query surprises you. Logically the database processes FROM and JOIN first, then WHERE, GROUP BY, HAVING, SELECT and finally ORDER BY and the row limit. That is why a column alias defined in SELECT cannot be used in WHERE in most databases.

Aggregates, GROUP BY and HAVING

COUNT, SUM, AVG, MIN and MAX collapse many rows into one value. GROUP BY computes them once per group. WHERE filters rows before grouping, while HAVING filters the groups afterwards, so conditions on an aggregate must go in HAVING.

SQL
SELECT customer_id,
       COUNT(*)   AS order_count,
       SUM(total) AS spent
FROM orders
WHERE status = 'paid'
GROUP BY customer_id
HAVING COUNT(*) >= 3
ORDER BY spent DESC;

Every selected column that is not inside an aggregate must appear in GROUP BY. COUNT(*) counts rows, while COUNT(column) skips NULLs in that column. COUNT(DISTINCT column) counts unique values. To group by month you need a date function, and its name differs: DATE_TRUNC in PostgreSQL, DATE_FORMAT in MySQL, strftime in SQLite and FORMAT or DATEPART in SQL Server.

Joins

A join combines rows from two tables on a condition. The join type decides what happens to rows with no match. Table aliases such as c and o keep the query short, and you should prefix columns with them whenever both tables have a column of the same name, like id.

  • INNER JOIN keeps only customers who have at least one matching order.
  • LEFT JOIN keeps every customer and fills order columns with NULL when there is no order.
  • RIGHT JOIN is the mirror image and is rarely needed, since you can swap the table order and use LEFT JOIN.
  • FULL OUTER JOIN keeps unmatched rows from both sides; MySQL and SQLite support it only in recent versions or through a UNION workaround.
SQL
-- Customers with their orders, including customers who never ordered
SELECT c.name, o.id AS order_id, o.total
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id;

-- Customers who have never ordered
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;

A condition on the right table placed in WHERE, such as o.status = 'paid', turns a LEFT JOIN into an inner join. Put it in the ON clause if you want to keep unmatched customers.

Subqueries and CTEs

A subquery is a query inside another query. A common table expression, written with WITH, gives a subquery a name so a long query reads from top to bottom. Both are supported by all current major databases.

SQL
WITH paid AS (
  SELECT customer_id, SUM(total) AS spent
  FROM orders
  WHERE status = 'paid'
  GROUP BY customer_id
)
SELECT c.name, paid.spent
FROM customers c
JOIN paid ON paid.customer_id = c.id
WHERE paid.spent > (SELECT AVG(total) FROM orders);

Use EXISTS when you only need to know whether a related row is present, as in WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id). Prefer NOT EXISTS over NOT IN when the subquery can return NULL, because NOT IN then matches nothing.

Changing data safely: INSERT, UPDATE, DELETE

INSERT adds rows, UPDATE changes existing ones and DELETE removes them. UPDATE and DELETE without a WHERE clause affect every row in the table, and in many setups there is no undo.

SQL
INSERT INTO customers (id, name, city, created_at)
VALUES (101, 'Asha Rao', 'Pune', '2026-11-01');

-- Step 1: run the same WHERE as a SELECT and check the rows
SELECT * FROM orders WHERE status = 'new' AND ordered_at < '2026-01-01';

-- Step 2: only then change them
UPDATE orders SET status = 'cancelled'
WHERE status = 'new' AND ordered_at < '2026-01-01';
  • Always write the SELECT first, read the row count, then convert it into UPDATE or DELETE with the identical WHERE clause.
  • Wrap the change in a transaction while you check the affected row count, as shown below.
  • Take a backup before any bulk change on production data.
  • TRUNCATE TABLE empties a whole table quickly, and in some databases it cannot be rolled back.

Indexes and transactions

An index is a sorted lookup structure on one or more columns. It speeds up WHERE, JOIN and ORDER BY on those columns, at the cost of extra storage and slower writes. Primary keys are indexed automatically, but foreign key columns usually are not in PostgreSQL, so index customer_id if you join on it often.

SQL
CREATE INDEX idx_orders_customer ON orders (customer_id);

BEGIN;                                   -- START TRANSACTION in MySQL
UPDATE orders SET status = 'paid' WHERE id = 5001;
-- check the affected row count here
COMMIT;                                  -- or ROLLBACK; to undo

A transaction groups statements so they succeed or fail together. Indexes will not help a query that wraps the column in a function, such as WHERE LOWER(name) = 'asha', or a LIKE pattern that starts with a wildcard. Use EXPLAIN to see whether the database used the index.

NULL and common beginner mistakes

NULL means unknown, not zero or empty text. Any comparison with NULL gives unknown, so city = NULL never matches; write city IS NULL. COALESCE(city, 'Unknown') returns the first non-NULL argument, and aggregates other than COUNT(*) ignore NULLs.

  • Putting an aggregate in WHERE instead of HAVING causes an error.
  • Selecting a column that is not in GROUP BY fails in standard SQL, though older MySQL settings allowed it and returned arbitrary values.
  • Joining without a correct ON condition produces a cross product, where every row pairs with every other row.
  • Counting after a join inflates numbers when the joined table has several matching rows; use COUNT(DISTINCT c.id) to count customers.
  • Comparing dates stored as text works only with ISO format, year first.

Need this built properly for your business?

CodingMarble is a remote studio in India that builds websites, apps and games on fixed packages with the scope written down before payment. Try the free tools we run, or start a project when you are ready.