SQL

SQL Cheatsheet

Standard SQL syntax for querying and modifying relational databases - works across MySQL, PostgreSQL, and SQL Server with minor dialect differences.

Querying

SELECT * FROM table

Select all columns

SELECT a, b FROM table

Select specific columns

WHERE condition

Filter rows

ORDER BY col DESC

Sort results

LIMIT 10

Limit number of rows returned

DISTINCT

Remove duplicate rows

Joins

INNER JOIN b ON a.id = b.a_id

Only matching rows in both tables

LEFT JOIN b ON a.id = b.a_id

All rows from left, matched rows from right

RIGHT JOIN b ON a.id = b.a_id

All rows from right, matched rows from left

Aggregation

COUNT(*)

Count rows

SUM(col)

Sum a column

AVG(col)

Average of a column

GROUP BY col

Group rows for aggregation

HAVING condition

Filter after grouping

Modifying data

INSERT INTO t (a,b) VALUES (1,2)

Insert a row

UPDATE t SET a=1 WHERE id=1

Update rows

DELETE FROM t WHERE id=1

Delete rows

CREATE TABLE t (id INT PRIMARY KEY)

Create a table