ANSI SQL Extensions  «Prev  Next»

Oracle 26ai DECODE Exercise

Translate car-sale codes and label subtotals

Objective: Use DECODE for labels, aggregate sales consistently, and distinguish stored nulls from ROLLUP summary rows.

Self-assessment: 15 points

A correct detail report is worth 10 points. Correct ROLLUP and GROUPING labels earn the remaining 5 points. The site displays your submitted text and a model answer; it does not execute SQL or automatically grade free-text answers.

Scenario and preparation

Each row of car represents one sold vehicle. Use the following schema description in an approved practice environment if you choose to run the queries. Do not create objects in a production schema for this exercise. No Oracle commands were executed to prepare this example.

CREATE TABLE car (
    car_make        VARCHAR2(20),
    car_color       NUMBER(2),
    sale_state_code NUMBER(2),
    sale_price      NUMBER(12,2)
);
Code mappings
ColumnCodes and labels
sale_state_code12: California; 33: Nebraska; 44: North Carolina
car_color1: Red; 2: Blue; 3: Green

Use Unknown state and Unknown color for unrecognized codes, including stored nulls. Group by the original codes, so distinct unknown codes need not merge merely because their display labels match. Sale prices may be null: COUNT(*) counts sold vehicles, while AVG(sale_price) averages only known prices. Do not replace missing prices with zero.

Tasks

  1. Replace the two codes in this detail report with DECODE labels, retaining NUMBER_SOLD and AVG_SALE_PRICE.
  2. Add a second version with ROLLUP(sale_state_code, car_color), state subtotals, and a grand total.
  3. Use GROUPING to label generated summaries All states and All colors. Keep stored null codes labeled Unknown state or Unknown color.
  4. Explain why the grand-total average must be calculated from source rows rather than averaging the displayed group averages.
SELECT sale_state_code, car_color,
       COUNT(*) AS number_sold,
       ROUND(AVG(sale_price), 2) AS avg_sale_price
FROM car
GROUP BY sale_state_code, car_color;

Check your reasoning with two California/Blue sales priced 100 and 200 and one Nebraska/Red sale with a null price. Expected detail counts are 2 and 1; the known-price averages are 150 and null. The grand total has count 3 and average 150. These are derived expectations, not execution output.

Submit your SQL and explanation

Keep a local copy and omit credentials or sensitive data.