SQL Cheatsheet

SELECT

Use this SQL reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Basic SELECT Syntax

-- All columns
SELECT * FROM users;

-- Specific columns
SELECT id, first_name, email FROM users;

-- With table alias
SELECT u.id, u.email FROM users u;
SELECT u.id, u.email FROM users AS u;

Column Expressions and Aliases

-- Arithmetic in SELECT
SELECT price, qty, price * qty AS total FROM order_items;

-- String expressions
SELECT first_name || ' ' || last_name AS full_name FROM users;
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM users;

-- Conditional expressions
SELECT
    name,
    CASE WHEN score >= 90 THEN 'A'
         WHEN score >= 80 THEN 'B'
         WHEN score >= 70 THEN 'C'
         ELSE 'F'
    END AS grade
FROM students;

-- Alias without AS (legal but avoid for clarity)
SELECT first_name name FROM users;

-- Aliases can be used in ORDER BY but NOT in WHERE or HAVING
SELECT price * qty AS total FROM order_items ORDER BY total DESC;

DISTINCT

-- Remove duplicate rows
SELECT DISTINCT country FROM customers;

-- DISTINCT across multiple columns (combination must be unique)
SELECT DISTINCT country, city FROM customers;

-- COUNT(DISTINCT col)
SELECT COUNT(DISTINCT country) FROM customers;

ORDER BY

-- Ascending (default)
SELECT * FROM products ORDER BY price ASC;
SELECT * FROM products ORDER BY price;

-- Descending
SELECT * FROM products ORDER BY price DESC;

-- Multiple columns: primary sort, then secondary
SELECT * FROM employees ORDER BY department ASC, salary DESC;

-- By column position (1-based)
SELECT id, name, price FROM products ORDER BY 3 DESC;

-- By expression
SELECT *, price * qty AS total FROM order_items ORDER BY price * qty DESC;

-- NULL placement
SELECT * FROM users ORDER BY last_login ASC NULLS LAST;
SELECT * FROM users ORDER BY last_login DESC NULLS FIRST;

LIMIT and OFFSET

-- First N rows
SELECT * FROM products ORDER BY price LIMIT 10;

-- Pagination: skip M rows, take N
SELECT * FROM products ORDER BY id LIMIT 10 OFFSET 20;   -- page 3 (0-indexed)

-- SQL Server / older syntax
SELECT TOP 10 * FROM products ORDER BY price;
SELECT * FROM products ORDER BY price FETCH FIRST 10 ROWS ONLY;

-- Random sample (PostgreSQL)
SELECT * FROM users ORDER BY RANDOM() LIMIT 5;
-- Random sample (MySQL)
SELECT * FROM users ORDER BY RAND() LIMIT 5;

Scalar Functions in SELECT

String Functions

FunctionDescriptionExample
UPPER(s)UppercaseUPPER('hello')'HELLO'
LOWER(s)LowercaseLOWER('HELLO')'hello'
LENGTH(s)Character countLENGTH('hello')5
TRIM(s)Strip leading/trailing spacesTRIM(' hi ')'hi'
LTRIM(s)Strip leading spacesLTRIM(' hi')'hi'
RTRIM(s)Strip trailing spacesRTRIM('hi ')'hi'
SUBSTR(s,pos,len)SubstringSUBSTR('hello',2,3)'ell'
SUBSTRING(s FROM pos FOR len)SQL standard substrSUBSTRING('hello' FROM 2 FOR 3)
REPLACE(s,old,new)Replace all occurrencesREPLACE('aab','a','x')'xxb'
POSITION(sub IN s)Find substring positionPOSITION('ell' IN 'hello')2
LPAD(s,n,pad)Left-pad stringLPAD('5',3,'0')'005'
RPAD(s,n,pad)Right-pad stringRPAD('5',3,'0')'500'
REPEAT(s,n)Repeat stringREPEAT('ab',3)'ababab'
REVERSE(s)Reverse stringREVERSE('abc')'cba'
SPLIT_PART(s,delim,n)Split and return nth part (PostgreSQL)SPLIT_PART('a,b,c',',',2)'b'
REGEXP_REPLACE(s,pat,rep)Regex replace (PostgreSQL)REGEXP_REPLACE('foo123','[0-9]+','')
SELECT
    UPPER(email),
    LENGTH(bio),
    TRIM(notes),
    REPLACE(phone, '-', ''),
    SUBSTRING(description FROM 1 FOR 100)
