SQL Reference
Searchable SQL keyword and function reference with syntax examples
Showing 65 of 65 entries across 13 sections
SELECT
SELECT
Retrieves rows from one or more columns in a table.
SELECT column1, column2 FROM table_name;
SELECT first_name, last_name FROM employees;
SELECT DISTINCT
Returns only unique (non-duplicate) values.
SELECT DISTINCT column1 FROM table_name;
SELECT DISTINCT department FROM employees;
SELECT TOP / LIMIT
Restricts the number of rows returned.
-- SQL Server SELECT TOP 10 * FROM table_name; -- MySQL / PostgreSQL SELECT * FROM table_name LIMIT 10;
SELECT TOP 5 name, salary FROM employees ORDER BY salary DESC;
SELECT INTO
Copies rows from one table into a new table.
SELECT column1, column2 INTO new_table FROM source_table WHERE condition;
SELECT * INTO employees_backup FROM employees WHERE active = 1;
WHERE
Filters rows based on a condition. Supports =, <>, <, >, <=, >=, BETWEEN, LIKE, IN, IS NULL, AND, OR, NOT.
SELECT * FROM table_name WHERE condition;
SELECT * FROM employees WHERE department = 'Engineering' AND salary > 80000;
ORDER BY
Sorts the result set. ASC (default) is ascending; DESC is descending.
SELECT * FROM table_name ORDER BY column1 ASC, column2 DESC;
SELECT name, salary FROM employees ORDER BY salary DESC, name ASC;
GROUP BY
Groups rows that share the same values in specified columns, used with aggregate functions.
SELECT column, AGG_FUNC(col) FROM table_name GROUP BY column;
SELECT department, COUNT(*) AS headcount FROM employees GROUP BY department;
HAVING
Filters groups after GROUP BY (like WHERE but for aggregates).
SELECT column, AGG_FUNC(col) FROM table_name GROUP BY column HAVING condition;
SELECT department, COUNT(*) AS headcount FROM employees GROUP BY department HAVING COUNT(*) > 5;
UNION
Combines results of two queries and removes duplicates. Use UNION ALL to keep duplicates.
SELECT columns FROM table1 UNION SELECT columns FROM table2;
SELECT name FROM customers UNION SELECT name FROM prospects;
INTERSECT
Returns rows that appear in both result sets.
SELECT columns FROM table1 INTERSECT SELECT columns FROM table2;
SELECT email FROM newsletter_subscribers INTERSECT SELECT email FROM customers;
EXCEPT / MINUS
Returns rows in the first query that are not in the second.
-- Standard SQL / SQL Server / PostgreSQL SELECT columns FROM table1 EXCEPT SELECT columns FROM table2; -- Oracle SELECT columns FROM table1 MINUS SELECT columns FROM table2;
SELECT email FROM all_users EXCEPT SELECT email FROM unsubscribed;
INSERT
INSERT INTO
Adds one or more new rows to a table.
INSERT INTO table_name (column1, column2) VALUES (value1, value2);
INSERT INTO employees (first_name, last_name, department, salary)
VALUES ('Alice', 'Smith', 'Engineering', 95000);INSERT INTO SELECT
Copies rows from one table and inserts them into another.
INSERT INTO table_name (column1, column2) SELECT column1, column2 FROM source_table WHERE condition;
INSERT INTO employees_archive (id, name, department) SELECT id, name, department FROM employees WHERE termination_date IS NOT NULL;
UPDATE
UPDATE
Modifies existing rows. Always include a WHERE clause to avoid updating all rows.
UPDATE table_name SET column1 = value1, column2 = value2 WHERE condition;
UPDATE employees
SET salary = salary * 1.10,
title = 'Senior Engineer'
WHERE department = 'Engineering'
AND years_experience >= 5;DELETE
DELETE
Removes rows from a table. Always include WHERE to avoid deleting all rows. Can be rolled back.
DELETE FROM table_name WHERE condition;
DELETE FROM employees WHERE termination_date < '2020-01-01';
TRUNCATE
Removes all rows quickly without logging individual row deletions. Cannot be rolled back in most databases.
TRUNCATE TABLE table_name;
TRUNCATE TABLE session_logs;
CREATE
CREATE TABLE
Creates a new table with defined columns and data types.
CREATE TABLE table_name ( column1 datatype CONSTRAINT, column2 datatype, ... );
CREATE TABLE employees ( id INT PRIMARY KEY AUTO_INCREMENT, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, email VARCHAR(100) UNIQUE, salary DECIMAL(10,2) DEFAULT 0, hired_at DATE );
CREATE DATABASE
Creates a new database.
CREATE DATABASE database_name;
CREATE DATABASE company_db;
CREATE INDEX
Creates an index to speed up queries. UNIQUE prevents duplicate values.
CREATE [UNIQUE] INDEX index_name ON table_name (column1, column2);
CREATE INDEX idx_employees_email ON employees (email); CREATE UNIQUE INDEX idx_orders_ref ON orders (reference_number);
CREATE VIEW
Creates a virtual table based on a saved SELECT statement.
CREATE VIEW view_name AS SELECT columns FROM table_name WHERE condition;
CREATE VIEW engineering_team AS SELECT id, first_name, last_name, salary FROM employees WHERE department = 'Engineering';
ALTER
ALTER TABLE: ADD COLUMN
Adds a new column to an existing table.
ALTER TABLE table_name ADD column_name datatype;
ALTER TABLE employees ADD phone VARCHAR(20);
ALTER TABLE: DROP COLUMN
Removes a column from an existing table.
ALTER TABLE table_name DROP COLUMN column_name;
ALTER TABLE employees DROP COLUMN fax_number;
ALTER TABLE: MODIFY / ALTER COLUMN
Changes the data type or constraints of an existing column.
-- MySQL ALTER TABLE table_name MODIFY COLUMN column_name new_datatype; -- SQL Server / PostgreSQL ALTER TABLE table_name ALTER COLUMN column_name new_datatype;
ALTER TABLE employees MODIFY COLUMN salary DECIMAL(12, 2) NOT NULL;
ALTER TABLE: RENAME
Renames an existing table.
-- MySQL ALTER TABLE old_name RENAME TO new_name; -- SQL Server EXEC sp_rename 'old_name', 'new_name';
ALTER TABLE staff RENAME TO employees;
DROP
DROP TABLE
Permanently removes a table and all its data. IF EXISTS prevents an error if the table doesn't exist.
DROP TABLE [IF EXISTS] table_name;
DROP TABLE IF EXISTS temp_imports;
DROP DATABASE
Permanently removes a database and all its tables and data.
DROP DATABASE [IF EXISTS] database_name;
DROP DATABASE IF EXISTS legacy_db;
DROP INDEX
Removes an existing index.
-- MySQL DROP INDEX index_name ON table_name; -- SQL Server / PostgreSQL DROP INDEX index_name;
DROP INDEX idx_employees_email ON employees;
DROP VIEW
Removes an existing view.
DROP VIEW [IF EXISTS] view_name;
DROP VIEW IF EXISTS engineering_team;
JOINs
INNER JOIN
Returns rows where there is a match in both tables.
SELECT a.col, b.col FROM table_a a INNER JOIN table_b b ON a.id = b.a_id;
SELECT e.first_name, d.department_name FROM employees e INNER JOIN departments d ON e.department_id = d.id;
LEFT JOIN
Returns all rows from the left table, and matching rows from the right. Non-matching right-side columns are NULL.
SELECT a.col, b.col FROM table_a a LEFT JOIN table_b b ON a.id = b.a_id;
SELECT e.first_name, m.first_name AS manager FROM employees e LEFT JOIN employees m ON e.manager_id = m.id;
RIGHT JOIN
Returns all rows from the right table, and matching rows from the left. Non-matching left-side columns are NULL.
SELECT a.col, b.col FROM table_a a RIGHT JOIN table_b b ON a.id = b.a_id;
SELECT e.first_name, d.department_name FROM employees e RIGHT JOIN departments d ON e.department_id = d.id;
FULL OUTER JOIN
Returns all rows from both tables. Columns are NULL where no match exists.
SELECT a.col, b.col FROM table_a a FULL OUTER JOIN table_b b ON a.id = b.a_id;
SELECT c.name, o.order_date FROM customers c FULL OUTER JOIN orders o ON c.id = o.customer_id;
CROSS JOIN
Returns the Cartesian product of both tables: every row in A combined with every row in B.
SELECT * FROM table_a CROSS JOIN table_b;
SELECT s.size, c.color FROM sizes s CROSS JOIN colors c;
SELF JOIN
Joins a table to itself using aliases, useful for hierarchical data.
SELECT a.col, b.col FROM table_name a JOIN table_name b ON a.related_id = b.id;
SELECT e.first_name AS employee,
m.first_name AS manager
FROM employees e
JOIN employees m ON e.manager_id = m.id;Aggregate Functions
COUNT
Returns the number of rows. COUNT(*) counts all rows; COUNT(col) ignores NULLs.
COUNT(*) or COUNT(column_name)
SELECT department, COUNT(*) AS total FROM employees GROUP BY department;
SUM
Returns the total sum of a numeric column.
SUM(column_name)
SELECT department, SUM(salary) AS total_payroll FROM employees GROUP BY department;
AVG
Returns the average value of a numeric column.
AVG(column_name)
SELECT department, AVG(salary) AS avg_salary FROM employees GROUP BY department;
MIN
Returns the smallest value in a column.
MIN(column_name)
SELECT MIN(salary) AS lowest_salary FROM employees WHERE department = 'Engineering';
MAX
Returns the largest value in a column.
MAX(column_name)
SELECT department, MAX(salary) AS top_salary FROM employees GROUP BY department;
ROUND
Rounds a number to the specified number of decimal places.
ROUND(number, decimal_places)
SELECT first_name,
ROUND(salary / 12, 2) AS monthly_salary
FROM employees;COALESCE
Returns the first non-NULL value in the list. Useful for providing defaults.
COALESCE(value1, value2, ..., fallback)
SELECT first_name,
COALESCE(phone, mobile, 'No contact') AS contact
FROM employees;NULLIF
Returns NULL if both expressions are equal; otherwise returns expression1.
NULLIF(expression1, expression2)
-- Avoid division by zero SELECT total_sales / NULLIF(num_transactions, 0) FROM daily_stats;
String Functions
UPPER
Converts a string to all uppercase letters.
UPPER(string)
SELECT UPPER(first_name) FROM employees; -- 'alice' → 'ALICE'
LOWER
Converts a string to all lowercase letters.
LOWER(string)
SELECT LOWER(email) FROM employees; -- 'Alice@Example.COM' → 'alice@example.com'
LEN / LENGTH
Returns the number of characters in a string.
-- SQL Server LEN(string) -- MySQL / PostgreSQL LENGTH(string)
SELECT first_name, LEN(first_name) AS name_length FROM employees;
SUBSTRING
Extracts a portion of a string starting at start_pos for length characters.
SUBSTRING(string, start_pos, length) -- or SUBSTR(string, start, length)
SELECT SUBSTRING(phone, 1, 3) AS area_code FROM employees; -- '555-123-4567' → '555'
CONCAT
Joins two or more strings together.
CONCAT(string1, string2, ...) -- or string1 || string2 (PostgreSQL / SQLite)
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM employees;
TRIM
Removes leading and/or trailing whitespace (or specified characters) from a string.
TRIM([LEADING | TRAILING | BOTH] FROM string) -- or TRIM(string)
SELECT TRIM(email) AS clean_email FROM employees; -- ' alice@example.com ' → 'alice@example.com'
REPLACE
Replaces all occurrences of a substring within a string.
REPLACE(string, old_substring, new_substring)
SELECT REPLACE(phone, '-', '') AS phone_digits FROM employees; -- '555-123-4567' → '5551234567'
LIKE
Pattern matching operator. % matches any sequence; _ matches one character. Use NOT LIKE for inverse.
column LIKE pattern -- % = any sequence of characters -- _ = exactly one character
SELECT * FROM employees WHERE email LIKE '%@example.com'; SELECT * FROM employees WHERE first_name LIKE 'A_i%';
Date Functions
NOW()
Returns the current date and time.
NOW() -- or GETDATE() (SQL Server) / CURRENT_TIMESTAMP
SELECT NOW() AS current_datetime; -- 2024-03-15 14:30:00
CURDATE / CURRENT_DATE
Returns the current date without the time component.
CURDATE() -- MySQL CURRENT_DATE -- PostgreSQL / Standard SQL CAST(GETDATE() AS DATE) -- SQL Server
SELECT * FROM orders WHERE order_date = CURDATE();
DATEADD
Adds a time interval to a date.
-- SQL Server DATEADD(interval, number, date) -- MySQL DATE_ADD(date, INTERVAL number unit) -- PostgreSQL date + INTERVAL 'n unit'
-- SQL Server SELECT DATEADD(day, 30, order_date) AS due_date FROM orders; -- MySQL SELECT DATE_ADD(order_date, INTERVAL 30 DAY) AS due_date FROM orders;
DATEDIFF
Returns the number of days between two dates.
-- SQL Server / MySQL DATEDIFF(end_date, start_date) -- PostgreSQL end_date - start_date
SELECT DATEDIFF(NOW(), hired_at) AS days_employed FROM employees;
DATE_FORMAT / FORMAT
Formats a date value as a string using format patterns.
-- MySQL DATE_FORMAT(date, format_string) -- SQL Server FORMAT(date, format_string) -- PostgreSQL TO_CHAR(date, format_string)
-- MySQL SELECT DATE_FORMAT(hired_at, '%d %M %Y') AS hire_date FROM employees; -- '15 March 2024'
Constraints
PRIMARY KEY
Uniquely identifies each row. Cannot be NULL. A table can have only one primary key (which may span multiple columns).
-- Inline column_name datatype PRIMARY KEY -- Table-level PRIMARY KEY (col1, col2)
CREATE TABLE orders ( order_id INT PRIMARY KEY AUTO_INCREMENT, order_date DATE NOT NULL );
FOREIGN KEY
Enforces referential integrity between two tables. Options: CASCADE, SET NULL, RESTRICT, NO ACTION.
FOREIGN KEY (column_name) REFERENCES other_table (column_name) ON DELETE CASCADE ON UPDATE CASCADE
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
FOREIGN KEY (customer_id)
REFERENCES customers (id)
ON DELETE CASCADE
);UNIQUE
Ensures all values in a column (or combination of columns) are distinct.
column_name datatype UNIQUE -- or UNIQUE (col1, col2) at table level
CREATE TABLE users ( id INT PRIMARY KEY, email TEXT UNIQUE );
NOT NULL
Prevents NULL values from being stored in a column.
column_name datatype NOT NULL
CREATE TABLE products ( id INT PRIMARY KEY, name VARCHAR(100) NOT NULL, price DECIMAL(10,2) NOT NULL );
CHECK
Ensures that values in a column satisfy a specified condition.
CHECK (condition)
CREATE TABLE employees ( id INT PRIMARY KEY, salary DECIMAL(10,2) CHECK (salary >= 0), age INT CHECK (age BETWEEN 16 AND 120) );
DEFAULT
Provides a default value inserted when no value is specified.
column_name datatype DEFAULT default_value
CREATE TABLE orders ( id INT PRIMARY KEY, status VARCHAR(20) DEFAULT 'pending', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
Transactions
BEGIN / START TRANSACTION
Marks the start of an explicit transaction. All subsequent statements are part of the transaction until COMMIT or ROLLBACK.
-- SQL Server BEGIN TRANSACTION; -- MySQL / PostgreSQL START TRANSACTION;
START TRANSACTION; UPDATE accounts SET balance = balance - 500 WHERE id = 1; UPDATE accounts SET balance = balance + 500 WHERE id = 2;
COMMIT
Permanently saves all changes made within the current transaction.
COMMIT;
START TRANSACTION; INSERT INTO orders (customer_id, total) VALUES (42, 199.99); COMMIT;
ROLLBACK
Undoes all changes made in the current transaction (or back to a named savepoint).
ROLLBACK; -- or ROLLBACK TO SAVEPOINT savepoint_name;
START TRANSACTION; DELETE FROM orders WHERE id = 99; -- Something went wrong ROLLBACK;
SAVEPOINT
Creates a named point within a transaction you can roll back to without aborting the entire transaction.
SAVEPOINT savepoint_name; -- later: ROLLBACK TO SAVEPOINT savepoint_name; RELEASE SAVEPOINT savepoint_name;
START TRANSACTION;
INSERT INTO log (msg) VALUES ('start');
SAVEPOINT after_log;
DELETE FROM temp_data;
-- Undo only the delete:
ROLLBACK TO SAVEPOINT after_log;
COMMIT;