SQL Basics Cheat Sheet

Essential SQL commands and syntax for querying, modifying, and managing relational databases. Bookmark this page for quick reference.

Data Queries

SyntaxDescription
SELECT col1, col2 FROM tableRetrieve specific columns from a table
SELECT * FROM tableRetrieve all columns from a table
SELECT DISTINCT col FROM tableReturn only unique values in the result set
SELECT col FROM table WHERE conditionFilter rows based on a condition
WHERE col = 'value'Match rows where column equals a specific value
WHERE col LIKE 'A%'Match rows where column starts with "A" (% = any characters)
WHERE col LIKE '%word%'Match rows containing "word" anywhere in the column
WHERE col IN ('a', 'b', 'c')Match rows where column value is in the given list
WHERE col BETWEEN 10 AND 50Match rows where column value is within a range (inclusive)
WHERE col IS NULLMatch rows where the column has no value
WHERE col IS NOT NULLMatch rows where the column has a value
ORDER BY col ASCSort results in ascending order (default)
ORDER BY col DESCSort results in descending order
LIMIT 10Return only the first 10 rows
LIMIT 10 OFFSET 20Skip 20 rows, then return the next 10

Joins

SyntaxDescription
SELECT * FROM a INNER JOIN b ON a.id = b.a_idReturn rows that have matching values in both tables
SELECT * FROM a LEFT JOIN b ON a.id = b.a_idReturn all rows from the left table, with matches from the right (or NULL)
SELECT * FROM a RIGHT JOIN b ON a.id = b.a_idReturn all rows from the right table, with matches from the left (or NULL)
SELECT * FROM a FULL OUTER JOIN b ON a.id = b.a_idReturn all rows from both tables, with NULLs where there is no match
SELECT * FROM a CROSS JOIN bReturn the Cartesian product of both tables (every combination)
SELECT * FROM emp e1 JOIN emp e2 ON e1.mgr_id = e2.idSelf join — join a table to itself using aliases

Aggregation

SyntaxDescription
SELECT COUNT(*) FROM tableCount the total number of rows
SELECT COUNT(col) FROM tableCount non-NULL values in a column
SELECT COUNT(DISTINCT col) FROM tableCount the number of unique non-NULL values
SELECT SUM(col) FROM tableCalculate the sum of a numeric column
SELECT AVG(col) FROM tableCalculate the average of a numeric column
SELECT MIN(col) FROM tableReturn the smallest value in a column
SELECT MAX(col) FROM tableReturn the largest value in a column
GROUP BY colGroup rows sharing a value so aggregate functions apply per group
GROUP BY col HAVING COUNT(*) > 5Filter groups after aggregation (like WHERE but for groups)

Data Modification

SyntaxDescription
INSERT INTO table (col1, col2) VALUES ('a', 'b')Insert a single row with specified values
INSERT INTO table (col1, col2) VALUES ('a', 'b'), ('c', 'd')Insert multiple rows in a single statement
INSERT INTO table SELECT ... FROM other_tableInsert rows from the result of a SELECT query
UPDATE table SET col = 'value' WHERE id = 1Update specific rows matching the WHERE condition
UPDATE table SET col1 = 'a', col2 = 'b' WHERE id = 1Update multiple columns in a single statement
DELETE FROM table WHERE id = 1Delete rows matching the WHERE condition
MERGE INTO target USING source ON ... WHEN MATCHED THEN UPDATE ... WHEN NOT MATCHED THEN INSERT ...Upsert — insert or update depending on whether the row exists

Table Operations

SyntaxDescription
CREATE TABLE t (id INT PRIMARY KEY, name VARCHAR(100))Create a new table with columns and types
CREATE TABLE new_t AS SELECT * FROM old_tCreate a new table from the results of a query
ALTER TABLE t ADD col VARCHAR(50)Add a new column to an existing table
ALTER TABLE t DROP COLUMN colRemove a column from an existing table
ALTER TABLE t RENAME COLUMN old TO newRename a column
DROP TABLE tPermanently delete a table and all its data
TRUNCATE TABLE tDelete all rows from a table quickly (cannot be rolled back in some DBs)
INT, BIGINT, SMALLINTInteger data types (whole numbers of various sizes)
DECIMAL(p, s), NUMERIC(p, s)Exact numeric types with precision and scale
VARCHAR(n), CHAR(n), TEXTString data types (variable-length, fixed-length, unlimited)
DATE, TIME, TIMESTAMPDate and time data types
BOOLEANTrue/false data type

Indexes & Constraints

SyntaxDescription
col INT PRIMARY KEYUniquely identifies each row; cannot be NULL
FOREIGN KEY (col) REFERENCES other(id)Enforce a link between data in two tables
col VARCHAR(50) UNIQUEEnsure all values in a column are different
col INT NOT NULLPrevent NULL values in a column
col INT DEFAULT 0Set a default value when none is provided
CHECK (col > 0)Ensure column values satisfy a given condition
CREATE INDEX idx_name ON table(col)Create an index to speed up queries on a column
CREATE UNIQUE INDEX idx ON table(col)Create a unique index (also enforces uniqueness)
DROP INDEX idx_nameRemove an index from the database

Subqueries & CTEs

SyntaxDescription
WHERE col IN (SELECT col FROM other)Filter using the result of another query
WHERE col = (SELECT MAX(col) FROM table)Scalar subquery — returns a single value for comparison
SELECT * FROM (SELECT ... ) AS subUse a subquery as a derived table in the FROM clause
WHERE EXISTS (SELECT 1 FROM other WHERE ...)Return rows only if the subquery finds at least one match
WHERE NOT EXISTS (SELECT 1 FROM other WHERE ...)Return rows only if the subquery finds no matches
WITH cte AS (SELECT ... ) SELECT * FROM cteCommon Table Expression — define a named temporary result set
WITH RECURSIVE cte AS (base UNION ALL recursive) SELECT * FROM cteRecursive CTE — useful for hierarchical or tree-structured data

String Functions

SyntaxDescription
CONCAT(str1, str2)Concatenate two or more strings together
SUBSTRING(str, start, length)Extract a portion of a string from a given position
UPPER(str)Convert a string to uppercase
LOWER(str)Convert a string to lowercase
TRIM(str)Remove leading and trailing whitespace
LENGTH(str)Return the number of characters in a string
REPLACE(str, 'old', 'new')Replace all occurrences of a substring within a string
COALESCE(col, 'default')Return the first non-NULL value from a list of arguments
CAST(col AS VARCHAR)Convert a value from one data type to another

Date Functions

SyntaxDescription
CURRENT_TIMESTAMPReturn the current date and time
CURRENT_DATEReturn the current date (no time component)
CURRENT_TIMEReturn the current time (no date component)
EXTRACT(YEAR FROM date_col)Extract a part (year, month, day, hour, etc.) from a date
date_col + INTERVAL '7' DAYAdd a duration to a date or timestamp
date_col - INTERVAL '1' MONTHSubtract a duration from a date or timestamp
CAST(col AS DATE)Convert a string or timestamp to a date type