1️⃣ Write a query to find the second highest salary in the employee table.
SELECT MAX(salary)
FROM employee
WHERE salary < (SELECT MAX(salary) FROM employee);
2️⃣ Get the top 3 products by revenue from sales table.
SELECT product_id, SUM(revenue) AS total_revenue
FROM sales
GROUP BY product_id
ORDER BY total_revenue DESC
LIMIT 3;
3️⃣ Use JOIN to combine customer and order data.
SELECT c.customer_name, o.order_id, o.order_date
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id;
(That's an INNER JOIN—use LEFT JOIN to include all customers, even without orders.)
4️⃣ Difference between WHERE and HAVING?
⦁ WHERE filters rows before aggregation (e.g., on individual records).
⦁ HAVING filters rows after aggregation (used with GROUP BY on aggregates).
Example:
SELECT department, COUNT(*)
FROM employee
GROUP BY department
HAVING COUNT(*) > 5;
5️⃣ Explain INDEX and how it improves performance.
An INDEX is a data structure that improves the speed of data retrieval.
It works like a lookup table and reduces the need to scan every row in a table.
Especially useful for large datasets and on columns used in WHERE, JOIN, or ORDER BY—think 10x faster queries, but it slows inserts/updates a bit.
💬 Tap ❤️ for more!