Calculate Average Order Value
You are tasked with analyzing sales data to understand the average value of customer orders. Calculating the average order value is crucial for businesses to gauge customer spending habits, assess the effectiveness of marketing campaigns, and make informed pricing decisions.
Problem Description
You need to write an SQL query that calculates the average order_value for all orders in a given table. The query should return a single value representing this average.
Key Requirements:
- Calculate the arithmetic mean of the
order_valuecolumn. - The output should be a single numerical value.
Expected Behavior:
The query should process all rows in the orders table and compute the average of the order_value for each row.
Edge Cases:
- Empty Table: If the
orderstable is empty, what should be returned? (Consider thatAVGtypically returnsNULLfor empty sets). - NULL
order_value: How shouldNULLvalues in theorder_valuecolumn be handled? (Standard SQLAVGignoresNULLvalues).
Examples
Example 1:
Input:
orders table:
| order_id | customer_id | order_value |
|---|---|---|
| 101 | 1 | 50.00 |
| 102 | 2 | 75.50 |
| 103 | 1 | 25.00 |
Output:
60.17
Explanation:
The sum of order_value is 50.00 + 75.50 + 25.00 = 150.50.
There are 3 orders.
The average is 150.50 / 3 = 50.1666... which rounds to 50.17 (assuming typical decimal precision).
Example 2:
Input:
orders table:
| order_id | customer_id | order_value |
|---|---|---|
| 201 | 3 | 100.00 |
| 202 | 4 | NULL |
| 203 | 3 | 200.00 |
Output:
150.00
Explanation:
The order_value of 202 is NULL and is ignored in the calculation.
The sum of order_value is 100.00 + 200.00 = 300.00.
There are 2 non-NULL order_value entries.
The average is 300.00 / 2 = 150.00.
Example 3:
Input:
orders table: (empty)
Output:
NULL
Explanation:
When the orders table is empty, there are no values to average, so the result is NULL.
Constraints
- The
orderstable will have at least one column namedorder_id(integer),customer_id(integer), andorder_value(decimal or float type). - The
order_valuecolumn can containNULLvalues. - The query should be efficient and perform well on tables with up to 1 million rows.
Notes
- You will be querying a table named
orders. - Pseudocode for the relevant SQL function is
AVG(column_name). - Consider the data type of the
order_valuecolumn and how it might affect the precision of the average. The output should generally be a floating-point or decimal number.