On this page

Query Basics

SQL Cheat Sheet

A quick reference of SQL commands grouped by category. Each row shows what the command does and its syntax.


1. Data Query (Reading Data)

CommandWhat it doesSyntax
SELECTGets columns from a tableSELECT col1, col2 FROM table;
SELECT *Gets all columnsSELECT * FROM table;
SELECT DISTINCTGets only unique valuesSELECT DISTINCT col FROM table;
AS (alias)Gives a temporary nameSELECT col AS new_name FROM table AS t;
FROMSays which table to readSELECT col FROM table;


2. Filtering (Choosing Rows)

CommandWhat it doesSyntax
WHEREFilters rows by a conditionSELECT * FROM table WHERE condition;
ANDAll conditions must be trueWHERE cond1 AND cond2;
ORAny one condition can be trueWHERE cond1 OR cond2;
NOTReverses a conditionWHERE NOT condition;
INMatches any value in a listWHERE col IN (val1, val2);
NOT INMatches none of the valuesWHERE col NOT IN (val1, val2);
BETWEENMatches a range (inclusive)WHERE col BETWEEN val1 AND val2;
LIKESearches for a text patternWHERE col LIKE 'pattern';
ILIKECase-insensitive LIKE (PostgreSQL)WHERE col ILIKE 'pattern';
IS NULLFinds empty valuesWHERE col IS NULL;
IS NOT NULLFinds non-empty valuesWHERE col IS NOT NULL;
EXISTSTrue if a subquery returns rowsWHERE EXISTS (SELECT 1 FROM table2 WHERE condition);

3. Comparison Operators

OperatorMeaningSyntax
=Equal toWHERE col = 10;
<> or !=Not equal toWHERE col <> 10;
>Greater thanWHERE col > 10;
<Less thanWHERE col < 10;
>=Greater than or equalWHERE col >= 10;
<=Less than or equalWHERE col <= 10;

LIKE wildcards

WildcardMeaningSyntax
%Zero or more charactersWHERE name LIKE 'A%';
_Exactly one characterWHERE name LIKE '_a%';

4. Sorting and Limiting

CommandWhat it doesSyntax
ORDER BYSorts the resultSELECT * FROM table ORDER BY col;
ASCSorts small to large (default)ORDER BY col ASC;
DESCSorts large to smallORDER BY col DESC;
NULLS FIRSTPuts NULLs at the topORDER BY col NULLS FIRST;
NULLS LASTPuts NULLs at the bottomORDER BY col NULLS LAST;
LIMITLimits number of rowsSELECT * FROM table LIMIT 10;
OFFSETSkips rows before returningSELECT * FROM table LIMIT 10 OFFSET 20;
TOPLimits rows (SQL Server)SELECT TOP 10 * FROM table;
FETCH FIRSTLimits rows (Oracle / standard)SELECT * FROM table FETCH FIRST 10 ROWS ONLY;

5. Aggregate Functions

Aggregate functions work on many rows and return one value. They ignore NULL values (except COUNT(*)).

FunctionWhat it doesSyntax
COUNT(*)Counts all rowsSELECT COUNT(*) FROM table;
COUNT(col)Counts non-NULL valuesSELECT COUNT(col) FROM table;
COUNT(DISTINCT)Counts unique valuesSELECT COUNT(DISTINCT col) FROM table;
SUM()Adds up valuesSELECT SUM(col) FROM table;
AVG()Finds the averageSELECT AVG(col) FROM table;
MIN()Finds the smallest valueSELECT MIN(col) FROM table;
MAX()Finds the largest valueSELECT MAX(col) FROM table;

6. Grouping

CommandWhat it doesSyntax
GROUP BYGroups rows with the same valueSELECT col, COUNT(*) FROM table GROUP BY col;
HAVINGFilters groups (after GROUP BY)SELECT col, COUNT(*) FROM table GROUP BY col HAVING COUNT(*) > 1;

