SQL Cheatsheet
Explore the top 20 most popular SQL queries that every SQL developer should know. These queries cover a wide range of tasks from basic data retrieval to more complex operations. Let's dive in!
SELECT
The
SELECT
statement retrieves data from a database.
SELECT * FROM table_name;
SELECT DISTINCT
This query retrieves unique values from a specified column.
SELECT DISTINCT column_name FROM table_name;
WHERE
The
WHERE
clause filters the results based on a specified condition.
SELECT * FROM table_name WHERE condition;
AND / OR
These operators are used to combine multiple conditions in a
WHERE
clause.
SELECT * FROM table_name WHERE condition1 AND/OR condition2;
ORDER BY
ORDER BY
sorts the results in ascending (default) or descending order.
SELECT * FROM table_name ORDER BY column_name;
LIMIT
LIMIT
restricts the number of rows returned by a query.
SELECT * FROM table_name LIMIT n;
INSERT INTO
This statement adds new records into a table.
INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);
UPDATE
UPDATE
modifies existing records in a table.
UPDATE table_name SET column1 = value1, column2 = value2 WHERE condition;
DELETE
The
DELETE
statement removes records from a table.
DELETE FROM table_name WHERE condition;
IN
IN
allows you to specify multiple values in a
WHERE
clause.
SELECT * FROM table_name WHERE column_name IN (value1, value2, ...);
BETWEEN
BETWEEN
filters results within a specified range.
SELECT * FROM table_name WHERE column_name BETWEEN value1 AND value2;
LIKE
LIKE
is used for pattern matching.
SELECT * FROM table_name WHERE column_name LIKE pattern;
JOIN
JOIN
combines records from two or more tables based on a related column.
SELECT * FROM table1 JOIN table2 ON table1.column = table2.column;
LEFT JOIN / RIGHT JOIN
LEFT JOIN
retrieves all records from the left table and matching records from the right table.
SELECT * FROM table1 LEFT JOIN table2 ON table1.column = table2.column;
RIGHT JOIN
retrieves all records from the right table and matching records from the left table.
SELECT * FROM table1 RIGHT JOIN table2 ON table1.column = table2.column;
INNER JOIN
INNER JOIN
retrieves records with matching values in both tables.
SELECT * FROM table1 INNER JOIN table2 ON table1.column = table2.column;
GROUP BY
GROUP BY
groups rows with the same values into summary rows.
SELECT column_name, COUNT(*) FROM table_name GROUP BY column_name;
HAVING
HAVING
filters results of a
GROUP BY
query based on a condition.
SELECT column_name, COUNT(*) FROM table_name GROUP BY column_name HAVING condition;
COUNT
COUNT
counts the number of records in a table.
SELECT COUNT(column_name) FROM table_name;
AVG
AVG
calculates the average value of a column.
SELECT AVG(column_name) FROM table_name;
MAX / MIN
MAX
and
MIN
retrieve the maximum and minimum values from a column, respectively.
SELECT MAX(column_name) FROM table_name;
SELECT MIN(column_name) FROM table_name;