Find Median Salary
Description
Write a SQL query to find the median salary of all employees. Return the median salary. For an odd number of employees, return the middle value. For an even number, return the average of the two middle values. **Output columns (in order):** median_salary
employee| Column | Type |
|---|---|
| id | INT |
| salary | INT |
Examples
CREATE TABLE employee (id INT, salary INT); INSERT INTO employee VALUES (1, 50000), (2, 55000), (3, 60000), (4, 70000), (5, 45000);55000Sorted salaries: [45000, 50000, 55000, 60000, 70000]. With 5 employees (odd count), the median is the middle (3rd) value: 55000.
CREATE TABLE employee (id INT, salary INT); INSERT INTO employee VALUES (1, 80000), (2, 65000), (3, 90000), (4, 75000);77500With 4 employees (even count), sorted salaries are [65000, 75000, 80000, 90000]. The median is the average of the two middle values: (75000+80000)/2 = 77500.
CREATE TABLE employee (id INT, salary INT); INSERT INTO employee VALUES (1, 100000), (2, 85000), (3, 95000), (4, 120000), (5, 110000), (6, 90000), (7, 105000);100000With 7 employees (odd count), sorted salaries are [85000, 90000, 95000, 100000, 105000, 110000, 120000]. The median is the middle (4th) value: 100000.
Constraints
- •
Handle odd/even count
Ready to solve this problem?
Practice solo and sharpen your skills for technical interviews.