Chapter 17 Intermediate 62 Questions

Practice Questions — Conditional Logic - CASE WHEN, IF, IFNULL

← Back to Notes
10 Easy
16 Medium
10 Hard

Topic-Specific Questions

Question 1
Easy
What does this return?
SELECT CASE WHEN 5 > 3 THEN 'yes' ELSE 'no' END;
5 > 3 is TRUE.
yes
Question 2
Easy
What is returned?
SELECT CASE WHEN 1 = 2 THEN 'a' END;
No match, no ELSE.
NULL
Question 3
Easy
Output?
SELECT IFNULL(NULL, 'default');
IFNULL replaces NULL with the second argument.
default
Question 4
Easy
Output?
SELECT IFNULL('hello', 'default');
IFNULL returns the first argument when it is not NULL.
hello
Question 5
Easy
Output?
SELECT COALESCE(NULL, NULL, 'third', 'fourth');
COALESCE returns the first non-NULL argument.
third
Question 6
Easy
Output?
SELECT NULLIF(5, 5), NULLIF(5, 3);
NULLIF(a, b) returns NULL when a = b.
NULL 5
Question 7
Easy
Output?
SELECT IF(10 > 5, 'big', 'small');
Classic IF with true condition.
big
Question 8
Medium
Given marks = 62, what does this return?
SELECT CASE
  WHEN marks >= 90 THEN 'A'
  WHEN marks >= 75 THEN 'B'
  WHEN marks >= 60 THEN 'C'
  ELSE 'D'
END;
First match wins.
C
Question 9
Medium
Output of this simple CASE?
SELECT CASE 'paid'
  WHEN 'paid'    THEN 1
  WHEN 'pending' THEN 2
  ELSE 3
END;
Simple CASE with equality matching.
1
Question 10
Medium
What does this return when status IS NULL?
CASE status
  WHEN NULL THEN 'unknown'
  ELSE 'known'
END
Simple CASE uses = comparison.
known
Question 11
Medium
Given these orders table rows: (101,'paid',1000), (101,'paid',500), (101,'pending',200), what does SUM(CASE WHEN status='paid' THEN amount ELSE 0 END) return?
Add only the 'paid' rows.
1500
Question 12
Medium
Given the same rows, what does COUNT(CASE WHEN status='paid' THEN 1 END) return?
COUNT ignores NULL.
2
Question 13
Medium
Output?
SELECT COALESCE(NULLIF('', ''), 'missing');
'' = '' is true.
missing
Question 14
Medium
Output?
SELECT 10 / NULLIF(0, 0);
NULLIF(0, 0) returns NULL.
NULL
Question 15
Hard
Output?
SELECT CASE
  WHEN 1 THEN 'a'
  WHEN 1 THEN 'b'
  ELSE 'c'
END;
Two WHENs both match. Which wins?
a
Question 16
Hard
Given amount = NULL, what does this return?
CASE
  WHEN amount > 1000 THEN 'big'
  WHEN amount <= 1000 THEN 'small'
  ELSE 'unknown'
END
Any comparison with NULL is NULL (not TRUE).
unknown
Question 17
Medium
What is the difference between IFNULL and COALESCE?
Argument count and portability.
IFNULL takes exactly 2 arguments and is MySQL-specific. COALESCE takes 2 or more arguments, returns the first non-NULL, and is part of the SQL standard (works on every database). For portable code use COALESCE. IFNULL is slightly faster in MySQL but the difference is negligible.
Question 18
Hard
Why does the conditional aggregation pattern SUM(CASE WHEN cond THEN val ELSE 0 END) work?
Think about what SUM adds and what 0 contributes.
SUM adds all non-NULL values. By writing ELSE 0, every non-matching row contributes 0 to the total — which is a no-op. Every matching row contributes its val. The end result is the sum of val only for rows where the condition is true. This lets you compute multiple filtered sums in a single pass of the table, which is the basis of SQL pivoting.
Question 19
Easy
Given employees(name, salary), write a query returning name, salary, and a 'band' column: 'Low' if < 40000, 'Mid' if < 80000, else 'High'.
Searched CASE with two WHENs and ELSE.
SELECT name, salary,
  CASE
    WHEN salary < 40000 THEN 'Low'
    WHEN salary < 80000 THEN 'Mid'
    ELSE 'High'
  END AS band
