(Beginner โก๏ธ Advanced)
1๏ธโฃ Select Specific Columns
SELECT name, email FROM users;
This fetches only the
name and email columns from the users table. โ๏ธ Used when you donโt want all columns from a table.
2๏ธโฃ Filter Records with WHERE
SELECT * FROM users WHERE age > 30;
The
WHERE clause filters rows where age is greater than 30. โ๏ธ Used for applying conditions on data.
3๏ธโฃ ORDER BY Clause
SELECT * FROM users ORDER BY registered_at DESC;
Sorts all users based on
registered_at in descending order. โ๏ธ Helpful to get latest data first.
4๏ธโฃ Aggregate Functions (COUNT, AVG)
SELECT COUNT(*) AS total_users, AVG(age) AS avg_age FROM users;
Explanation:
-
COUNT(*) counts total rows (users). -
AVG(age) calculates the average age. โ๏ธ Used for quick stats from tables.
5๏ธโฃ GROUP BY Usage
SELECT city, COUNT(*) AS user_count FROM users GROUP BY city;
Groups data by
city and counts users in each group. โ๏ธ Use when you want grouped summaries.
6๏ธโฃ JOIN Tables
SELECT users.name, orders.amount
FROM users
JOIN orders ON users.id = orders.user_id;
Fetches user names along with order amounts by joining
users and orders on matching IDs. โ๏ธ Essential when combining data from multiple tables.
7๏ธโฃ Use of HAVING
SELECT city, COUNT(*) AS total
FROM users
GROUP BY city
HAVING COUNT(*) > 5;
Like
WHERE, but used with aggregates. This filters cities with more than 5 users. โ๏ธ **Use
HAVING after GROUP BY.**8๏ธโฃ Subqueries
SELECT * FROM users
WHERE salary > (SELECT AVG(salary) FROM users);
Finds users whose salary is above the average. The subquery calculates the average salary first.
โ๏ธ Nested queries for dynamic filtering9๏ธโฃ CASE Statementnt**
SELECT name,
CASE
WHEN age < 18 THEN 'Teen'
WHEN age <= 40 THEN 'Adult'
ELSE 'Senior'
END AS age_group
FROM users;
Adds a new column that classifies users into categories based on age.
โ๏ธ Powerful for conditional logic.
๐ Window Functions (Advanced)
SELECT name, city, score,
RANK() OVER (PARTITION BY city ORDER BY score DESC) AS rank
FROM users;
Ranks users by score *within each city*.
SQL Learning Series: https://whatsapp.com/channel/0029VanC5rODzgT6TiTGoa1v/1075