DatabaseCheat Sheet

SQL Query Examples: A Complete Cheat Sheet for Developers

TT
TopicTrick
SQL Query Examples: A Complete Cheat Sheet for Developers

SQL Query Examples - Complete Cheat Sheet for Developers

SQL (Structured Query Language) is the universal language of databases. Whether you are building web apps, performing data analysis, or working on backend microservices, SQL is an absolutely essential skill.

This cheat sheet provides the most common and useful SQL query examples that you will use in real-world projects.


The Core SQL Operations (CRUD)

SQL databases store data in tables (similar to spreadsheets with rows and columns). The core operations you perform on these tables are known as CRUD:

  1. Create (INSERT)
  2. Read (SELECT)
  3. Update (UPDATE)
  4. Delete (DELETE)

1. SELECT: Retrieving Data

The SELECT statement is the most frequent command you will use. It is how you ask the database a question.

sql
1-- Grab absolutely everything (Bad practice for production) 2SELECT * FROM users; 3 4-- Select specific columns (Best practice) 5SELECT id, first_name, email FROM users; 6 7-- Rename columns in the output using AS (Alias) 8SELECT 9 id, 10 first_name AS name, 11 email AS contact_info 12FROM users; 13 14-- Select with a calculated column 15SELECT 16 product_name, 17 price, 18 (price * 0.9) AS discounted_price 19FROM products; 20 21-- Return only unique values (Remove duplicates) 22SELECT DISTINCT country FROM users; 23 24-- Limit results for pagination (Show rows 21-30) 25SELECT * FROM products 26ORDER BY created_at DESC 27LIMIT 10 OFFSET 20;

2. WHERE: Filtering Data

Without a WHERE clause, you are querying every single row in the table, which is extremely slow. WHERE lets you filter the data based on conditions.

sql
1-- Basic Math Comparisons 2SELECT * FROM users WHERE age >= 18; 3SELECT * FROM orders WHERE total_amount <= 100; 4 5-- Multiple Conditions (AND / OR) 6SELECT * FROM users 7WHERE status = 'active' AND created_at > '2026-01-01'; 8 9SELECT * FROM products 10WHERE category = 'electronics' OR price < 20; 11 12-- NULL Checks (You cannot use "= NULL") 13SELECT * FROM users WHERE phone_number IS NULL; 14SELECT * FROM users WHERE email IS NOT NULL; 15 16-- Pattern Matching with LIKE (% is a wildcard) 17SELECT * FROM users WHERE first_name LIKE 'John%'; -- Starts with "John" 18SELECT * FROM users WHERE email LIKE '%@gmail.com'; -- Ends with "@gmail.com" 19 20-- IN clause (Matches any value in the list) 21SELECT * FROM users WHERE country IN ('US', 'UK', 'CA');

3. JOIN: Combining Tables

In a well-designed relational database, data is split across multiple tables. JOINs act as the glue to bring that data back together.

sql
1-- INNER JOIN (Only returns rows that have matches in BOTH tables) 2SELECT 3 users.first_name, 4 orders.total_amount 5FROM orders 6INNER JOIN users ON orders.user_id = users.id; 7 8-- LEFT JOIN (Returns ALL users, even if they haven't made an order) 9SELECT 10 users.first_name, 11 orders.id AS order_id 12FROM users 13LEFT JOIN orders ON users.id = orders.user_id; 14 15-- Joining 3 Tables Together 16SELECT 17 u.first_name, 18 o.id AS order_id, 19 p.product_name 20FROM orders o 21JOIN users u ON o.user_id = u.id 22JOIN order_items oi ON oi.order_id = o.id 23JOIN products p ON oi.product_id = p.id;

4. GROUP BY & Aggregates

Sometimes you don't need individual rows; you need a summary. Aggregate functions (COUNT, SUM, AVG) calculate totals, and GROUP BY organizes them into categories.

sql
1-- Basic Aggregates 2SELECT 3 COUNT(*) AS total_users, 4 AVG(age) AS average_age, 5 MAX(age) AS oldest_user 6FROM users; 7 8-- Grouping data by a category 9SELECT 10 country, 11 COUNT(*) AS user_count 12FROM users 13GROUP BY country 14ORDER BY user_count DESC; 15 16-- HAVING clause (Filters POST-aggregation. WHERE filters PRE-aggregation) 17SELECT 18 user_id, 19 SUM(total_amount) AS total_spent 20FROM orders 21GROUP BY user_id 22HAVING SUM(total_amount) > 500;

5. Modifying Data (INSERT, UPDATE, DELETE)

These commands physically alter the data stored in the database.

Danger Zone!

Always use a WHERE clause with UPDATE and DELETE. If you run 'DELETE FROM users;' without a WHERE clause, you will delete every user in your database.

    sql
    1-- INSERT a single row 2INSERT INTO users (first_name, email, country) 3VALUES ('John', 'john@example.com', 'US'); 4 5-- INSERT multiple rows at once 6INSERT INTO products (name, price) VALUES 7 ('Laptop', 999.99), 8 ('Mouse', 24.99), 9 ('Keyboard', 49.99); 10 11-- UPDATE existing records 12UPDATE users 13SET status = 'active', 14 updated_at = NOW() 15WHERE email = 'john@example.com'; 16 17-- DELETE records based on a condition 18DELETE FROM sessions 19WHERE expires_at < NOW();

    Conclusion

    Mastering SQL is a superpower. While Object-Relational Mappers (ORMs) like Prisma or TypeORM are great, understanding the underlying SQL queries they generate is what separates junior developers from senior engineers.

    Bookmark this cheat sheet and refer to it the next time you need to write a complex database query!