PostgreSQL Aggregate Functions and Group By: Get the difference between the highest and lowest salaries
8. Write a query to get the difference between the highest and lowest salaries.
Sample Solution:
Code:
-- This SQL query calculates the salary difference between the highest and lowest salaries among employees.
SELECT MAX(salary) - MIN(salary) DIFFERENCE -- Calculates the difference between the maximum and minimum salaries from the employees table and labels the result column as "DIFFERENCE"
FROM employees; -- Specifies the table from which to retrieve data, in this case, the employees table
Explanation:
- The SQL query computes the salary difference between the highest and lowest salaries among employees.
- The SELECT statement is used to specify the calculation of the salary difference.
- MAX(salary) retrieves the highest salary from the salary column.
- MIN(salary) retrieves the lowest salary from the salary column.
- MAX(salary) - MIN(salary) calculates the difference between the highest and lowest salaries.
- The result column is labeled as "DIFFERENCE" using the alias DIFFERENCE.
- The FROM clause specifies the table from which to retrieve the data, which is the employees table in this case.
Sample table: employees
Output:
pg_exercises=# SELECT MAX(salary) - MIN(salary) DIFFERENCE pg_exercises-# FROM employees; difference ------------ 21900.00 (1 row)
Practice Online
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a query to get the number of employees working in each post.
Next: Write a query to find the manager ID and the salary of the lowest-paid employee under that manager.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics