Querying Data Commands

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_idproduct_namecategorypriceage
1LaptopElectronics600002
2PhoneElectronics300001
3ShirtClothing15003
4JeansClothing25004
5TVElectronics450005
6WatchAccessories50006

๐Ÿงพ Summary Table (Querying Commands)

No.CommandQuestion
1SELECTRetrieve specific columns
2WHEREFilter rows
3ORDER BYSort result
4GROUP BYGroup rows
5HAVINGFilter groups

1️⃣ SELECT Statement

Question: Show product name and price of all products.

SELECT product_name, price
FROM products;

✅ Output

product_nameprice
Laptop60000
Phone30000
Shirt1500
Jeans2500
TV45000
Watch5000

✔ 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_idproduct_namecategorypriceage
1LaptopElectronics600002
5TVElectronics450005

✔ 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_nameprice
Laptop60000
TV45000
Phone30000
Watch5000
Jeans2500
Shirt1500

✔ 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

categorytotal_products
Electronics3
Clothing2
Accessories1

✔ 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

categorytotal_products
Electronics3

✔ Filters grouped results
✔ Used after GROUP BY


๐Ÿ”ฅ WHERE vs HAVING (Quick Revision)

WHEREHAVING
Filters rowsFilters groups
Used before GROUP BYUsed after GROUP BY
No aggregate functionsAggregate functions allowed

๐Ÿง  One-Line Memory Trick

ClauseRemember
SELECTWhat to show
WHEREWhich rows
ORDER BYIn what order
GROUP BYMake groups
HAVINGFilter 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.