FROM employees;
Question 20
Medium
Given orders(customer_id, status, amount), write a pivot returning per customer: total paid, total pending, and total failed.
Conditional aggregation with SUM + CASE.
SELECT customer_id,
  SUM(CASE WHEN status = 'paid'    THEN amount ELSE 0 END) AS paid_total,
  SUM(CASE WHEN status = 'pending' THEN amount ELSE 0 END) AS pending_total,
  SUM(CASE WHEN status = 'failed'  THEN amount ELSE 0 END) AS failed_total
FROM orders
GROUP BY customer_id;
Question 21
Medium
Write a query that sorts orders by priority: 'urgent' first, then 'normal', then 'low'.
CASE in ORDER BY.
SELECT *
FROM orders
ORDER BY
  CASE priority
    WHEN 'urgent' THEN 1
    WHEN 'normal' THEN 2
    WHEN 'low'    THEN 3
    ELSE 4
  END;
Question 22
Medium
Given orders(id, amount, discount_pct), write a query returning the final price, treating NULL discount_pct as 0.
IFNULL + arithmetic.
SELECT id, amount, discount_pct,
  amount * (1 - IFNULL(discount_pct, 0) / 100.0) AS final_price
FROM orders;
Question 23
Hard
Given orders(customer_id, amount), compute the margin per customer where margin = SUM(profit)/SUM(revenue), treating customers with zero revenue as NULL margin instead of an error. Assume columns profit and revenue.
NULLIF for safe division.
SELECT customer_id,
  SUM(profit)  AS total_profit,
  SUM(revenue) AS total_revenue,
  ROUND(SUM(profit) / NULLIF(SUM(revenue), 0), 4) AS margin
FROM orders
GROUP BY customer_id;
Question 24
Hard
Given users(id, age), bucket users into age groups: 'Teen' (13-17), 'Adult' (18-59), 'Senior' (60+), 'Other' (everyone else). Return counts per bucket.
CASE in both SELECT and GROUP BY.
SELECT
  CASE
    WHEN age BETWEEN 13 AND 17 THEN 'Teen'
    WHEN age BETWEEN 18 AND 59 THEN 'Adult'
    WHEN age >= 60             THEN 'Senior'
    ELSE                           'Other'
  END AS age_group,
  COUNT(*) AS total
FROM users
GROUP BY age_group;
Question 25
Hard
Why should you almost never write WHERE CASE WHEN x THEN 1 ELSE 0 END = 1?
Readability and indexes.
It is equivalent to WHERE x, just more verbose. It also prevents the optimizer from using an index on the underlying column because the CASE wraps the expression. The only time CASE in WHERE is justified is when the column being filtered actually changes per row (e.g., CASE type WHEN 'daily' THEN days ELSE hours END > 10). Otherwise, rewrite using AND/OR directly.

Mixed & Application Questions

Question 1
Easy
Output?
SELECT IF(NULL, 'yes', 'no');
NULL is neither true nor false.
no
Question 2
Easy
Output?
SELECT CASE WHEN 0 THEN 'a' ELSE 'b' END;
0 is falsy in MySQL.
b
Question 3
Medium
Given a row with marks=NULL, output of:
CASE
  WHEN marks IS NULL THEN 'absent'
  WHEN marks >= 40   THEN 'pass'
  ELSE 'fail'
END
First WHEN wins.
absent
Question 4
Medium
Given orders: (1,'paid',500), (2,'paid',200), (3,'failed',300), what does
SELECT SUM(IF(status='paid', amount, 0)) FROM orders;
return?
IF is a 2-branch shortcut for CASE.
700
Question 5
Medium
Given products(name, price, category), mark each product as 'Premium' if price > 10000, 'Standard' between 2000 and 10000, 'Budget' below 2000.
Searched CASE with three WHENs.
SELECT name, price, category,
  CASE
    WHEN price > 10000 THEN 'Premium'
    WHEN price >= 2000 THEN 'Standard'
    ELSE 'Budget'
  END AS tier