WHERE vs HAVING: WHERE filters rows before grouping. HAVING filters groups after grouping.


7. Data Modification (DML)

CommandWhat it doesSyntax
INSERT INTOAdds a new rowINSERT INTO table (col1, col2) VALUES (val1, val2);
INSERT INTO (many)Adds many rows at onceINSERT INTO table (col1, col2) VALUES (v1, v2), (v3, v4);
INSERT INTO ... SELECTCopies rows from another tableINSERT INTO table1 (col) SELECT col FROM table2;
UPDATEChanges existing rowsUPDATE table SET col = value WHERE condition;
DELETERemoves rowsDELETE FROM table WHERE condition;

Warning: Always use WHERE with UPDATE and DELETE. Without it, all rows are changed or deleted.


8. Table Structure (DDL)

CommandWhat it doesSyntax
CREATE DATABASECreates a databaseCREATE DATABASE db_name;
CREATE TABLECreates a tableCREATE TABLE table (col1 datatype, col2 datatype);
ALTER TABLE ADDAdds a columnALTER TABLE table ADD col datatype;
ALTER TABLE DROP COLUMNRemoves a columnALTER TABLE table DROP COLUMN col;
ALTER TABLE RENAMERenames a table (PostgreSQL / MySQL)ALTER TABLE old_name RENAME TO new_name;
DROP TABLEDeletes a table completelyDROP TABLE table;
TRUNCATE TABLEDeletes all rows, keeps the tableTRUNCATE TABLE table;
CREATE INDEXSpeeds up searches on a columnCREATE INDEX index_name ON table (col);
CREATE VIEWSaves a query as a virtual tableCREATE VIEW view_name AS SELECT col FROM table;

9. Constraints

ConstraintWhat it doesSyntax
PRIMARY KEYUnique ID for each row (not NULL)id INT PRIMARY KEY
FOREIGN KEYLinks to another tableFOREIGN KEY (col) REFERENCES other_table(col)
UNIQUENo duplicate values allowedcol datatype UNIQUE
NOT NULLValue cannot be emptycol datatype NOT NULL
CHECKValue must meet a conditioncol INT CHECK (col > 0)
DEFAULTSets a value when none is givencol datatype DEFAULT value
AUTO_INCREMENTAuto-increasing number (MySQL)id INT AUTO_INCREMENT

10. Joins (Combining Tables)

CommandWhat it doesSyntax
INNER JOINRows that match in both tablesSELECT * FROM t1 INNER JOIN t2 ON t1.id = t2.id;
LEFT JOINAll rows from left table + matches from rightSELECT * FROM t1 LEFT JOIN t2 ON t1.id = t2.id;
RIGHT JOINAll rows from right table + matches from leftSELECT * FROM t1 RIGHT JOIN t2 ON t1.id = t2.id;
FULL JOINAll rows from both tablesSELECT * FROM t1 FULL JOIN t2 ON t1.id = t2.id;
CROSS JOINEvery row combined with every rowSELECT * FROM t1 CROSS JOIN t2;
SELF JOINJoins a table with itselfSELECT * FROM table a JOIN table b ON a.col = b.col;

11. Set Operations (Combining Results)

CommandWhat it doesSyntax
UNIONCombines results, removes duplicatesSELECT col FROM t1 UNION SELECT col FROM t2;
UNION ALLCombines results, keeps duplicatesSELECT col FROM t1 UNION ALL SELECT col FROM t2;
INTERSECTOnly rows found in both resultsSELECT col FROM t1 INTERSECT SELECT col FROM t2;
EXCEPTRows in first result but not in secondSELECT col FROM t1 EXCEPT SELECT col FROM t2;

Note: Oracle uses MINUS instead of EXCEPT.


12. Subqueries

