SELECT Anatomy
SELECT column1, column2Return selected columns.
SELECT *Return every column; useful for inspection, usually avoid in production APIs.
FROM table_nameChoose the source table or relation.
SELECT DISTINCT columnRemove duplicate result rows for the selected expression set.
AS aliasRename an output column or table reference for the query.
SELECT expressionReturn calculations, literals, function results, or CASE expressions.
Aliases & Qualification
users AS uGive a table a shorter query alias.
u.idQualify a column with its table alias; important in joins.
total * tax_rate AS taxAlias a calculated output column.
"Order" / `Order`Quoted identifiers are dialect-specific; avoid reserved words for object names.
Sorting & Pagination
ORDER BY created_at ASCSort from lowest/oldest to highest/newest.
ORDER BY created_at DESCSort from highest/newest to lowest/oldest.
ORDER BY last_name, first_nameSort by multiple keys in sequence.
LIMIT 25Return at most 25 rows in PostgreSQL, MySQL, and SQLite.
OFFSET 50Skip rows before returning the next page; large offsets can become expensive.
FETCH FIRST 25 ROWS ONLYStandard-style row limiting supported by some systems.
Common Data Types
INTEGER / INTWhole numbers.
BIGINTLarge whole numbers and large generated identifiers.
DECIMAL(p,s) / NUMERIC(p,s)Exact fixed-precision values; preferred for money-like calculations.
REAL / FLOAT / DOUBLEApproximate floating-point numeric values.
CHAR(n) / VARCHAR(n) / TEXTCharacter data; exact behavior and limits vary by database.
BOOLEANTrue/false values; storage details vary by database.
DATECalendar date without a time.
TIMETime of day.
TIMESTAMPDate and time; timezone behavior depends on type and database.
BLOB / BYTEA / BINARYBinary data; names differ across engines.
JSON / JSONBStructured JSON where supported; PostgreSQL distinguishes JSON and JSONB.
Written vs Logical Query Order
WrittenSELECT → FROM/JOIN → WHERE → GROUP BY → HAVING → ORDER BY → LIMIT/FETCH.
Logical processingFROM/JOIN → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT.
Why it mattersA SELECT alias often cannot be referenced in WHERE because WHERE is logically evaluated earlier.
WHERE predicates, NULL handling, CASE expressions, pattern matching, and common scalar functions.
02 — Filtering, Expressions & Functions
Comparison & Boolean Logic
=Equal.
<>Standard SQL not-equal operator.
!=Common not-equal synonym; support is widespread but <> is standard.
> < >= <=Numeric, textual, or date comparisons when types are comparable.
ANDRequire both predicates to be true.
ORRequire either predicate to be true.
NOTNegate a predicate.
( ... )Use parentheses to make mixed AND/OR logic explicit.
WHERE Patterns
WHERE status = 'active'Filter rows by an exact value.
WHERE price BETWEEN 10 AND 50Inclusive range test.
WHERE id IN (1, 2, 3)Match any value in a list or subquery.
WHERE id NOT IN (...)Exclude listed values; NULLs in the list can create surprising results.
WHERE EXISTS (subquery)True when the correlated or uncorrelated subquery returns a row.
WHERE NOT EXISTS (subquery)True when the subquery returns no rows.
Pattern Matching
LIKE 'Ada%'% matches zero or more characters.
LIKE '_at'_ matches exactly one character.
NOT LIKE patternExclude matches.
ILIKE patternPostgreSQL case-insensitive LIKE extension.
LOWER(name) LIKE 'ada%'Portable-style case folding, though function use can affect index use.
NULL Rules
IS NULLCorrect test for a missing/unknown value.
IS NOT NULLCorrect test for a non-NULL value.
column = NULLDo not use; comparisons with NULL evaluate to UNKNOWN rather than true.
COALESCE(a, b, c)Return the first non-NULL expression.
NULLIF(a, b)Return NULL when a equals b; otherwise return a.
COUNT(column)Counts non-NULL values only.
COUNT(*)Counts rows, regardless of NULL values.
CASE Expressions
CASE WHEN condition THEN value ELSE other ENDGeneral conditional expression.
CASE status WHEN 'A' THEN 'Active' ELSE 'Other' ENDSimple CASE comparing one expression to several values.
ORDER BY CASE ... ENDUse conditional logic to define a custom sort order.
SUM(CASE WHEN ... THEN 1 ELSE 0 END)Portable conditional counting pattern.
String Functions
LOWER(text)Convert text to lowercase.
UPPER(text)Convert text to uppercase.
TRIM(text)Remove surrounding whitespace or configured characters.
LENGTH(text)Return string length; byte/character semantics vary by database and function.
SUBSTRING(text FROM start FOR count)Standard-style substring syntax; dialect alternatives exist.
REPLACE(text, old, new)Replace occurrences inside text.
CONCAT(a, b)Concatenate values where supported.
a || bStandard concatenation operator; MySQL behavior differs unless configured.
Numeric & Date/Time Functions
ABS(n)Absolute numeric value.
ROUND(n, digits)Round a number.
CEIL(n) / CEILING(n)Round upward.
FLOOR(n)Round downward.
CURRENT_DATECurrent date.
CURRENT_TIMECurrent time.
CURRENT_TIMESTAMPCurrent date and time.
EXTRACT(YEAR FROM ts)Read a date/time field where supported.
Date arithmeticIntervals, date-add functions, and syntax vary significantly by database.
Aggregates, GROUP BY, joins, subqueries, set operators, CTEs, and window functions.
03 — Grouping, Joins & Result Sets
Aggregate Functions
COUNT(*)Count rows.
COUNT(DISTINCT user_id)Count distinct non-NULL values.
SUM(amount)Total numeric values.
AVG(amount)Average non-NULL numeric values.
MIN(value)Smallest value.
MAX(value)Largest value.
GROUP BY & HAVING
GROUP BY departmentCollapse rows into one result group per department.
GROUP BY department, statusGroup by multiple expressions.
HAVING COUNT(*) > 5Filter groups after aggregation.
WHERE ...Filter individual rows before grouping.
HAVING ...Filter aggregate groups after GROUP BY.
JOIN Types
INNER JOINReturn matching rows from both sides.
LEFT JOINKeep every left-side row and matching right-side rows; unmatched right values become NULL.
RIGHT JOINKeep every right-side row where the engine supports it.
FULL OUTER JOINKeep matched rows plus unmatched rows from both sides where supported.
CROSS JOINCartesian product: every left row paired with every right row.
SELF JOINJoin a table to itself using aliases; useful for hierarchies and comparisons.
JOIN Syntax & Safety
... JOIN orders o ON o.user_id = u.idPut relationship conditions in ON.
LEFT JOIN ... ON ...Filtering the right table in WHERE can unintentionally turn a LEFT JOIN into an inner-style result.
USING (id)Concise join syntax when both sides share the same join-column name.
Qualified columnsUse aliases such as u.id and o.id to avoid ambiguity.
Many-to-manyJoin through the relationship table rather than storing repeated lists in one column.
Subqueries
WHERE id IN (SELECT ...)Use a subquery as a set of candidate values.
WHERE EXISTS (SELECT 1 ...)Efficient semantic pattern for existence checks.
FROM (SELECT ...) AS xUse a derived table as a query source.
SELECT (SELECT ...)Scalar subquery must return at most one value.
Correlated subqueryReferences the outer query; can be expressive but may need performance review.
Set Operators
UNIONCombine compatible result sets and remove duplicates.
UNION ALLCombine compatible result sets without duplicate elimination; usually faster.
INTERSECTRows present in both result sets where supported.
EXCEPTRows in the first result but not the second where supported.
Column compatibilityEach SELECT must return the same number of columns with compatible types.
Common Table Expressions
WITH recent AS (SELECT ...) SELECT ... FROM recentName a query expression for readability and reuse in one statement.
Multiple CTEsSeparate CTE definitions with commas.
WITH RECURSIVEExpress hierarchies, trees, graphs, and iterative relationships where supported.
CTE optimizationMaterialization/inlining behavior differs by engine and version; inspect plans for performance-critical queries.
Window Functions
ROW_NUMBER() OVER (...)Assign a unique sequence within the window ordering.
RANK() OVER (...)Ranking with gaps after ties.
DENSE_RANK() OVER (...)Ranking without gaps after ties.
SUM(amount) OVER (...)Running or partitioned totals without collapsing rows.
LAG(value) OVER (...)Read a previous row's value.
LEAD(value) OVER (...)Read a following row's value.
PARTITION BY departmentRestart the window calculation for each partition.
ORDER BY created_atDefine order inside a window.
INSERT, UPDATE, DELETE, CREATE, ALTER, DROP, views, constraints, and safe change patterns.
04 — Data Changes & Schema
INSERT
INSERT INTO users (name,email) VALUES ('Ada','a@example.com');Insert one row.
INSERT INTO t (a,b) VALUES (1,2), (3,4);Insert multiple rows where supported.
INSERT INTO archive (...) SELECT ...;Insert rows produced by a query.
DEFAULTUse a column's configured default value.
RETURNING ...PostgreSQL and some other engines can return affected rows directly.
UPDATE
UPDATE users SET active = 0 WHERE id = 42;Change matching rows.
SET a = 1, b = 2Update multiple columns.
WHERE ...Critical safety boundary; without it every row may be updated.
UPDATE ... FROM ...Join-style update syntax exists in PostgreSQL and some engines; details differ.
Preview firstRun the equivalent SELECT with the same WHERE before a broad update.
DELETE
DELETE FROM users WHERE id = 42;Delete matching rows.
DELETE FROM users;Delete every row while keeping the table.
WHERE ...Critical safety boundary for selective deletion.
Foreign keysChild references may block deletion or trigger configured referential actions.
Preview firstRun SELECT with the same WHERE before a broad delete.
UPSERT Patterns
PostgreSQL / SQLiteINSERT ... ON CONFLICT (...) DO UPDATE / DO NOTHING.
MySQLINSERT ... ON DUPLICATE KEY UPDATE ...
MERGEStandard-style matched/not-matched data-change statement; support and syntax vary.
RuleChoose the conflict key deliberately and understand which constraint triggers the alternative action.
CREATE TABLE
CREATE TABLE users (...);Create a table.
id INTEGER PRIMARY KEYDefine a primary key inline.
email TEXT NOT NULL UNIQUECombine required-value and uniqueness constraints.
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMPApply a default expression.
FOREIGN KEY (...) REFERENCES ...Define an inter-table relationship.
ALTER / DROP / TRUNCATE
ALTER TABLE t ADD COLUMN x ...Add a column.
ALTER TABLE t DROP COLUMN xRemove a column where supported.
ALTER TABLE t RENAME COLUMN a TO bRename a column where supported.
ALTER TABLE t ADD CONSTRAINT ...Add table-level constraints; support differs.
DROP TABLE tRemove table structure and data.
DROP TABLE IF EXISTS tConditionally remove a table.
TRUNCATE TABLE tQuickly remove all rows where supported; transactional behavior differs by engine.
Views
CREATE VIEW active_users AS SELECT ...Save a query as a virtual relation.
DROP VIEW active_usersRemove a view definition.
Materialized viewStores query results physically where supported; refresh semantics are engine-specific.
Use casesSimplify complex joins, centralize reusable query logic, and expose limited projections.
Keys, constraints, normalization, indexing, query plans, schema design, and secure application access.
05 — Design, Integrity & Performance
Keys & Constraints
PRIMARY KEYUniquely identifies each row; implies uniqueness and non-NULL semantics.
FOREIGN KEYRequires referenced values to exist according to the relationship definition.
UNIQUEPrevent duplicate values or duplicate column combinations.
NOT NULLRequire a value.
CHECK (condition)Enforce a row-level business rule where supported.
DEFAULT expressionProvide a value when INSERT omits the column.
Composite keyA key or constraint defined across multiple columns.
Referential Actions
ON DELETE CASCADEDelete referencing child rows automatically.
ON DELETE SET NULLSet the foreign-key column to NULL when the parent is deleted.
ON DELETE RESTRICT / NO ACTIONPrevent parent deletion when references exist; timing details vary.
ON UPDATE ...Control behavior when a referenced key changes; support and defaults vary.
RuleChoose cascading behavior based on ownership semantics, not convenience.
Normalization Quick Read
1NFStore atomic values and avoid repeating groups inside a row.
2NFFor composite keys, non-key attributes depend on the whole key.
3NFNon-key attributes should not depend transitively on other non-key attributes.
Junction tableRepresent many-to-many relationships with a relationship table.
DenormalizationIntentional duplication for performance/read models; document why it exists.
Indexes
CREATE INDEX idx_users_email ON users(email);Create a non-unique index.
CREATE UNIQUE INDEX ...Create an index that also enforces uniqueness.
CREATE INDEX ... ON orders(user_id, created_at);Composite index; column order matters.
DROP INDEX ...Remove an index; syntax varies by database.
Good candidatesFrequently filtered, joined, sorted, or uniqueness-enforced columns.
TradeoffIndexes improve many reads but consume storage and add write/update maintenance cost.
Query Plans
EXPLAIN SELECT ...Inspect the optimizer's planned operations.
EXPLAIN ANALYZE ...Execute and measure the query in supporting systems; use carefully on writes or expensive queries.
Table/sequence scanMay be correct for small tables or broad result sets; not automatically a problem.
Index scan/searchUses an index to locate rows.
Join strategyNested loop, hash, merge, and other strategies depend on engine and statistics.
StatisticsOptimizers depend on current table/index statistics to estimate row counts and costs.
Sargability & Query Habits
Indexed column directlyWHERE email = ? can use a suitable index more easily.
Function on indexed columnWHERE LOWER(email) = ? may require an expression/function index or prevent a normal index seek.
Leading wildcardLIKE '%term' often cannot use a normal B-tree prefix efficiently.
Select needed columnsAvoid transferring unused data and reduce coupling to schema changes.
Filter earlyReduce rows before expensive joins/aggregations when semantics permit.
Prepared Statements & Injection Safety
SELECT ... WHERE id = ?Use positional placeholders for data values.
... WHERE email = :emailUse named placeholders when supported by the client library.
Do not concatenate inputNever build executable SQL by directly inserting untrusted user values.
IdentifiersPlaceholders represent values, not arbitrary table/column names; whitelist dynamic identifiers.
Least privilegeApplication credentials should have only the database permissions the application needs.
Transactions, isolation, locking, permissions, metadata, dialect differences, and high-risk operations.
06 — Transactions, Advanced SQL & Dialects
Transaction Control
BEGIN / START TRANSACTIONStart an explicit transaction; exact syntax varies.
COMMITMake the transaction's changes durable.
ROLLBACKUndo uncommitted work.
SAVEPOINT nameCreate an intermediate rollback point.
ROLLBACK TO SAVEPOINT nameUndo work after the savepoint while keeping the transaction open.
RELEASE SAVEPOINT nameDiscard a savepoint where supported.
ACID
AtomicityA transaction succeeds as a unit or is rolled back.
ConsistencyCommitted data obeys defined integrity rules.
IsolationConcurrent work is controlled so transactions do not interfere unpredictably.
DurabilityCommitted changes survive normal failures according to the database's durability guarantees.
Isolation Levels
READ UNCOMMITTEDWeakest standard level; dirty reads may be possible in systems that implement it.
READ COMMITTEDPrevents dirty reads; repeated reads can still observe committed changes.
REPEATABLE READStronger repeat-read guarantees; exact phantom behavior varies by database.
SERIALIZABLEStrongest standard isolation; may reject/retry conflicting transactions.
RealityEngines implement isolation differently; verify your database's documentation.
Concurrency & Locking
Short transactionsReduce lock duration and contention.
Consistent access orderAcquire/update shared resources in a consistent order to reduce deadlock risk.
DeadlockDatabase detects a dependency cycle and usually aborts one transaction.
Retry policyApplications may need bounded retries for serialization failures or deadlock victims.
Long reportsLarge reads can interact with vacuum/version storage/locks differently across engines.
PostgreSQL / MySQL / SQLite Quick Differences
PostgreSQLRich SQL feature set, RETURNING, ILIKE, schemas, arrays/JSONB, strong window/CTE support.
MySQLUses AUTO_INCREMENT, ON DUPLICATE KEY UPDATE, backtick identifiers, and engine-specific date/string functions.
SQLiteEmbedded single-file database, dynamic type affinity, PRAGMA metadata/configuration, ON CONFLICT upserts.
Identity columnsPostgreSQL IDENTITY/SERIAL, MySQL AUTO_INCREMENT, SQLite INTEGER PRIMARY KEY behavior differ.
BooleanRepresentation and native typing differ.
Date/timeStorage types and arithmetic differ; never assume one engine's date functions are portable.
ConcatenationPostgreSQL/SQLite commonly use ||; MySQL normally uses CONCAT().
High-Risk SQL: Slow Down
UPDATE without WHERECan change every row.
DELETE without WHERECan delete every row.
DROP TABLE / DROP DATABASERemoves database structures and data.
TRUNCATERemoves all rows quickly and may have special transactional/identity behavior.
ALTER destructive changesDropping or changing columns/types can destroy or rewrite data.
Before runningVerify environment/database/schema, preview affected rows, back up important data, and prefer reversible migrations.
Compact Query Pattern
ReadSELECT columns FROM tables JOIN ... WHERE ... GROUP BY ... HAVING ... ORDER BY ... LIMIT ...
CreateINSERT INTO table (columns) VALUES (values).
ChangeUPDATE table SET column = value WHERE key = value.
RemoveDELETE FROM table WHERE key = value.
DefineCREATE / ALTER / DROP schema objects.
ProtectConstraints + transactions + prepared statements + least privilege + backups.