Programming · Cheatsheet
SQL Reference Cheatsheet
Common SQL clauses for queries, joins, aggregation, data changes, tables, and indexes. Check the database dialect.
43 commands 7 sections
No entry matches that filter.
-
SELECT * FROM tableSelect all columns from table -
SELECT col1, col2 FROM tableSelect specific columns -
SELECT DISTINCT col FROM tableSelect unique values only -
SELECT col AS alias FROM tableColumn alias -
SELECT COUNT(*) FROM tableCount total rows -
SELECT * FROM table LIMIT 10Limit results to 10 rows -
SELECT * FROM table LIMIT 10 OFFSET 20Pagination (skip 20, take 10)
-
WHERE col = valueFilter by exact match -
WHERE col != value / WHERE col <> valueNot equal -
WHERE col > 10 AND col < 100Range with AND -
WHERE col IN (1, 2, 3)Match any value in list -
WHERE col NOT IN (1, 2, 3)Exclude values in list -
WHERE col BETWEEN 10 AND 100Range inclusive -
WHERE col LIKE "%pattern%"Pattern match (% = any chars) -
WHERE col IS NULL / IS NOT NULLCheck for NULL values -
ORDER BY col ASC|DESCSort results -
ORDER BY col1 ASC, col2 DESCMulti-column sort
-
INNER JOIN t2 ON t1.id = t2.fkOnly matching rows from both tables -
LEFT JOIN t2 ON t1.id = t2.fkAll from left + matching from right -
RIGHT JOIN t2 ON t1.id = t2.fkAll from right + matching from left -
FULL OUTER JOIN t2 ON t1.id = t2.fkAll rows from both tables -
CROSS JOIN t2Cartesian product (all combinations) -
self JOIN: FROM t1 a JOIN t1 bJoin table with itself
-
COUNT(col) / COUNT(*)Count non-null values / all rows -
SUM(col)Sum of values -
AVG(col)Average of values -
MIN(col) / MAX(col)Minimum / maximum value -
GROUP BY colGroup rows by column -
HAVING COUNT(*) > 5Filter groups (like WHERE for groups)
-
INSERT INTO t (col) VALUES (val)Insert single row -
INSERT INTO t (col) VALUES (v1), (v2)Insert multiple rows -
UPDATE t SET col = val WHERE id = 1Update specific rows -
DELETE FROM t WHERE id = 1Delete specific rows -
TRUNCATE TABLE tRemove all rows; logging, locking, and rollback behavior depend on the database
-
CREATE TABLE t (id INT PRIMARY KEY, ...)Create table -
ALTER TABLE t ADD col TYPEAdd column -
ALTER TABLE t DROP COLUMN colRemove column -
ALTER TABLE t RENAME TO new_nameRename table -
DROP TABLE tDelete table -
CREATE INDEX idx ON t(col)Create index
-
https://www.postgresql.org/docs/current/queries.htmlPostgreSQL query reference: clauses, joins, grouping, and limits. -
https://www.postgresql.org/docs/current/sql-truncate.htmlPostgreSQL TRUNCATE: locking and transaction behavior. -
https://dev.mysql.com/doc/refman/8.4/en/truncate-table.htmlMySQL 8.4 TRUNCATE: implicit commits and binary logging.