TypeWhat it doesSyntax
Subquery in WHEREUses one query's result in anotherSELECT * FROM t1 WHERE col IN (SELECT col FROM t2);
Subquery in FROMUses a query as a temporary tableSELECT * FROM (SELECT col FROM t1) AS sub;
Subquery in SELECTReturns a single value per rowSELECT col, (SELECT MAX(col) FROM t2) FROM t1;
WITH (CTE)Names a temporary result to reuseWITH name AS (SELECT * FROM t1) SELECT * FROM name;

13. Conditional Logic and NULL Handling

CommandWhat it doesSyntax
CASEIf-then-else inside a queryCASE WHEN cond THEN val1 ELSE val2 END
COALESCE()Returns the first non-NULL valueCOALESCE(col, 'default')
NULLIF()Returns NULL if two values are equalNULLIF(col1, col2)
IFNULL()Replaces NULL with a value (MySQL)IFNULL(col, 'default')

14. String Functions

FunctionWhat it doesSyntax
UPPER()Converts to uppercaseUPPER(col)
LOWER()Converts to lowercaseLOWER(col)
LENGTH()Returns text lengthLENGTH(col)
TRIM()Removes spaces from both endsTRIM(col)
SUBSTRING()Extracts part of a textSUBSTRING(col, start, length)
CONCAT()Joins texts togetherCONCAT(col1, ' ', col2)
REPLACE()Replaces text with other textREPLACE(col, 'old', 'new')

15. Numeric Functions

FunctionWhat it doesSyntax
ROUND()Rounds a numberROUND(col, 2)
CEIL()Rounds upCEIL(col)
FLOOR()Rounds downFLOOR(col)
ABS()Returns the absolute valueABS(col)
MOD()Returns the remainderMOD(col, 3)
POWER()Raises to a powerPOWER(col, 2)

16. Date Functions

FunctionWhat it doesSyntax
CURRENT_DATEReturns today's dateSELECT CURRENT_DATE;
NOW()Returns current date and timeSELECT NOW();
EXTRACT()Gets a part of a dateEXTRACT(YEAR FROM col)
DATE_PART()Gets a part of a date (PostgreSQL)DATE_PART('month', col)
DATEDIFF()Difference between two dates (MySQL)DATEDIFF(date1, date2)

17. Window Functions

FunctionWhat it doesSyntax
ROW_NUMBER()Gives a unique number to each rowROW_NUMBER() OVER (ORDER BY col)
RANK()Ranks rows, leaves gaps for tiesRANK() OVER (ORDER BY col DESC)
DENSE_RANK()Ranks rows, no gaps for tiesDENSE_RANK() OVER (ORDER BY col DESC)
PARTITION BYRestarts the calculation per groupROW_NUMBER() OVER (PARTITION BY col1 ORDER BY col2)
LAG()Gets value from the previous rowLAG(col) OVER (ORDER BY col2)
LEAD()Gets value from the next rowLEAD(col) OVER (ORDER BY col2)

18. Transactions (Data Safety)

CommandWhat it doesSyntax
BEGINStarts a transactionBEGIN;
COMMITSaves all changesCOMMIT;
ROLLBACKCancels all changesROLLBACK;
SAVEPOINTSets a point to roll back toSAVEPOINT name;

19. Permissions (DCL)

CommandWhat it doesSyntax
GRANTGives permission to a userGRANT SELECT ON table TO user;
REVOKETakes back a permissionREVOKE SELECT ON table FROM user;

20. Command Categories at a Glance

CategoryFull NameCommands
DQLData Query LanguageSELECT
DMLData Manipulation LanguageINSERT, UPDATE, DELETE
DDLData Definition LanguageCREATE, ALTER, DROP, TRUNCATE
DCLData Control LanguageGRANT, REVOKE
TCLTransaction ControlBEGIN, COMMIT, ROLLBACK, SAVEPOINT

21. Order of Writing a Query

sql
1SELECT columns
2FROM table
3JOIN other_table ON condition
4WHERE row_condition
5GROUP BY columns
6HAVING group_condition
7ORDER BY columns
8LIMIT number;

Order the database runs it: FROM → JOIN → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT

Next TopicAggregation