SQL
SQL
Question: Write a SQL query to get the department, COUNT(*) (number of employees), and the
AVG(salary) for each department from the employees table. The results should be grouped by
department.
Question: Write a SQL query to get the department and the total salary (SUM(salary)) for each
department in the employees table. The result should be ordered by the total salary in descending
order.
SELECT department, SUM (salary) TotalSalary FROM employees GROUP BY department ORDER
BY TotalSalary DESC;
Question: Write a SQL query to find the second highest salary from the employees table.
SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees);
Question: Write a SQL query to find all employees who have the same salary as the average salary of
all employees in the company.
SELECT first_name, last_name FROM employees WHERE salary = (SELECT AVG(salary) FROM
employees);
Question: Write a SQL query to find the total number of employees in each department, and display
the department name along with the number of employees.
Question: Write an SQL query to find the total sales value for each product (i.e., quantity *
sale_price), grouped by product_id.
Employees
1 John Doe HR
2 Jane Smith IT
3 Alice Johnson IT
Contractors
Question: Write an SQL query to get a list of all employees and contractors (both first and last
names), from both the Employees and Contractors tables.
SELECT first_name, last_name FROM Employees UNION SELECT first_name, last_name FROM
Contractors
Employees
ELSE 'High'
END AS salary_grade
FROM Employees;
Question 19: (JOIN with Aggregation) You have the following two tables:
Orders
Customers
Question: Write an SQL query to find the total amount spent by each customer (sum of
total_amount), along with their first_name and last_name, ordered by the total amount in
descending order.
You should also include c.first_name and c.last_name in the GROUP BY clause to avoid SQL
errors. This is because any column in the SELECT list that is not aggregated (like
SUM(o.total_amount)) needs to be part of the GROUP BY clause.