Excellent ๐
Now Querying Data commands in the same exam-perfect pattern:
One base table
Question
SQL
Exact OUTPUT
✔ short explanation
๐ Base Table (Used for ALL Queries)
products
| product_id | product_name | category | price | age |
|---|---|---|---|---|
| 1 | Laptop | Electronics | 60000 | 2 |
| 2 | Phone | Electronics | 30000 | 1 |
| 3 | Shirt | Clothing | 1500 | 3 |
| 4 | Jeans | Clothing | 2500 | 4 |
| 5 | TV | Electronics | 45000 | 5 |
| 6 | Watch | Accessories | 5000 | 6 |
๐งพ Summary Table (Querying Commands)
| No. | Command | Question |
|---|---|---|
| 1 | SELECT | Retrieve specific columns |
| 2 | WHERE | Filter rows |
| 3 | ORDER BY | Sort result |
| 4 | GROUP BY | Group rows |
| 5 | HAVING | Filter groups |
1️⃣ SELECT Statement
Question: Show product name and price of all products.
SELECT product_name, price
FROM products;
✅ Output
| product_name | price |
|---|---|
| Laptop | 60000 |
| Phone | 30000 |
| Shirt | 1500 |
| Jeans | 2500 |
| TV | 45000 |
| Watch | 5000 |
✔ Retrieves selected columns
✔ Does not filter or sort data
2️⃣ WHERE Clause
Question: Show products with price greater than 30,000.
SELECT *
FROM products
WHERE price > 30000;
✅ Output
| product_id | product_name | category | price | age |
|---|---|---|---|---|
| 1 | Laptop | Electronics | 60000 | 2 |
| 5 | TV | Electronics | 45000 | 5 |
✔ Filters rows based on condition
✔ Works before grouping
3️⃣ ORDER BY Clause
Question: Show all products sorted by price (highest first).
SELECT *
FROM products
ORDER BY price DESC;
✅ Output
| product_name | price |
|---|---|
| Laptop | 60000 |
| TV | 45000 |
| Phone | 30000 |
| Watch | 5000 |
| Jeans | 2500 |
| Shirt | 1500 |
✔ Sorts result set
✔ Does not change table data
4️⃣ GROUP BY Clause
Question: Show total number of products in each category.
SELECT category, COUNT(*) AS total_products
FROM products
GROUP BY category;
✅ Output
| category | total_products |
|---|---|
| Electronics | 3 |
| Clothing | 2 |
| Accessories | 1 |
✔ Groups rows by category
✔ Uses aggregate function
5️⃣ HAVING Clause
Question: Show categories having more than 2 products.
SELECT category, COUNT(*) AS total_products
FROM products
GROUP BY category
HAVING COUNT(*) > 2;
✅ Output
| category | total_products |
|---|---|
| Electronics | 3 |
✔ Filters grouped results
✔ Used after GROUP BY
๐ฅ WHERE vs HAVING (Quick Revision)
| WHERE | HAVING |
|---|---|
| Filters rows | Filters groups |
| Used before GROUP BY | Used after GROUP BY |
| No aggregate functions | Aggregate functions allowed |
๐ง One-Line Memory Trick
| Clause | Remember |
|---|---|
| SELECT | What to show |
| WHERE | Which rows |
| ORDER BY | In what order |
| GROUP BY | Make groups |
| HAVING | Filter groups |
If you want next:
Combined queries (WHERE + GROUP BY + HAVING)
MCQs with output prediction
Interview traps
Hindi explanations for exams
Just say ๐
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.