Explain the solution you have written. For a given problem, come up with a SQL query. Can you explain how this SQL works?
💡 Model Answer
When you write a SQL query you are essentially telling the database how to transform data from tables into a result set. A typical query has the following clauses:
- SELECT – lists the columns or expressions you want in the output.
- FROM – specifies the source tables and any joins between them.
- WHERE – filters rows before any grouping or aggregation.
- GROUP BY – aggregates rows that share the same values for the listed columns.
- HAVING – filters groups after aggregation.
- ORDER BY – sorts the final result.
- LIMIT/OFFSET – restricts the number of rows returned.
For example, to find the top 5 products by sales you might write:
SELECT p.product_id,
p.name,
SUM(o.quantity * o.unit_price) AS total_salesFROM orders o
JOIN products p ON o.product_id = p.product_id
GROUP BY p.product_id, p.name
ORDER BY total_sales DESC
LIMIT 5;
Here, the JOIN brings together order and product data. The GROUP BY aggregates sales per product. SUM calculates the total revenue. ORDER BY sorts the products from highest to lowest revenue, and LIMIT 5 keeps only the top five. Understanding each clause and how they interact lets you build complex queries that answer business questions efficiently.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500