Hone logo
Hone
Problems

Handling Missing Product Prices with COALESCE

In real-world databases, it's common for some data fields to be missing. This can lead to unexpected results in queries, especially when performing calculations or displaying information. This challenge focuses on using the COALESCE function to gracefully handle NULL values in a product catalog, ensuring that our queries always produce meaningful results.

Problem Description

You are tasked with querying a Products table that contains information about various products, including their names and prices. However, some products might not have a price recorded, resulting in NULL values in the price column. You need to write a SQL query that retrieves the product name and its price. If a product's price is NULL, you should display a default value of 0.00 instead. This ensures that all products are represented with a numerical price, even if it's zero, making subsequent analysis or display much simpler.

Key Requirements:

  • Retrieve the product_name from the Products table.
  • Retrieve the price from the Products table.
  • If the price is NULL, substitute it with 0.00.
  • The query should be efficient and handle potentially large datasets.

Expected Behavior: The output should be a list of all products, each with its name and its corresponding price. Products with a recorded price will show that price, while products with a NULL price will show 0.00.

Examples

Example 1:

Input:

Products table:

product_idproduct_nameprice
1Laptop1200.50
2Keyboard75.00
3MouseNULL

Output:

product_namedisplay_price
Laptop1200.50
Keyboard75.00
Mouse0.00

Explanation: For 'Laptop' and 'Keyboard', their existing prices are displayed. For 'Mouse', since the price is NULL, COALESCE substitutes it with 0.00.

Example 2:

Input:

Products table:

product_idproduct_nameprice
4Monitor300.00
5WebcamNULL
6Speakers150.75
7MicrophoneNULL

Output:

product_namedisplay_price
Monitor300.00
Webcam0.00
Speakers150.75
Microphone0.00

Explanation: Similar to Example 1, NULL prices for 'Webcam' and 'Microphone' are replaced with 0.00.

Constraints

  • The Products table will contain at least one row.
  • product_name will always be a non-NULL string.
  • price can be a decimal number or NULL.
  • The query should execute within typical database performance expectations for such an operation.

Notes

The COALESCE function in SQL returns the first non-NULL expression from its list of arguments. Consider what arguments you need to provide to COALESCE to achieve the desired output. You will likely need to alias the resulting column to something descriptive, like display_price.

Loading editor...
plaintext