Averages that skip NULLs

null handling

Averages that skip NULLs

Amazon SQL Interview Question

Two Amazon analysts reported different average discounts for the same catalog, and both were right. One averaged only the products that have a discount recorded. The other treated a product with no discount as 0% off.

Calculate both numbers in a single row: the first analyst's average as avg_listed_discount and the second analyst's average as avg_overall_discount. Do not round the results.

Asked of

  • Data Analyst
  • Data Scientist
  • Analytics Engineer
  • ML Engineer
  • AI Engineer

productsTable15 rows

Column NameType
product_idBIGINT
product_nameVARCHAR
categoryVARCHAR
brandVARCHAR
priceDOUBLE
discount_pctBIGINT
stock_quantityBIGINT
launch_dateDATE
is_activeBOOLEAN

productsExample Input

product_idproduct_namecategorybrandpricediscount_pctstock_quantitylaunch_dateis_active
1Wireless MouseElectronicsLogitech24.99101502023-02-14true
2Mechanical Keyboard ProElectronicsKeychron119NULL402023-05-01true
3Noise Canceling HeadphonesElectronicsSony299.991502022-11-20true
4Standing DeskFurnitureFlexispot349NULL122023-08-09true
5Ergonomic Chair ProFurnitureSteelcase1299552021-06-30true
6Desk LampFurnitureNULL39.5NULL802024-01-15true
7USB-C HubElectronicsAnker45202002023-03-22true
8Notebook SetStationeryMoleskine18NULL02022-09-01false

Example Output

avg_listed_discountavg_overall_discount
12.56.25

Explanation

Four of the eight products have a discount: 10, 15, 5 and 20, which add up to 50. Averaging only those four gives 12.5. Counting the other four products as 0% off spreads the same 50 across all eight products, which gives 6.25.

The example above is a small slice of the data. Your query runs against the full tables.