SQL Basics Cheat Sheet

Essential commands for interacting with relational databases.

Data Query Language (DQL)

SELECT

Select all columns from a table.

SELECT * FROM table_name;

SELECT DISTINCT

Select only unique values.

SELECT DISTINCT column FROM table;

WHERE

Filter records.

SELECT * FROM table WHERE condition;

ORDER BY

Sort the result set.

SELECT * FROM table ORDER BY column ASC|DESC;

Data Manipulation Language (DML)

INSERT INTO

Insert new records.

INSERT INTO table (col1, col2) VALUES (val1, val2);

UPDATE

Modify existing records.

UPDATE table SET col1 = val1 WHERE condition;

DELETE

Delete existing records.

DELETE FROM table WHERE condition;

Joins

INNER JOIN

Returns records that have matching values in both tables.

SELECT * FROM t1 INNER JOIN t2 ON t1.id = t2.id;

LEFT JOIN

Returns all records from the left table, and the matched records from the right table.

SELECT * FROM t1 LEFT JOIN t2 ON t1.id = t2.id;

Aggregation

COUNT

Returns the number of rows.

SELECT COUNT(column) FROM table;

SUM

Returns the total sum of a numeric column.

SELECT SUM(column) FROM table;

AVG

Returns the average value of a numeric column.

SELECT AVG(column) FROM table;

GROUP BY

Group rows that have the same values.

SELECT col, COUNT(*) FROM table GROUP BY col;