SQL Reference
Quick reference for SQL keywords and functions
Data Query
SELECTSELECT col1, col2 FROM tableRetrieve rows from a table or viewWHEREWHERE conditionFilter rows by a conditionJOININNER JOIN t2 ON t1.id = t2.fkCombine rows from two tables on a conditionLEFT JOINLEFT JOIN t2 ON t1.id = t2.fkInclude all rows from the left table, NULLs for non-matching right rowsGROUP BYGROUP BY colGroup rows for aggregate functionsHAVINGHAVING COUNT(*) > 1Filter groups after GROUP BYORDER BYORDER BY col DESCSort result rowsLIMITLIMIT 10Restrict number of returned rowsDISTINCTSELECT DISTINCT colReturn unique values onlyUNIONSELECT ... UNION SELECT ...Combine results of two queries, removing duplicatesData Manipulation
INSERTINSERT INTO t (col) VALUES ('val')Insert new rowsUPDATEUPDATE t SET col = 'val' WHERE id = 1Modify existing rowsDELETEDELETE FROM t WHERE id = 1Remove rowsTRUNCATETRUNCATE TABLE tRemove all rows quickly (DDL in some databases)Data Definition
CREATE TABLECREATE TABLE t (id INT NOT NULL)Create a new tableALTER TABLEALTER TABLE t ADD COLUMN col INTModify an existing table structureDROP TABLEDROP TABLE tPermanently delete a tableCREATE INDEXCREATE INDEX idx ON t (col)Create an index to speed up queriesPRIMARY KEYid INT PRIMARY KEYUniquely identifies each rowFOREIGN KEYFOREIGN KEY (col) REFERENCES t2(id)Enforces referential integrityNOT NULLColumn must have a valueUNIQUEAll values in the column must be distinctDEFAULTcol INT DEFAULT 0Fallback value when none is suppliedAggregate Functions
COUNT(*)Number of rows in a groupSUM(col)Sum of numeric valuesAVG(col)Average of numeric valuesMIN(col)Smallest valueMAX(col)Largest valueCommon Data Types
INT / INTEGERWhole numbers (4 bytes)BIGINTLarge whole numbers (8 bytes)VARCHAR(n)Variable-length string up to n charactersTEXTUnlimited-length stringBOOLEANTrue/false valueDECIMAL(p,s)Exact numeric with precision p and scale sTIMESTAMPDate and time valueJSON / JSONBJSON document (JSONB is binary-indexed in PostgreSQL)Transactions
BEGINStart a transaction blockCOMMITSave all changes in the current transactionROLLBACKUndo all changes since BEGINSAVEPOINTSAVEPOINT sp1Mark a point within a transaction to roll back to