Programming40 entries

SQL Reference

SELECT, JOIN, GROUP BY, subqueries, indexes, and database manipulation commands

1Querying Data

SELECT * FROM table
Select all columns from table
SELECT col1, col2 FROM table
Select specific columns
SELECT DISTINCT col FROM table
Select unique values only
SELECT col AS alias FROM table
Column alias
SELECT COUNT(*) FROM table
Count total rows
SELECT * FROM table LIMIT 10
Limit results to 10 rows
SELECT * FROM table LIMIT 10 OFFSET 20
Pagination (skip 20, take 10)

2Filtering & Sorting

WHERE col = value
Filter by exact match
WHERE col != value / WHERE col <> value
Not equal
WHERE col > 10 AND col < 100
Range 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 100
Range inclusive
WHERE col LIKE "%pattern%"
Pattern match (% = any chars)
WHERE col IS NULL / IS NOT NULL
Check for NULL values
ORDER BY col ASC|DESC
Sort results
ORDER BY col1 ASC, col2 DESC
Multi-column sort

3Joins

INNER JOIN t2 ON t1.id = t2.fk
Only matching rows from both tables
LEFT JOIN t2 ON t1.id = t2.fk
All from left + matching from right
RIGHT JOIN t2 ON t1.id = t2.fk
All from right + matching from left
FULL OUTER JOIN t2 ON t1.id = t2.fk
All rows from both tables
CROSS JOIN t2
Cartesian product (all combinations)
self JOIN: FROM t1 a JOIN t1 b
Join table with itself

4Aggregation

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 col
Group rows by column
HAVING COUNT(*) > 5
Filter groups (like WHERE for groups)

5Data Modification

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 = 1
Update specific rows
DELETE FROM t WHERE id = 1
Delete specific rows
TRUNCATE TABLE t
Remove all rows (fast, no logging)

6Table Operations

CREATE TABLE t (id INT PRIMARY KEY, ...)
Create table
ALTER TABLE t ADD col TYPE
Add column
ALTER TABLE t DROP COLUMN col
Remove column
ALTER TABLE t RENAME TO new_name
Rename table
DROP TABLE t
Delete table
CREATE INDEX idx ON t(col)
Create index