FROM products;
Question 6
Medium
Given orders(customer_id, status, amount), return customers along with a flag 'HighValue' (sum paid > 10000) or 'LowValue'.
Conditional SUM inside a CASE in SELECT, after GROUP BY.
SELECT customer_id,
  SUM(CASE WHEN status='paid' THEN amount ELSE 0 END) AS paid_total,
  CASE
    WHEN SUM(CASE WHEN status='paid' THEN amount ELSE 0 END) > 10000
      THEN 'HighValue'
    ELSE 'LowValue'
  END AS tier
FROM orders
GROUP BY customer_id;
Question 7
Hard
For a row (name='Aarav', bonus=NULL, salary=50000), what does this return?
SELECT salary + IFNULL(bonus, 0) AS total
FROM employees;
NULL replaced by 0 before adding.
50000
Question 8
Hard
Given a row (dept='sales', salary=80000), what does this return?
SELECT
  CASE dept
    WHEN 'sales'      THEN salary * 1.1
    WHEN 'engineering' THEN salary * 1.2
    ELSE salary
  END AS adjusted
FROM employees;
Simple CASE matches 'sales'.
88000
Question 9
Hard
Given a feedback(rating) table where rating is 1-5, build a 'pivot' returning counts per rating value in a single row: rating_1, rating_2, rating_3, rating_4, rating_5.
Conditional COUNT for each value.
SELECT
  COUNT(CASE WHEN rating = 1 THEN 1 END) AS rating_1,
  COUNT(CASE WHEN rating = 2 THEN 1 END) AS rating_2,
  COUNT(CASE WHEN rating = 3 THEN 1 END) AS rating_3,
  COUNT(CASE WHEN rating = 4 THEN 1 END) AS rating_4,
  COUNT(CASE WHEN rating = 5 THEN 1 END) AS rating_5
FROM feedback;
Question 10
Medium
Output?
SELECT COALESCE(NULL, '', 'third');
COALESCE returns the first non-NULL. Is empty string NULL?
(empty string)
Question 11
Hard
Why does COUNT(CASE WHEN cond THEN 1 END) count matches, but SUM(CASE WHEN cond THEN 1 END) also works — what is the difference?
COUNT counts rows; SUM adds values. They happen to give the same answer for this pattern.
Both produce the same integer when each matching row contributes 1. COUNT ignores NULLs (non-matching rows with no ELSE become NULL and get skipped). SUM adds NULLs as nothing, same result. COUNT is stylistically preferred because its name is self-documenting ('I am counting matches'), and it works without ELSE. SUM would be required if you want to add a variable amount per match (e.g., SUM(CASE WHEN cond THEN amount ELSE 0 END)).

Multiple Choice Questions

MCQ 1
Which keyword marks the default branch in a CASE expression?
  • A. DEFAULT
  • B. OTHERWISE
  • C. ELSE
  • D. FALLBACK
Answer: C
C is correct. ELSE is used as the default branch in SQL's CASE. DEFAULT appears in column definitions, not CASE.
MCQ 2
What does a CASE expression return when no WHEN matches and there is no ELSE?
  • A. 0
  • B. An error
  • C. NULL
  • D. Empty string
Answer: C
C is correct. With no matching WHEN and no ELSE, CASE evaluates to NULL.
MCQ 3
Which function is MySQL-specific and not part of the SQL standard?
  • A. COALESCE
  • B. IFNULL
  • C. NULLIF
  • D. CASE WHEN
Answer: B
B is correct. IFNULL is MySQL (also SQLite)-specific. COALESCE, NULLIF, and CASE are SQL-standard.
MCQ 4
NULLIF(a, b) returns NULL when:
  • A. a is NULL
  • B. b is NULL
  • C. a = b
  • D. a > b
