menu
save_alt Download

SQL Language Cheat Sheet

Essential SQL commands and syntax reference for querying databases

📥 Download PDF Version

🔍 SELECT Basics

Retrieve data from tables by specifying which columns to return. Use DISTINCT to remove duplicates and AS for column aliases.
SELECT customer_id, name, email
FROM customers;

-- With alias and DISTINCT
SELECT DISTINCT country AS customer_country
FROM customers;

Key Points:

  • Use specific columns instead of * for better performance
  • DISTINCT removes duplicate rows
  • AS keyword creates column aliases
  • Column order in SELECT determines result order

WHERE Clause

Filter rows based on conditions using comparison operators. Combine multiple conditions with AND/OR for complex filtering.
SELECT name, price
FROM products
WHERE price > 100;

-- Multiple conditions
SELECT name, category
FROM products
WHERE category = 'Electronics'
  AND price <= 500;

Key Points:

  • Filters rows before returning results
  • Can combine multiple conditions with AND/OR
  • String values require single quotes
  • Operators: =, !=, <>, <, >, <=, >=

⚙️ Logical Operators

Combine multiple conditions using AND (all must be true), OR (at least one must be true), and NOT (negates condition).
-- AND operator
SELECT * FROM orders
WHERE status = 'shipped' AND total > 100;

-- OR operator
SELECT * FROM customers
WHERE country = 'USA' OR country = 'Canada';

-- NOT operator
SELECT * FROM products
WHERE NOT category = 'Discontinued';

Key Points:

  • AND has higher precedence than OR
  • Use parentheses to control evaluation order
  • NOT is equivalent to != or <>
  • Combine operators for complex logic

↕️ ORDER BY

Sort query results in ascending (ASC) or descending (DESC) order. Sort by multiple columns for complex ordering.
-- Single column sort
SELECT name, price
FROM products
ORDER BY price DESC;

-- Multiple columns
SELECT name, category, price
FROM products
ORDER BY category ASC, price DESC;

Key Points:

  • ASC is default if not specified
  • Sort by multiple columns (left to right priority)
  • Can sort by column not in SELECT list
  • NULL values sorted first or last (DB-dependent)

✂️ LIMIT / OFFSET

Limit the number of rows returned and skip rows using OFFSET. Essential for pagination and working with large result sets.
-- First 10 rows
SELECT name, price
FROM products
ORDER BY price DESC
LIMIT 10;

-- Pagination (skip first 20, get next 10)
SELECT name, price
FROM products
ORDER BY price DESC
LIMIT 10 OFFSET 20;

Key Points:

  • Essential for pagination
  • Combine with ORDER BY for consistent results
  • OFFSET starts at 0 (first row)
  • Note: SQL Server uses TOP instead of LIMIT

*️⃣ Pattern Matching (LIKE)

Match text patterns using wildcards: % matches any sequence of characters, _ matches a single character.
-- Starts with 'John'
SELECT name, email
FROM customers
WHERE name LIKE 'John%';

-- Contains 'smith'
SELECT name FROM customers
WHERE name LIKE '%smith%';

-- Exact pattern (5 characters starting with 'A')
SELECT code FROM products
WHERE code LIKE 'A____';

Key Points:

  • % matches zero or more characters
  • _ matches exactly one character
  • Case sensitivity depends on database collation
  • Can use NOT LIKE for exclusion

↔️ Range & Set (BETWEEN, IN)

Filter by ranges using BETWEEN (inclusive) or match values in a list using IN. More efficient than multiple OR conditions.
-- BETWEEN (inclusive)
SELECT name, price
FROM products
WHERE price BETWEEN 50 AND 100;

-- IN operator
SELECT name, country
FROM customers
WHERE country IN ('USA', 'Canada', 'Mexico');

-- NOT IN
SELECT name FROM products
WHERE category NOT IN ('Discontinued', 'Draft');

Key Points:

  • BETWEEN includes both boundary values
  • IN is cleaner than multiple OR conditions
  • Can use IN with subqueries
  • BETWEEN works with dates and strings

NULL Handling

Work with NULL values using IS NULL and IS NOT NULL. Use COALESCE to provide default values for NULL columns.
-- Find NULL values
SELECT name, phone
FROM customers
WHERE phone IS NULL;

-- Exclude NULL values
SELECT name, email
FROM customers
WHERE email IS NOT NULL;

-- Provide default value
SELECT name, COALESCE(phone, 'No phone') AS contact
FROM customers;

Key Points:

  • Cannot use = or != with NULL
  • Must use IS NULL or IS NOT NULL
  • COALESCE returns first non-NULL argument
  • NULL in math operations results in NULL

Σ Aggregate Functions

Perform calculations on sets of rows: COUNT, SUM, AVG, MIN, MAX. Aggregates ignore NULL values (except COUNT(*)).
-- Basic aggregates
SELECT
  COUNT(*) AS total_orders,
  SUM(amount) AS total_revenue,
  AVG(amount) AS avg_order_value,
  MIN(amount) AS smallest_order,
  MAX(amount) AS largest_order
FROM orders;

-- COUNT variations
SELECT COUNT(*) AS all_rows,
       COUNT(email) AS rows_with_email,
       COUNT(DISTINCT country) AS unique_countries
FROM customers;

Key Points:

  • COUNT(*) includes all rows (even with NULL)
  • COUNT(column) excludes NULL values
  • COUNT(DISTINCT column) counts unique values
  • SUM/AVG only work with numeric types

GROUP BY / HAVING

Group rows by column values and apply aggregate functions. Use HAVING to filter groups (like WHERE for groups).
-- Group by single column
SELECT country, COUNT(*) AS customer_count
FROM customers
GROUP BY country
ORDER BY customer_count DESC;

-- Group by multiple columns with HAVING
SELECT category, status, AVG(price) AS avg_price
FROM products
GROUP BY category, status
HAVING AVG(price) > 50;

Key Points:

  • All non-aggregate SELECT columns must be in GROUP BY
  • WHERE filters rows before grouping
  • HAVING filters groups after aggregation
  • Can use aggregate functions in HAVING clause

🔗 Joins (Quick Reference) SEE DETAILED GUIDE

Combine data from multiple tables based on related columns. INNER JOIN returns matches only, LEFT/RIGHT preserve one side.
-- INNER JOIN (most common)
SELECT orders.id, customers.name, orders.amount
FROM orders
INNER JOIN customers
  ON orders.customer_id = customers.id;

-- LEFT JOIN (all orders, even without customer)
SELECT orders.id, customers.name
FROM orders
LEFT JOIN customers
  ON orders.customer_id = customers.id;

Key Points:

  • INNER JOIN is most common (can write as just JOIN)
  • LEFT/RIGHT JOINs preserve all rows from one table
  • Use ON clause to specify join condition

📚 Full guide: SQL JOIN Cheat Sheet with 7 JOIN types and visual diagrams

Subqueries

Queries within queries for complex filtering and calculations. Use with IN, EXISTS, or as scalar values.
-- Subquery with IN
SELECT name, price
FROM products
WHERE category_id IN (
  SELECT id FROM categories
  WHERE name = 'Electronics'
);

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

-- Scalar subquery
SELECT name, price,
  price - (SELECT AVG(price) FROM products) AS price_diff
FROM products;

Key Points:

  • IN subquery returns multiple values
  • EXISTS checks for existence (efficient)
  • Scalar subquery returns single value
  • Correlated subquery references outer query

Need a Better Way to Write SQL?

Beekeeper Studio is a modern, intuitive SQL editor with autocomplete, query history, and support for 15+ databases.

Try Beekeeper Studio Free