0% found this document useful (0 votes)
7 views1 page

SQL Query Decoding CheatSheet

This document is a cheat sheet for SQL query decoding, outlining the structure of SQL queries and providing keyword mappings. It emphasizes the difference between WHERE and HAVING clauses, along with self-check questions to consider before writing queries. Additionally, it includes example patterns for common SQL queries involving filtering and aggregation.

Uploaded by

whynot.mehal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views1 page

SQL Query Decoding CheatSheet

This document is a cheat sheet for SQL query decoding, outlining the structure of SQL queries and providing keyword mappings. It emphasizes the difference between WHERE and HAVING clauses, along with self-check questions to consider before writing queries. Additionally, it includes example patterns for common SQL queries involving filtering and aggregation.

Uploaded by

whynot.mehal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SQL Query Decoding Cheat Sheet

1. SQL Skeleton (Always Follow Order)


SELECT …
FROM …
WHERE … -- row filter
GROUP BY … -- make groups
HAVING … -- group filter
ORDER BY …;

2. Keyword → SQL Mapping


- List / Display / Show → SELECT
- Number of … → COUNT()
- Total … → SUM()
- Average … → AVG()
- Highest / Lowest … → MAX() / MIN()
- Greater than / less than … → WHERE (row) / HAVING (group)
- Each / Group wise / Per … → GROUP BY
- Only those groups … → HAVING
- Arrange / Sort → ORDER BY

3. WHERE vs HAVING (Golden Rule)


WHERE = row filter (before grouping)
HAVING = group filter (after grouping)

Mantra: WHERE = rows, HAVING = groups

4. Self-Check Before Writing


1. Am I filtering rows or groups?
2. Do I need an aggregate function (SUM, AVG, COUNT…)?
3. Which columns must appear in SELECT? (Only grouped + aggregates allowed!)

5. Example Patterns
Q1. Departments with more than 2 employees
SELECT department, COUNT(*)
FROM employees
GROUP BY department
HAVING COUNT(*) > 2;

Q2. Names & salaries of employees earning >50000


SELECT name, salary
FROM employees
WHERE salary > 50000;

Q3. Department and total salary paid


SELECT department, SUM(salary)
FROM employees
GROUP BY department;

You might also like