Answer: C
C is correct. NULLIF returns NULL when a equals b, otherwise it returns a.
MCQ 5
Which expression is equivalent to IF(x > 5, 'big', 'small')?
  • A. CASE WHEN x > 5 THEN 'big' ELSE 'small' END
  • B. x > 5 ? 'big' : 'small'
  • C. IF x > 5 THEN 'big' ELSE 'small'
  • D. SWITCH x > 5 CASE 'big' DEFAULT 'small'
Answer: A
A is correct. IF(cond, t, f) is equivalent to CASE WHEN cond THEN t ELSE f END. The ternary (?:) is not SQL.
MCQ 6
In a simple CASE CASE x WHEN NULL THEN ... END, when does the NULL branch match?
  • A. When x is NULL
  • B. When x is 0
  • C. Never
  • D. Always
Answer: C
C is correct. Simple CASE compares with =, and NULL = NULL evaluates to NULL, never TRUE. The branch is unreachable. Use searched CASE: WHEN x IS NULL.
MCQ 7
Which is the canonical SQL pivot pattern for per-category totals?
  • A. PIVOT(amount FOR category)
  • B. SUM(CASE WHEN category = 'X' THEN amount ELSE 0 END)
  • C. GROUP BY ROLLUP(category)
  • D. TRANSPOSE(category)
Answer: B
B is correct. MySQL has no PIVOT operator, so conditional aggregation with SUM + CASE is the standard pattern.
MCQ 8
If the condition salary >= 40 is placed before salary >= 75 in a CASE, what happens to the second branch?
  • A. It runs for all salaries 40-74
  • B. It runs when salary is exactly 75
  • C. It never runs (unreachable code)
  • D. SQL raises an error
Answer: C
C is correct. The first match wins. Any salary >= 75 also satisfies salary >= 40, so the first WHEN catches them and the second branch is dead code.
MCQ 9
What does COALESCE(NULL, '', 'X') return?
  • A. NULL
  • B. Empty string ''
  • C. 'X'
  • D. Error
Answer: B
B is correct. COALESCE returns the first non-NULL argument. Empty string '' is non-NULL. If you want empty strings treated as missing, use COALESCE(NULLIF(x, ''), 'default').
MCQ 10
Which pattern prevents divide-by-zero errors in strict SQL mode?
  • A. SUM(a) / SUM(b)
  • B. SUM(a) / IF(SUM(b)=0, NULL, SUM(b))
  • C. SUM(a) / NULLIF(SUM(b), 0)
  • D. Both B and C
Answer: D
D is correct. Both IF and NULLIF convert zero into NULL, making division safe. NULLIF is shorter and preferred.
MCQ 11
Where CAN you NOT use a CASE expression?
  • A. SELECT list
  • B. ORDER BY
  • C. Column definition DEFAULT clause (cannot use)
  • D. GROUP BY
Answer: C
C is correct. CASE works in SELECT, WHERE, GROUP BY, HAVING, and ORDER BY. It cannot be used in column DEFAULT clauses — defaults must be literal values.
MCQ 12
Why does COUNT(CASE WHEN status='paid' THEN 1 END) correctly count paid rows without ELSE?
  • A. COUNT ignores NULL values
  • B. COUNT treats all values as 1
  • C. Non-matching rows are automatically dropped
  • D. MySQL auto-adds ELSE 0
Answer: A
A is correct. Without ELSE, non-matching rows return NULL. COUNT skips NULLs, so only matching rows are counted.
MCQ 13
If you SUM(CASE WHEN cond THEN amount END) with NO ELSE, and a GROUP has zero matching rows, SUM returns:
  • A. 0
  • B. NULL
  • C. Empty
  • D. An error
Answer: B
B is correct. SUM of nothing (all NULLs) is NULL, not 0. This is a common dashboard bug. Fix: add ELSE 0 or wrap in IFNULL.
MCQ 14
Which CASE form allows checking 'IS NULL'?
  • A. Simple CASE only
  • B. Searched CASE only
  • C. Both
  • D. Neither
