SQL Command Reference

Querying (DQL)

Statement What it does Example
SELECT Retrieves data from a database SELECT * FROM users;
SELECT DISTINCT Returns unique values SELECT DISTINCT city FROM users;
SELECT ... AS Aliases a column SELECT name AS full_name FROM users;

Filtering & Sorting

Statement What it does Example
WHERE Filters records SELECT * FROM users WHERE age > 18;
LIKE Searches for a specified pattern in a column SELECT * FROM users WHERE name LIKE 'J%';
IN Checks if a value exists in a list SELECT * FROM users WHERE city IN ('New York', 'Los Angeles');

Joins

Statement What it does Example
INNER JOIN Returns records that have matching values in both tables SELECT users.name, orders.order_id FROM users INNER JOIN orders ON users.id = orders.user_id;
LEFT JOIN Returns all records from the left table, and the matched records from the right table SELECT users.name, orders.order_id FROM users LEFT JOIN orders ON users.id = orders.user_id;
RIGHT JOIN Returns all records from the right table, and the matched records from the left table SELECT users.name, orders.order_id FROM users RIGHT JOIN orders ON users.id = orders.user_id;

Aggregation & Grouping

Statement What it does Example
COUNT Returns the number of rows SELECT COUNT(*) FROM users;
SUM Returns the sum of a numeric column SELECT SUM(salary) FROM users;
AVG Returns the average value of a numeric column SELECT AVG(salary) FROM users;

Modifying Data (DML)

Statement What it does Example
INSERT INTO Inserts new records into a table INSERT INTO users (name, age) VALUES ('John', 30);
UPDATE Updates existing records in a table UPDATE users SET age = 31 WHERE name = 'John';
DELETE Deletes records from a table DELETE FROM users WHERE name = 'John';

Schema (DDL)

Statement What it does Example
CREATE TABLE Creates a new table CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(255), age INT);
ALTER TABLE Modifies an existing table ALTER TABLE users ADD COLUMN email VARCHAR(255);
DROP TABLE Deletes a table DROP TABLE users;

Constraints & Indexes

Statement What it does Example
PRIMARY KEY Uniquely identifies each record in a table CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(255), age INT);
FOREIGN KEY Links two tables together CREATE TABLE orders (id INT PRIMARY KEY, user_id INT, product_id INT, FOREIGN KEY (user_id) REFERENCES users(id));
UNIQUE Ensures that all values in a column are unique CREATE TABLE users (id INT PRIMARY KEY, email VARCHAR(255) UNIQUE, name VARCHAR(255));