3 min readBy Alember Shreesh
sqldatabaseprogrammingcheatsheet

Everyday SQL Cheatsheet: 17 Queries You Actually Use

A concise guide to the SQL queries you’ll reach for daily.

Everyday SQL Cheatsheet: 17 Queries You Actually Use

15 queries you’ll use most of the time

You don’t need every SQL keyword in your head. Most of the time, you’ll only use a core set of queries to get work done. This cheatsheet covers the ones you’ll reach for daily.

1. Select All Columns

SELECT *
FROM users;

Quickly look at all data in a table.

2. Select Specific Columns

SELECT id, name
FROM users;

Retrieve only the fields you actually need.

3. Filter Rows With WHERE

SELECT *
FROM users
WHERE active = 1;

Return rows matching specific conditions.

4. Get Unique Values With DISTINCT

SELECT DISTINCT country
FROM users;

Eliminate duplicate results.

5. Sort Results With ORDER BY

SELECT name, score
FROM leaderboard
ORDER BY score DESC;

Arrange rows in ascending (ASC) or descending (DESC) order.

6. Limit Rows

SELECT *
FROM logs
ORDER BY created_at DESC
LIMIT 10;

Return only the first n rows. Useful for previews.

7. Skip Rows With OFFSET

SELECT *
FROM users
ORDER BY id
LIMIT 10 OFFSET 20;

Implement pagination or skip a set of rows.

8. Count Rows

SELECT COUNT(*) AS total_users
FROM users;

Get the total number of rows.

9. Aggregate With GROUP BY

SELECT department, COUNT(*) AS employees
FROM staff
GROUP BY department;

Summarize rows by categories.

10. Filter Groups With HAVING

SELECT department, COUNT(*) AS employees
FROM staff
GROUP BY department
HAVING COUNT(*) > 5;

Apply conditions to aggregated results.

11. Range Filtering With BETWEEN

SELECT *
FROM orders
WHERE created_at BETWEEN '2024-01-01' AND '2024-01-31';

Filter values within a range.

12. Multiple Matches With IN

SELECT *
FROM users
WHERE country IN ('US', 'UK', 'CA');

Match against multiple values in a cleaner way than chaining OR.

13. Join Tables

SELECT u.name, o.total
FROM users u
JOIN orders o ON u.id = o.user_id;

Combine related data across tables.

14. Handle Missing Data With COALESCE

SELECT name, COALESCE(phone, 'N/A') AS phone
FROM users;

Replace NULL values with defaults.

15. Conditional Output With CASE

SELECT name,
       CASE
           WHEN score >= 90 THEN 'Pro'
           WHEN score >= 60 THEN 'Average'
           ELSE 'Beginner'
       END AS level
FROM players;

Add conditional logic directly into your queries.

16. Update Rows

UPDATE users
SET active = 0
WHERE last_login < '2024-01-01';

Modify existing data. Always use a WHERE clause to avoid updating everything.

17. Delete Rows

DELETE FROM logs
WHERE created_at < NOW() - INTERVAL 30 DAY;

Remove old or unneeded rows. Use carefully.

Final Note

These 17 queries cover 90% of what you’ll do in SQL. Learn them well, and you’ll be able to explore, analyze, and modify most databases confidently.

Related Posts