Answer: B
B is correct. Simple CASE uses = which never matches NULL. Only searched CASE can do WHEN x IS NULL.
MCQ 15
In MySQL, which of these is TRUE about using an alias defined in the SELECT list inside GROUP BY?
  • A. MySQL allows it; strict SQL standards do not
  • B. It is forbidden in MySQL
  • C. It only works in WHERE, not GROUP BY
  • D. It requires the alias to be quoted
Answer: A
A is correct. MySQL allows GROUP BY alias from the SELECT list. For portability (PostgreSQL, SQL Server), repeat the full expression in GROUP BY.
MCQ 16
Which of these is equivalent to IFNULL(x, 0)?
  • A. IF(x, 0, x)
  • B. COALESCE(x, 0)
  • C. NULLIF(x, 0)
  • D. CASE WHEN x = 0 THEN NULL ELSE x END
Answer: B
B is correct. COALESCE(x, 0) returns x if not NULL, else 0 — identical to IFNULL(x, 0). NULLIF does the opposite.
MCQ 17
A CASE that returns mixed types (string and number) in different branches will:
  • A. Raise a SyntaxError
  • B. Coerce all results to a compatible type (often string)
  • C. Return only the number branches
  • D. Crash at runtime
Answer: B
B is correct. MySQL picks a common type. Mixing INT and VARCHAR usually returns VARCHAR — the column's declared type is determined by type promotion rules, not by the last branch.
MCQ 18
What is the correct interpretation of CASE WHEN a=1 THEN x WHEN a=2 THEN y END when a=3?
  • A. Returns 0
  • B. Returns NULL
  • C. Raises an error
  • D. Returns x (the first THEN)
Answer: B
B is correct. No WHEN matches and there is no ELSE, so the expression is NULL.
MCQ 19
Which one is the BEST replacement for WHERE CASE WHEN status='paid' THEN 1 ELSE 0 END = 1?
  • A. WHERE status = 'paid'
  • B. WHERE status IS 'paid'
  • C. WHERE IF(status='paid', 1, 0)
  • D. WHERE status MATCHES 'paid'
Answer: A
A is correct. A direct boolean expression is cleaner, faster (sargable), and more readable.
MCQ 20
If you use a CASE expression in GROUP BY that references a computed alias, which rule MUST hold for SQL-standard portability?
  • A. The alias must be quoted
  • B. The full CASE expression must be repeated in GROUP BY
  • C. The alias must be lowercase
  • D. The alias must be prefixed with the table name
Answer: B
B is correct. SQL-92 standard does not allow SELECT aliases in GROUP BY. MySQL permits it, PostgreSQL partially, SQL Server does not. For portability, repeat the CASE.

Coding Challenges

Challenge 1: Grade Calculator

Easy
Given students(id, name, marks), return each student with their grade: A (>=90), B (>=75), C (>=60), D (>=40), else F. Sort by marks DESC.
Sample Input
6 students with marks 32..92.
Sample Output
One row per student with grade.
Use searched CASE with ELSE.
CREATE TABLE students (id INT PRIMARY KEY, name VARCHAR(50), marks INT);
INSERT INTO students VALUES
  (1,'Aarav Sharma',92),(2,'Priya Nair',78),(3,'Rohan Mehta',64),
  (4,'Ananya Iyer',45),(5,'Vikram Singh',32),(6,'Meera Krishnan',88);

SELECT name, marks,
  CASE
    WHEN marks >= 90 THEN 'A'
    WHEN marks >= 75 THEN 'B'
    WHEN marks >= 60 THEN 'C'
    WHEN marks >= 40 THEN 'D'
    ELSE 'F'
  END AS grade
FROM students
ORDER BY marks DESC;

Challenge 2: Pay Band with IF

