SELECT * FROM users;Return all columns from a table.
A massive searchable, copy-ready SQL reference covering querying, joins, grouping, subqueries, CTEs, window functions, schema design, constraints, indexes, transactions, security, performance, and vendor-specific notes for MySQL, PostgreSQL, SQL Server, and SQLite.
SELECT * FROM users;Return all columns from a table.
SELECT id, name FROM users;Return selected columns.
SELECT DISTINCT city FROM users;Return unique values.
SELECT name AS customer_name FROM users;Rename an output column.
SELECT * FROM users LIMIT 10;Return the first 10 rows in MySQL/PostgreSQL/SQLite.
SELECT TOP 10 * FROM users;Return the first 10 rows in SQL Server.
SELECT * FROM users FETCH FIRST 10 ROWS ONLY;ANSI-style row limiting on supported databases.
SELECT CURRENT_DATE;Return the current date.
SELECT CURRENT_TIMESTAMP;Return the current timestamp.
SELECT 2 + 2 AS result;Evaluate an expression.
SELECT * FROM users WHERE age >= 18;Filter rows by a comparison.
SELECT * FROM users WHERE status = 'active';Filter text values.
SELECT * FROM users WHERE age BETWEEN 18 AND 30;Filter within an inclusive range.
SELECT * FROM users WHERE city IN ('Lima','Columbus');Filter against a list.
SELECT * FROM users WHERE city NOT IN ('Lima','Columbus');Exclude listed values.
SELECT * FROM users WHERE email IS NULL;Find NULL values.
SELECT * FROM users WHERE email IS NOT NULL;Find non-NULL values.
SELECT * FROM users WHERE name LIKE 'A%';Wildcard match beginning with A.
SELECT * FROM users WHERE name LIKE '%son';Wildcard match ending in son.
SELECT * FROM users WHERE name LIKE '%tech%';Wildcard match containing text.
SELECT * FROM users WHERE age >= 18 AND status = 'active';Combine conditions with AND.
SELECT * FROM users WHERE role = 'admin' OR role = 'teacher';Combine conditions with OR.
SELECT * FROM users WHERE NOT status = 'disabled';Negate a condition.
SELECT * FROM users WHERE (role='admin' OR role='teacher') AND active=1;Group Boolean logic with parentheses.
SELECT * FROM users ORDER BY name ASC;Sort ascending.
SELECT * FROM users ORDER BY created_at DESC;Sort descending.
SELECT * FROM users ORDER BY role, name;Sort by multiple columns.
SELECT * FROM users ORDER BY 2;Sort by select-list position; valid but less readable.
SELECT * FROM users LIMIT 25 OFFSET 50;Paginate with LIMIT/OFFSET.
SELECT * FROM users ORDER BY id OFFSET 50 ROWS FETCH NEXT 25 ROWS ONLY;Paginate in SQL Server/ANSI-style syntax.
INSERT INTO users (name, email) VALUES ('Ada','[email protected]');Insert one row.
INSERT INTO users (name, email) VALUES ('Ada','[email protected]'),('Linus','[email protected]');Insert multiple rows.
INSERT INTO archive_users SELECT * FROM users WHERE active = 0;Insert rows from a query.
INSERT INTO users DEFAULT VALUES;Insert a row using default values where supported.
INSERT INTO users (name) VALUES ('Ada') RETURNING id;Insert and return generated data in PostgreSQL/SQLite versions supporting RETURNING.
UPDATE users SET status = 'active' WHERE id = 1;Update one row.
UPDATE users SET status='inactive', updated_at=CURRENT_TIMESTAMP WHERE id=1;Update multiple columns.
UPDATE users SET score = score + 10 WHERE active = 1;Update using the existing value.
UPDATE users SET department = 'IT';Update every row. ⚠
DELETE FROM users WHERE id = 1;Delete one matching row.
DELETE FROM users WHERE active = 0;Delete matching rows.
DELETE FROM users;Delete all rows while keeping the table. ⚠
TRUNCATE TABLE users;Quickly remove all rows from a table where supported. ⚠
CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(100));Create a simple table.
CREATE TABLE users (id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name VARCHAR(100));Create an identity column using standard-style syntax on supported systems.
CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100));MySQL auto-increment example.
CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT);SQLite auto-increment style.
CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT);Legacy/common PostgreSQL serial style.
CREATE TABLE users (id INT IDENTITY(1,1) PRIMARY KEY, name NVARCHAR(100));SQL Server identity style.
CREATE TABLE IF NOT EXISTS users (id INT PRIMARY KEY, name VARCHAR(100));Create only if missing where supported.
CREATE TABLE backup AS SELECT * FROM users;Create a table from query results on supported databases.
ALTER TABLE users ADD COLUMN phone VARCHAR(30);Add a column.
ALTER TABLE users DROP COLUMN phone;Drop a column. ⚠
ALTER TABLE users RENAME COLUMN name TO full_name;Rename a column on supported databases.
ALTER TABLE users RENAME TO app_users;Rename a table.
ALTER TABLE users ADD CONSTRAINT uq_users_email UNIQUE (email);Add a unique constraint.
ALTER TABLE orders ADD CONSTRAINT fk_orders_user FOREIGN KEY (user_id) REFERENCES users(id);Add a foreign key.
ALTER TABLE users ALTER COLUMN name SET NOT NULL;Set NOT NULL in PostgreSQL-style syntax.
ALTER TABLE users MODIFY name VARCHAR(150) NOT NULL;Modify column definition in MySQL.
DROP TABLE users;Delete a table and its data. ⚠
DROP TABLE IF EXISTS users;Delete a table only if it exists. ⚠
DROP DATABASE appdb;Delete an entire database. ⚠
TRUNCATE TABLE logs;Remove all rows quickly. ⚠
DROP VIEW active_users;Delete a view.
DROP INDEX idx_users_email;Drop an index; syntax varies by database.
INTWhole-number type.
BIGINTLarge whole-number type.
SMALLINTSmaller whole-number type.
DECIMAL(10,2)Exact numeric type suitable for money-like values.
NUMERIC(10,2)Exact numeric type, often equivalent to DECIMAL.
REALFloating-point type.
DOUBLE PRECISIONDouble-precision floating-point type.
VARCHAR(255)Variable-length text.
CHAR(2)Fixed-length text.
TEXTLarge or unbounded text on many databases.
DATECalendar date.
TIMETime of day.
TIMESTAMPDate and time.
BOOLEANTrue/false type where supported.
BLOBBinary large object.
JSONNative JSON type on databases that support it.
PRIMARY KEY (id)Uniquely identify each row.
FOREIGN KEY (user_id) REFERENCES users(id)Enforce referential integrity.
UNIQUE (email)Require unique values.
NOT NULLDisallow NULL.
CHECK (age >= 0)Require a condition to be true.
DEFAULT 'active'Provide a default value.
CONSTRAINT pk_users PRIMARY KEY (id)Create a named constraint.
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADEDelete child rows when the parent is deleted.
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULLSet child foreign key to NULL when parent is deleted.
SELECT COUNT(*) FROM users;Count rows.
SELECT COUNT(email) FROM users;Count non-NULL email values.
SELECT COUNT(DISTINCT city) FROM users;Count distinct values.
SELECT SUM(amount) FROM orders;Sum numeric values.
SELECT AVG(amount) FROM orders;Average numeric values.
SELECT MIN(amount) FROM orders;Smallest value.
SELECT MAX(amount) FROM orders;Largest value.
SELECT MIN(created_at), MAX(created_at) FROM users;Get earliest and latest values.
SELECT city, COUNT(*) FROM users GROUP BY city;Count rows per city.
SELECT department, AVG(salary) FROM employees GROUP BY department;Average by group.
SELECT city, COUNT(*) FROM users GROUP BY city HAVING COUNT(*) > 10;Filter groups after aggregation.
SELECT department, SUM(salary) FROM employees GROUP BY department HAVING SUM(salary) > 100000;Filter aggregate totals.
SELECT department, role, COUNT(*) FROM employees GROUP BY department, role;Group by multiple columns.
SELECT u.name, o.total FROM users u INNER JOIN orders o ON o.user_id = u.id;Return only matching rows.
SELECT * FROM a JOIN b ON a.id = b.a_id;JOIN defaults to INNER JOIN in common SQL dialects.
SELECT u.name, d.name AS department FROM users u JOIN departments d ON d.id = u.department_id;Join lookup data.
SELECT u.name, o.id FROM users u LEFT JOIN orders o ON o.user_id = u.id;Keep all rows from the left table.
SELECT u.name, o.id FROM users u RIGHT JOIN orders o ON o.user_id = u.id;Keep all rows from the right table where supported.
SELECT * FROM a FULL OUTER JOIN b ON a.id = b.id;Keep rows from both sides where supported.
SELECT u.* FROM users u LEFT JOIN orders o ON o.user_id=u.id WHERE o.id IS NULL;Find left-side rows with no match.
SELECT * FROM colors CROSS JOIN sizes;Return every combination of rows.
SELECT e.name, m.name AS manager FROM employees e LEFT JOIN employees m ON e.manager_id = m.id;Self-join to a manager row.
SELECT * FROM users WHERE id IN (SELECT user_id FROM orders);Filter using a subquery.
SELECT * FROM users WHERE EXISTS (SELECT 1 FROM orders o WHERE o.user_id = users.id);Filter using EXISTS.
SELECT * FROM users WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.user_id = users.id);Find rows with no related row.
SELECT name, (SELECT COUNT(*) FROM orders o WHERE o.user_id=u.id) AS order_count FROM users u;Use a correlated scalar subquery.
SELECT * FROM products WHERE price > (SELECT AVG(price) FROM products);Compare against an aggregate subquery.
WITH active_users AS (SELECT * FROM users WHERE active=1) SELECT * FROM active_users;Define a common table expression.
WITH totals AS (SELECT user_id, SUM(total) total FROM orders GROUP BY user_id) SELECT * FROM totals;Use a CTE for grouped data.
WITH a AS (...), b AS (...) SELECT * FROM a JOIN b ON ...;Define multiple CTEs.
WITH RECURSIVE nums(n) AS (SELECT 1 UNION ALL SELECT n+1 FROM nums WHERE n<10) SELECT * FROM nums;Recursive CTE example for supported databases.
SELECT email FROM customers UNION SELECT email FROM leads;Combine results and remove duplicates.
SELECT email FROM customers UNION ALL SELECT email FROM leads;Combine results and keep duplicates.
SELECT id FROM a INTERSECT SELECT id FROM b;Return values present in both sets where supported.
SELECT id FROM a EXCEPT SELECT id FROM b;Return values present only in the first set where supported.
SELECT name, CASE WHEN age>=18 THEN 'adult' ELSE 'minor' END AS category FROM users;Conditional output.
SELECT CASE status WHEN 'A' THEN 'Active' WHEN 'I' THEN 'Inactive' ELSE 'Other' END FROM users;Simple CASE expression.
ORDER BY CASE WHEN priority='high' THEN 1 WHEN priority='medium' THEN 2 ELSE 3 END;Custom sort order.
COALESCE(phone, 'N/A')Return the first non-NULL value.
NULLIF(a, b)Return NULL when two expressions are equal.
IS NULLTest for NULL.
IS NOT NULLTest for non-NULL.
COALESCE(discount, 0)Common pattern for replacing NULL numerics.
UPPER(name)Convert text to uppercase.
LOWER(name)Convert text to lowercase.
TRIM(name)Remove surrounding whitespace.
LENGTH(name)Return string length on many databases.
CHAR_LENGTH(name)ANSI-style character length.
SUBSTRING(name FROM 1 FOR 3)ANSI-style substring on supported databases.
SUBSTRING(name, 1, 3)Common substring syntax.
CONCAT(first_name, ' ', last_name)Concatenate text.
REPLACE(name, 'old', 'new')Replace text.
POSITION('a' IN name)Find substring position in ANSI-style syntax.
ROUND(price, 2)Round numeric value.
ABS(balance)Absolute value.
CEILING(price)Round upward.
FLOOR(price)Round downward.
POWER(2, 8)Exponentiation.
MOD(10, 3)Remainder.
CURRENT_DATECurrent date.
CURRENT_TIMECurrent time.
CURRENT_TIMESTAMPCurrent date and time.
EXTRACT(YEAR FROM created_at)Extract date/time component.
DATE_TRUNC('month', created_at)Truncate timestamp in PostgreSQL.
DATEADD(day, 7, created_at)Add time in SQL Server.
DATEDIFF(day, start_date, end_date)Difference in SQL Server.
created_at + INTERVAL '7 days'Add interval in PostgreSQL.
DATE(created_at)Extract date portion in MySQL/SQLite-style usage.
ROW_NUMBER() OVER (ORDER BY score DESC)Assign sequential row numbers.
RANK() OVER (ORDER BY score DESC)Rank rows with gaps after ties.
DENSE_RANK() OVER (ORDER BY score DESC)Rank rows without gaps after ties.
COUNT(*) OVER ()Return total row count alongside each row.
SUM(amount) OVER (PARTITION BY user_id)Calculate per-user total without grouping away rows.
AVG(score) OVER (PARTITION BY class_id)Calculate per-group average.
SUM(amount) OVER (ORDER BY created_at)Running total.
LAG(amount) OVER (ORDER BY created_at)Read previous row value.
LEAD(amount) OVER (ORDER BY created_at)Read next row value.
FIRST_VALUE(score) OVER (PARTITION BY team ORDER BY created_at)Get first value in each window.
WITH x AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) rn FROM employees) SELECT * FROM x WHERE rn <= 3;Top 3 salaries per department.
WITH x AS (SELECT *, RANK() OVER (PARTITION BY category ORDER BY score DESC) rnk FROM items) SELECT * FROM x WHERE rnk = 1;Top-ranked rows per category, preserving ties.
CREATE VIEW active_users AS SELECT * FROM users WHERE active=1;Create a view.
CREATE OR REPLACE VIEW active_users AS SELECT id,name FROM users WHERE active=1;Replace a view where supported.
SELECT * FROM active_users;Query a view.
DROP VIEW active_users;Delete a view.
CREATE INDEX idx_users_email ON users(email);Create a basic index.
CREATE UNIQUE INDEX idx_users_email_uq ON users(email);Create a unique index.
CREATE INDEX idx_orders_user_date ON orders(user_id, created_at);Create a composite index.
DROP INDEX idx_users_email;Drop an index; vendor syntax can vary.
CREATE INDEX idx_active_users ON users(id) WHERE active=1;Create a partial index in PostgreSQL/SQLite.
BEGIN;Start a transaction in PostgreSQL/SQLite-style syntax.
START TRANSACTION;Start a transaction in MySQL-style syntax.
BEGIN TRANSACTION;Start a transaction in SQL Server-style syntax.
COMMIT;Persist transaction changes.
ROLLBACK;Undo uncommitted transaction changes.
SAVEPOINT before_update;Create a savepoint.
ROLLBACK TO SAVEPOINT before_update;Rollback part of a transaction.
RELEASE SAVEPOINT before_update;Release a savepoint.
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;Set common isolation level.
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;Use repeatable-read isolation.
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;Use strongest common isolation level.
SELECT * FROM users WHERE id=1 FOR UPDATE;Lock selected rows for update on supported databases.
SELECT * FROM jobs WHERE status='new' FOR UPDATE SKIP LOCKED;Lock work rows while skipping rows locked elsewhere on supported databases.
PRIMARY KEYUniquely identifies a row.
FOREIGN KEYReferences a key in another table.
UNIQUECandidate key or uniqueness rule.
ON DELETE CASCADECascade parent deletions to children.
ON UPDATE CASCADECascade key updates where supported.
FOREIGN KEY (manager_id) REFERENCES employees(id)Self-referencing relationship.
1NFAtomic column values and no repeating groups.
2NF1NF plus no partial dependency on a composite key.
3NF2NF plus no transitive dependency on non-key attributes.
BCNFEvery determinant is a candidate key.
junction tableUse for many-to-many relationships.
surrogate keyArtificial identifier such as an identity integer or UUID.
natural keyMeaningful real-world key such as a unique code.
CREATE PROCEDURE ...Create a stored procedure; exact syntax is vendor-specific.
CREATE FUNCTION ... RETURNS ...Create a stored function; exact syntax is vendor-specific.
CALL procedure_name(...);Invoke a stored procedure in MySQL/PostgreSQL-style environments.
EXEC procedure_name ...;Invoke a procedure in SQL Server.
DROP PROCEDURE procedure_name;Delete a stored procedure.
DROP FUNCTION function_name;Delete a stored function.
CREATE TRIGGER ...Create a trigger; syntax varies by database.
BEFORE INSERTTrigger timing/event pattern.
AFTER UPDATETrigger after rows are updated.
OLD.column_nameReference old row values in several SQL dialects.
NEW.column_nameReference new row values in several SQL dialects.
DROP TRIGGER trigger_name;Delete a trigger; syntax varies.
GRANT SELECT ON users TO analyst;Grant read permission.
GRANT INSERT, UPDATE ON users TO app_user;Grant write permissions.
REVOKE UPDATE ON users FROM app_user;Remove permission.
GRANT ALL PRIVILEGES ON database_name.* TO 'user'@'host';MySQL-style broad grant.
CREATE ROLE analyst;Create a role where supported.
GRANT analyst TO alice;Grant a role to a user on supported systems.
CREATE DATABASE appdb;Create a database.
CREATE SCHEMA reporting;Create a schema.
SET search_path TO reporting, public;Set PostgreSQL schema search path.
USE appdb;Select a database in MySQL/SQL Server.
DROP SCHEMA reporting CASCADE;Delete a schema and dependent objects in PostgreSQL. ⚠
SELECT * FROM information_schema.tables;List table metadata in standard information schema.
SELECT * FROM information_schema.columns WHERE table_name='users';Inspect columns.
SELECT * FROM information_schema.table_constraints WHERE table_name='users';Inspect constraints.
PRAGMA table_info(users);Inspect SQLite table columns.
SHOW TABLES;List tables in MySQL.
DESCRIBE users;Describe table columns in MySQL.
\d usersDescribe a table in PostgreSQL psql.
EXPLAIN SELECT * FROM users WHERE email='[email protected]';Show query plan.
EXPLAIN ANALYZE SELECT * FROM users WHERE email='[email protected]';Execute and show actual plan/runtime on supported databases.
SET STATISTICS IO ON;Show I/O statistics in SQL Server.
SET STATISTICS TIME ON;Show timing information in SQL Server.
ANALYZE users;Refresh planner statistics on supported databases.
VACUUM;Reclaim/organize storage in PostgreSQL/SQLite-style systems; behavior differs.
SELECT VERSION();Show MySQL version.
SHOW DATABASES;List databases.
SHOW TABLES;List tables in current database.
SHOW CREATE TABLE users;Show table DDL.
AUTO_INCREMENTMySQL identity/auto-number keyword.
IFNULL(value, 0)MySQL-style NULL replacement.
DATE_FORMAT(created_at, '%Y-%m-%d')Format a date in MySQL.
INSERT ... ON DUPLICATE KEY UPDATE ...MySQL upsert pattern.
SELECT version();Show PostgreSQL version.
\lList databases in psql.
\dtList tables in psql.
\d usersDescribe a table in psql.
RETURNING *Return affected rows from INSERT/UPDATE/DELETE.
ILIKE '%text%'Case-insensitive pattern match.
INSERT ... ON CONFLICT (...) DO UPDATE ...PostgreSQL upsert pattern.
GENERATED ALWAYS AS IDENTITYPreferred modern PostgreSQL identity syntax.
jsonbBinary JSON type with indexing capabilities.
SELECT @@VERSION;Show SQL Server version.
SELECT TOP 10 * FROM users;Limit rows.
IDENTITY(1,1)Auto-numbering column property.
GETDATE()Current date/time.
ISNULL(value, 0)Replace NULL with a fallback.
LEN(name)String length.
STRING_AGG(name, ',')Aggregate strings.
MERGE ...SQL Server merge/upsert-style statement; use carefully.
EXEC sp_help 'users';Show object information.
SELECT sqlite_version();Show SQLite version.
.tablesList tables in sqlite3 shell.
.schema usersShow table schema in sqlite3 shell.
PRAGMA table_info(users);Inspect columns.
INTEGER PRIMARY KEYAliases SQLite rowid behavior.
INSERT OR REPLACE INTO ...SQLite replacement/upsert-style syntax.
INSERT ... ON CONFLICT(...) DO UPDATE SET ...SQLite UPSERT syntax on modern versions.
datetime('now')Current UTC date/time string.
BACKUP DATABASE ...SQL Server backup statement; syntax depends on destination.
RESTORE DATABASE ...SQL Server restore statement.
pg_dump appdb > backup.sqlPostgreSQL logical backup from shell.
psql appdb < backup.sqlRestore PostgreSQL SQL dump from shell.
mysqldump appdb > backup.sqlMySQL logical backup from shell.
mysql appdb < backup.sqlRestore MySQL SQL dump from shell.
.backup backup.dbSQLite shell backup command.
SELECT * FROM users WHERE created_at >= CURRENT_DATE - INTERVAL '7 days';Rows from the last seven days in PostgreSQL-style syntax.
SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1;Find duplicate emails.
DELETE FROM users WHERE id NOT IN (SELECT MIN(id) FROM users GROUP BY email);Simple duplicate-removal pattern. ⚠ Verify carefully before running.
SELECT * FROM users ORDER BY RANDOM() LIMIT 1;Random row in PostgreSQL/SQLite.
SELECT * FROM users ORDER BY RAND() LIMIT 1;Random row in MySQL.
SELECT * FROM users ORDER BY NEWID();Randomized order in SQL Server.
SELECT department, COUNT(*) FROM employees GROUP BY department ORDER BY COUNT(*) DESC;Count rows by category.
SELECT DATE(created_at), COUNT(*) FROM events GROUP BY DATE(created_at);Daily counts on databases supporting DATE().
SELECT user_id, SUM(total) AS lifetime_value FROM orders GROUP BY user_id ORDER BY lifetime_value DESC;Rank users by total order value.
WHERE column = NULLWrong: use IS NULL because NULL is not equal to anything.
SELECT *Convenient, but avoid it in stable production interfaces when you only need specific columns.
UPDATE users SET active=0;Missing WHERE updates every row. ⚠
DELETE FROM users;Missing WHERE deletes every row. ⚠
NOT IN (subquery_with_nulls)NULLs can make NOT IN behave unexpectedly; NOT EXISTS is often safer.
FLOAT for moneyPrefer DECIMAL/NUMERIC for exact financial values.
function(column) in WHEREWrapping indexed columns in functions can prevent index use.
OFFSET pagination on huge tablesLarge offsets can be slow; keyset/seek pagination is often better.
SELECT COUNT(*) FROM table_name;Count rows.
SELECT DISTINCT column_name FROM table_name;List unique values.
SELECT column_name, COUNT(*) FROM table_name GROUP BY column_name ORDER BY COUNT(*) DESC;Frequency table.
SELECT * FROM table_name ORDER BY created_at DESC LIMIT 1;Newest row in LIMIT-capable databases.
SELECT MIN(value), MAX(value), AVG(value) FROM table_name;Quick numeric summary.
SELECT * FROM users WHERE name LIKE '%test%';Simple contains search.
SELECT table_name FROM information_schema.tables WHERE table_schema='public';List PostgreSQL public-schema tables.
SELECT name FROM sqlite_master WHERE type='table';List SQLite tables.
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE';List base tables using information schema.