SQL Cheatsheet

SQL Basics for Projects

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

SQL Dialects — Overview

This reference targets standard SQL (SQL:2016) with notes on major dialects. Most examples run in PostgreSQL, MySQL, SQLite, and SQL Server with minor variation.

FeaturePostgreSQLMySQLSQLiteSQL Server
String concat|| or CONCAT()CONCAT()||+ or CONCAT()
Auto-incrementSERIAL / GENERATEDAUTO_INCREMENTAUTOINCREMENTIDENTITY
Boolean typeBOOLEANTINYINT(1)INTEGERBIT
Limit rowsLIMIT nLIMIT nLIMIT nTOP n / FETCH FIRST
String case-sensitivitycase-sensitivecase-insensitivecase-insensitivedepends on collation

Data Types

Numeric

TypeDescriptionExample
INTEGER / INTWhole number42
SMALLINTSmall integer (2 bytes)32767
BIGINTLarge integer (8 bytes)9223372036854775807
DECIMAL(p,s) / NUMERIC(p,s)Exact fixed-point, p digits, s after decimalDECIMAL(10,2)
FLOAT / REALApproximate floating point3.14
DOUBLE PRECISIONDouble-precision float3.14159265358979

Text

TypeDescriptionExample
CHAR(n)Fixed-length string, padded with spacesCHAR(10)
VARCHAR(n)Variable-length string, max n charsVARCHAR(255)
TEXTUnlimited-length string (PostgreSQL/MySQL/SQLite)
NVARCHAR(n)Unicode variable string (SQL Server)NVARCHAR(100)
CLOBCharacter large object (standard)

Date / Time

TypeDescriptionLiteral Example
DATECalendar date'2024-01-15'
TIMETime of day'14:30:00'
TIMESTAMPDate + time'2024-01-15 14:30:00'
TIMESTAMPTZTimestamp with timezone (PostgreSQL)'2024-01-15 14:30:00+00'
INTERVALDuration (PostgreSQL)INTERVAL '1 day'

Other

TypeDescription
BOOLEANTRUE / FALSE / NULL
BLOB / BYTEABinary data
JSON / JSONBJSON document (PostgreSQL JSONB is indexed)
UUID128-bit universally unique identifier
ARRAYArray of another type (PostgreSQL)
ENUM(...)Restricted set of string values (MySQL)

Statement Structure

Every SQL statement ends with ;. SQL is case-insensitive for keywords but convention uses UPPERCASE keywords.

-- Line comment
/* Block comment
   spanning lines */

-- A complete SELECT statement (clauses must appear in this order):
SELECT column1, column2
FROM   table_name
WHERE  condition
GROUP  BY column1
HAVING aggregate_condition
ORDER  BY column1 ASC
LIMIT  10
OFFSET 20;

NULL Semantics

NULL means unknown — it is not zero, not empty string. Any comparison with NULL yields NULL (not TRUE or FALSE).

-- Correct NULL checks
SELECT * FROM users WHERE phone IS NULL;
SELECT * FROM users WHERE phone IS NOT NULL;

-- Wrong — always returns no rows
SELECT * FROM users WHERE phone = NULL;

-- NULL propagates through arithmetic
SELECT NULL + 5;        -- NULL
SELECT NULL || 'text';  -- NULL (PostgreSQL)
SELECT COALESCE(NULL, 'default');  -- 'default'
SELECT NULLIF(5, 5);    -- NULL (returns NULL when args are equal)
SELECT NULLIF(5, 3);    -- 5

-- NULL in aggregate functions: ignored except COUNT(*)
SELECT AVG(salary) FROM employees;  -- NULLs excluded from average
SELECT COUNT(*) FROM employees;      -- counts all rows including NULL
SELECT COUNT(salary) FROM employees; -- excludes NULL salaries

Operators

Comparison

OperatorMeaning
=Equal
<> or !=Not equal
<Less than
>Greater than
<=Less than or equal
>=Greater than or equal
IS NULLIs null
IS NOT NULLIs not null
IS DISTINCT FROMNot equal, treating NULLs as comparable

Logical

WHERE a = 1 AND b = 2
WHERE a = 1 OR  b = 2
WHERE NOT (a = 1)

-- Operator precedence: NOT > AND > OR
-- Always use parentheses to be explicit
WHERE (a = 1 OR a = 2) AND b > 0

Arithmetic

SELECT 10 + 3,   -- 13
       10 - 3,   -- 7
       10 * 3,   -- 30
       10 / 3,   -- 3  (integer division in most dialects)
       10.0 / 3, -- 3.333...
       10 % 3,   -- 1  (modulo)
       10 ^ 2;   -- 100 (PostgreSQL; use POWER(10,2) elsewhere)

String

-- Concatenation
SELECT 'Hello' || ' ' || 'World';        -- standard
SELECT CONCAT('Hello', ' ', 'World');    -- MySQL / SQL Server

-- LIKE pattern matching (case-insensitive in MySQL/SQLite by default)
WHERE name LIKE 'A%'       -- starts with A
WHERE name LIKE '%son'     -- ends with son
WHERE name LIKE '%art%'    -- contains art
WHERE name LIKE 'J_n'      -- J, any one char, n
WHERE name NOT LIKE 'X%'

-- ILIKE — case-insensitive LIKE (PostgreSQL)
WHERE name ILIKE 'alice%'

Casting

-- CAST (standard)
SELECT CAST('123' AS INTEGER);
SELECT CAST(price AS TEXT);
SELECT CAST('2024-01-01' AS DATE);

-- :: shorthand (PostgreSQL)
SELECT '123'::INTEGER;
SELECT price::TEXT;

-- CONVERT (MySQL / SQL Server)
SELECT CONVERT(INT, '123');        -- SQL Server
SELECT CONVERT('123', UNSIGNED);   -- MySQL

Transactions

BEGIN;                          -- start transaction (also: START TRANSACTION)
  UPDATE accounts SET balance = balance - 100 WHERE id = 1;
  UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;                         -- make changes permanent

-- On error:
ROLLBACK;                       -- undo all changes in the transaction

-- Savepoints
BEGIN;
  INSERT INTO orders VALUES (1, 'pending');
  SAVEPOINT before_payment;
  INSERT INTO payments VALUES (1, 100);
  ROLLBACK TO before_payment;   -- undo only from savepoint
COMMIT;

-- Isolation levels (SET before BEGIN or after BEGIN)
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

Comments

-- Single-line comment (SQL standard)
# Single-line comment (MySQL only)

/*
   Multi-line
   block comment
*/

SELECT id /*, name */ FROM users;  -- inline block comment

Identifiers and Quoting

-- Unquoted identifiers are case-insensitive and must start with a letter/underscore
SELECT user_id FROM orders;

-- Quoted identifiers preserve case and allow reserved words / spaces
SELECT "User ID" FROM "Order Details";   -- standard SQL and PostgreSQL
SELECT `user_id` FROM `orders`;          -- MySQL backtick quoting
SELECT [user id] FROM [order details];   -- SQL Server bracket quoting

-- Reserved word used as column name
SELECT "select" FROM my_table;