Easy
Given employees(name, salary), use IF to tag each row as 'High' (>= 50000) or 'Low' (< 50000).
Sample Input
5 employees with varied salaries.
Sample Output
Each row has name, salary, and band.
Use IF for two branches.
CREATE TABLE employees (id INT PRIMARY KEY, name VARCHAR(50), salary DECIMAL(10,2));
INSERT INTO employees VALUES
  (1,'Aarav Sharma',72000),(2,'Priya Nair',45000),
  (3,'Rohan Mehta',51000),(4,'Ananya Iyer',38000),
  (5,'Vikram Singh',95000);

SELECT name, salary,
  IF(salary >= 50000, 'High', 'Low') AS band
FROM employees;

Challenge 3: Order Status Pivot

Medium
Given orders(id, customer_id, amount, status) where status is 'paid', 'pending', or 'failed', return per customer: paid_total, pending_total, failed_total (0 if none).
Sample Input
8 orders across 3 customers and 3 statuses.
Sample Output
One row per customer, three amount columns.
Use SUM(CASE ... ELSE 0 END) to avoid NULLs.
CREATE TABLE orders (id INT PRIMARY KEY, customer_id INT, amount DECIMAL(10,2), status VARCHAR(20));
INSERT INTO orders VALUES
  (1,101,1200,'paid'),(2,101, 800,'paid'),(3,101, 500,'pending'),
  (4,102,2500,'paid'),(5,102,1000,'failed'),
  (6,103, 700,'pending'),(7,103, 300,'pending'),(8,103,1500,'paid');

SELECT customer_id,
  SUM(CASE WHEN status='paid'    THEN amount ELSE 0 END) AS paid_total,
  SUM(CASE WHEN status='pending' THEN amount ELSE 0 END) AS pending_total,
  SUM(CASE WHEN status='failed'  THEN amount ELSE 0 END) AS failed_total
FROM orders
GROUP BY customer_id
ORDER BY customer_id;

Challenge 4: Custom Priority Sort

Medium
Given tickets(id, subject, priority) where priority is 'urgent', 'high', 'normal', 'low', sort in exactly that business order (not alphabetical).
Sample Input
6 tickets with mixed priorities.
Sample Output
Rows in the order: urgent, high, normal, low.
Use CASE in ORDER BY.
CREATE TABLE tickets (id INT PRIMARY KEY, subject VARCHAR(60), priority VARCHAR(10));
INSERT INTO tickets VALUES
  (1,'Server down','urgent'),
  (2,'Typo on page','low'),
  (3,'Deploy pipeline','high'),
  (4,'Slow login','normal'),
  (5,'Billing bug','urgent'),
  (6,'Missing tooltip','low');

SELECT *
FROM tickets
ORDER BY
  CASE priority
    WHEN 'urgent' THEN 1
    WHEN 'high'   THEN 2
    WHEN 'normal' THEN 3
    WHEN 'low'    THEN 4
    ELSE 5
  END,
  id;

Challenge 5: Safe Margin Calculation

Medium
Given campaigns(id, name, spend, revenue), return roas (revenue / spend) and margin ((revenue-spend)/revenue). Handle zeros safely — return NULL instead of dividing by zero.
Sample Input
4 campaigns including one with spend=0 and one with revenue=0.
Sample Output
Four rows, zero rows error out, NULLs where appropriate.
Use NULLIF for safe division.
CREATE TABLE campaigns (id INT PRIMARY KEY, name VARCHAR(40), spend DECIMAL(10,2), revenue DECIMAL(10,2));
INSERT INTO campaigns VALUES
  (1,'Google Search',5000,25000),
  (2,'Meta Ads',3200,8000),
  (3,'LinkedIn',1500,0),
  (4,'YouTube',0,4200);

SELECT name, spend, revenue,
  ROUND(revenue / NULLIF(spend, 0), 2)                                         AS roas,
  ROUND((revenue - spend) / NULLIF(revenue, 0), 4)                             AS margin
FROM campaigns;

Challenge 6: Age-Group Census

