Consider the following Table "SALE".
InvoiceNo CarId CustID SaleDate I00001 C123 C0001 2019-05-24 I00002 C128 C0002 2020-02-21 I00003 C139 C0001 2020-03-23 I00004 C145 C0003 2020-04-17 I00005 C147 C0002 2021-04-11 I00006 C145 C0004 2022-05-08
What will be the output of the following SQL Query?
SELECT CustID, COUNT(*) FROM SALE GROUP BY CustID HAVING Count(*)>1;
Consider the following Table "SALE".
| InvoiceNo | CarId | CustID | SaleDate |
|---|---|---|---|
| I00001 | C123 | C0001 | 2019-05-24 |
| I00002 | C128 | C0002 | 2020-02-21 |
| I00003 | C139 | C0001 | 2020-03-23 |
| I00004 | C145 | C0003 | 2020-04-17 |
| I00005 | C147 | C0002 | 2021-04-11 |
| I00006 | C145 | C0004 | 2022-05-08 |
What will be the output of the following SQL Query?
SELECT CustID, COUNT(*) FROM SALE GROUP BY CustID HAVING Count(*)>1;
Solution
✅ Correct Option: 1
GROUP BY CustID puts the rows into one group per customer, and HAVING COUNT(*) > 1 keeps only the groups with more than one row.
| CustID | Rows (COUNT(*)) | Kept by HAVING COUNT(*) > 1 |
|---|---|---|
| C0001 | 2 (I00001, I00003) | Yes |
| C0002 | 2 (I00002, I00005) | Yes |
| C0003 | 1 | No |
| C0004 | 1 | No |
The output has both selected columns, CustID and COUNT(*), for C0001 and C0002.
Option 2: leaves out C0002, which also has 2 sales.
Options 3 and 4: the query selects both CustID and COUNT(*), so both columns must appear in the output.
Related questions:
2025: 20 May Shift 1
2025: 20 May Shift 1
2026: 29 May Shift 1
2026: 23 May Shift 2