How do you write a query to get the difference between the highest and lowest values in a column?
Posted by AliceWk
Last Updated: July 18, 2024
To calculate the difference between the highest and lowest values in a column using SQL, you can use the MAX() and MIN() aggregate functions in a single query. Here’s an example of how you can do this:
SELECT (MAX(column_name) - MIN(column_name)) AS difference
FROM table_name;
Replace column_name with the name of the column you are interested in and table_name with the name of the table where the data is stored.
Example
Assume you have a table named sales and you want to find the difference between the highest and lowest sale amount in the amount column. Your query would look like this:
SELECT (MAX(amount) - MIN(amount)) AS difference
FROM sales;
This will return a single value representing the difference between the maximum and minimum sale amounts in the amount column.