Medium
Given users(id, name, age), return a count of users per age group: 'Under 18', '18-29', '30-49', '50+'. Sort so the buckets appear in natural order.
Sample Input
8 users across all four buckets.
Sample Output
Four rows, one per bucket.
CASE in both SELECT and GROUP BY. Sort using MIN(age).
CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(50), age INT);
INSERT INTO users VALUES
  (1,'Ishaan Gupta',14),(2,'Kavya Reddy',17),(3,'Arjun Pillai',24),
  (4,'Neha Choudhary',28),(5,'Diya Bhatt',35),(6,'Dev Kapoor',41),
  (7,'Riya Joshi',52),(8,'Kabir Shah',67);

SELECT
  CASE
    WHEN age < 18 THEN 'Under 18'
    WHEN age < 30 THEN '18-29'
    WHEN age < 50 THEN '30-49'
    ELSE            '50+'
  END AS age_group,
  COUNT(*) AS users
FROM users
GROUP BY age_group
ORDER BY MIN(age);

Challenge 7: Rating Pivot

Hard
Given feedback(id, product_id, rating) where rating is 1-5, return per product: count of each star rating as columns (stars_1 through stars_5) plus total_ratings and average_rating (rounded to 2 decimals).
Sample Input
10 feedback rows across 3 products, varied ratings.
Sample Output
One row per product with 7 columns.
Use COUNT(CASE WHEN rating=N THEN 1 END) for each column.
CREATE TABLE feedback (id INT PRIMARY KEY, product_id INT, rating INT);
INSERT INTO feedback VALUES
  (1,1,5),(2,1,4),(3,1,5),(4,1,3),
  (5,2,2),(6,2,1),(7,2,3),
  (8,3,5),(9,3,5),(10,3,4);

SELECT product_id,
  COUNT(CASE WHEN rating=1 THEN 1 END) AS stars_1,
  COUNT(CASE WHEN rating=2 THEN 1 END) AS stars_2,
  COUNT(CASE WHEN rating=3 THEN 1 END) AS stars_3,
  COUNT(CASE WHEN rating=4 THEN 1 END) AS stars_4,
  COUNT(CASE WHEN rating=5 THEN 1 END) AS stars_5,
  COUNT(*)                              AS total_ratings,
  ROUND(AVG(rating), 2)                 AS avg_rating
FROM feedback
GROUP BY product_id
ORDER BY product_id;

Challenge 8: Exam Verdict With Nulls

Hard
Given results(student, maths, english, science) where any subject can be NULL (absent), return student, total (treating NULL as 0), avg_marks, and verdict: 'Incomplete' if any NULL, 'Fail' if any subject < 40, 'Distinction' if avg >= 90, 'First Class' >= 75, 'Second Class' >= 60, else 'Pass'.
Sample Input
5 students, one with NULL in maths, one below 40 in english.
Sample Output
5 rows with verdict column.
Guard NULLs in the FIRST WHEN. Use IFNULL for total.
CREATE TABLE results (student VARCHAR(50), maths INT, english INT, science INT);
INSERT INTO results VALUES
  ('Aarav Sharma',92,88,95),
  ('Priya Nair',75,82,71),
  ('Rohan Mehta',60,33,68),
  ('Ananya Iyer',35,42,39),
  ('Vikram Singh',NULL,80,85);

SELECT student, maths, english, science,
  (IFNULL(maths,0)+IFNULL(english,0)+IFNULL(science,0)) AS total,
  ROUND((IFNULL(maths,0)+IFNULL(english,0)+IFNULL(science,0))/3.0, 1) AS avg_marks,
  CASE
    WHEN maths IS NULL OR english IS NULL OR science IS NULL  THEN 'Incomplete'
    WHEN maths < 40 OR english < 40 OR science < 40           THEN 'Fail'
    WHEN (maths+english+science)/3.0 >= 90                     THEN 'Distinction'
    WHEN (maths+english+science)/3.0 >= 75                     THEN 'First Class'
    WHEN (maths+english+science)/3.0 >= 60                     THEN 'Second Class'
    ELSE                                                           'Pass'
  END AS verdict
FROM results;

Need to Review the Concepts?

Go back to the detailed notes for this chapter.

Read Chapter Notes

Want to master SQL and databases with a mentor?

Explore our MySQL Masterclass