FROM users;

Numeric Functions

FunctionDescriptionExample
ABS(n)Absolute valueABS(-5)5
ROUND(n,d)Round to d decimal placesROUND(3.456, 2)3.46
FLOOR(n)Round downFLOOR(3.9)3
CEIL(n) / CEILING(n)Round upCEIL(3.1)4
TRUNC(n,d)Truncate (no rounding)TRUNC(3.99, 1)3.9
POWER(b,e)ExponentiationPOWER(2,10)1024
SQRT(n)Square rootSQRT(16)4
MOD(n,d)ModuloMOD(10,3)1
SIGN(n)-1, 0, or 1SIGN(-5)-1
GREATEST(a,b,...)Largest valueGREATEST(3,7,2)7
LEAST(a,b,...)Smallest valueLEAST(3,7,2)2
RANDOM()Random 0-1 float (PostgreSQL)RANDOM()

Date / Time Functions

FunctionDescriptionExample
NOW()Current timestamp with tzNOW()
CURRENT_DATECurrent dateCURRENT_DATE
CURRENT_TIMECurrent timeCURRENT_TIME
CURRENT_TIMESTAMPCurrent timestampCURRENT_TIMESTAMP
DATE_PART('field', ts)Extract date part (PostgreSQL)DATE_PART('year', NOW())
EXTRACT(field FROM ts)SQL standard extractEXTRACT(MONTH FROM created_at)
DATE_TRUNC('unit', ts)Truncate to unit (PostgreSQL)DATE_TRUNC('month', NOW())
AGE(ts)Interval since timestamp (PostgreSQL)AGE(birth_date)
DATE_ADD(date, INTERVAL n unit)Add interval (MySQL)DATE_ADD(NOW(), INTERVAL 7 DAY)
date + INTERVAL '7 days'Add interval (PostgreSQL)created_at + INTERVAL '30 days'
DATEDIFF(d1,d2)Days between dates (MySQL)DATEDIFF(NOW(), hire_date)
TO_CHAR(ts, 'fmt')Format timestamp (PostgreSQL)TO_CHAR(NOW(), 'YYYY-MM-DD')
DATE_FORMAT(ts, 'fmt')Format timestamp (MySQL)DATE_FORMAT(NOW(), '%Y-%m-%d')
-- Common date/time patterns
SELECT
    EXTRACT(YEAR FROM created_at)        AS yr,
    DATE_TRUNC('month', created_at)      AS month_start,
    created_at + INTERVAL '90 days'      AS expires_at,
    NOW() - created_at                   AS age
FROM subscriptions;

Conditional Expressions

-- CASE WHEN (searched form)
SELECT name,
    CASE
        WHEN salary > 100000 THEN 'high'
        WHEN salary > 50000  THEN 'mid'
        ELSE 'low'
    END AS band
FROM employees;

-- CASE value (simple form)
SELECT name,
    CASE status
        WHEN 'A' THEN 'Active'
        WHEN 'I' THEN 'Inactive'
        ELSE 'Unknown'
    END AS status_label
FROM users;

-- COALESCE: first non-NULL
SELECT COALESCE(middle_name, '') AS middle FROM users;

-- NULLIF: returns NULL if equal
SELECT NULLIF(value, 0) FROM measurements;  -- avoid division by zero

-- IIF shorthand (SQL Server)
SELECT IIF(score >= 60, 'Pass', 'Fail') FROM results;

-- IF (MySQL only — not in standard SQL)
SELECT IF(score >= 60, 'Pass', 'Fail') FROM results;

SELECT without FROM

-- Compute expressions directly
SELECT 1 + 1;
SELECT CURRENT_DATE;
SELECT UPPER('hello');
SELECT NOW(), CURRENT_USER;

-- PostgreSQL / MySQL; SQL Server needs: SELECT 1+1 FROM (VALUES(1)) t(n)
-- SQLite: SELECT 1+1

Column Metadata and Schema Inspection

-- List all tables in current schema (PostgreSQL)
SELECT table_name FROM information_schema.tables
WHERE table_schema = 'public' AND table_type = 'BASE TABLE';

-- List columns of a table (PostgreSQL)
SELECT column_name, data_type, is_nullable, column_default
FROM information_schema.columns
WHERE table_name = 'users' ORDER BY ordinal_position;

-- MySQL describe shorthand
DESCRIBE users;
SHOW COLUMNS FROM users;
SHOW TABLES;