Q.Keshav has written the following query to find out the sum of bonus earned by the employees of WEST zone: SELECT zone, TOTAL (bonus) FROM employee HAVING zone = 'WEST'; But he got an error. Identify the errors and rewrite the query by underlining the corrections(s) done.
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →Keshav's query failed due to three main errors: using TOTAL instead of the correct aggregate function SUM, misplacing the row-level filter zone = 'WEST' in the HAVING clause instead of WHERE, and omitting the mandatory GROUP BY clause when selecting both an aggregate and a non-aggregate column.
Imagine you're trying to gather specific information from a vast ledger, like an employee database. You wouldn't just shout out vague instructions; you'd use precise language to get exactly what you need. SQL, or Structured Query Language, is that precise language for databases. It allows us to ask questions and retrieve data in a structured way. Keshav's query, while aiming to find the total bonus for employees in the 'WEST' zone, contains a few common misunderstandings about how SQL processes information, particularly when it comes to summarizing data.
When we want to perform calculations across multiple rows, like finding a sum, an average, or a count, we use what are called 'aggregate functions'. These functions take a set of values and return a single summary value.
Here's a breakdown of the issues in Keshav's query:
-
Error 1: The
TOTALfunctionSQL has a standard set of aggregate functions, and
TOTALis not one of them. To calculate the sum of values in a column, the correct function to use isSUM(). For instance,SUM(bonus)would correctly add up all the bonus amounts. Other common aggregate functions includeAVG()for average,COUNT()for counting rows,MIN()for the minimum value, andMAX()for the maximum value. -
Error 2: Misuse of the
HAVINGclauseThe
HAVINGclause is specifically designed to filter groups of rows after they have been aggregated using aGROUP BYclause. Think of it as aWHEREclause for groups. If you want to filter individual rows before any aggregation happens, or based on a condition that applies to each row, you must use theWHEREclause. Keshav wants to select employees whose zone is 'WEST' before summing their bonuses. This is a row-level condition, not a group-level condition, and thus belongs in theWHEREclause. -
Error 3: Missing
GROUP BYclause …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.