SQL SCENARIO
BASED QUESTIONS
PART-3
You need to retrieve the top 5 highest-paid
employees from the employees table.
Question:
How would you use the ORDER BY and LIMIT clauses to get
the top records?
The ORDER BY clause sorts the data, and the LIMIT clause
restricts the number of rows returned. To retrieve the top 5
highest-paid employees, you need to sort the salary in
descending order and use LIMIT 5.
For Example:
This query will display the top 5 employees by salary.
You want to calculate the total salary for
each department.
Question:
How can you use the GROUP BY clause to aggregate data?
The GROUP BY clause groups rows with the same values,
allowing aggregate functions like SUM() to be applied to each
group. In this scenario, we group employees by department
and calculate the total salary for each department.
For Example:
This query returns the total salary for each department.
You need to display departments with a
total salary greater than 100,000.
Question:
How can you filter grouped data using the HAVING clause?
The HAVING clause filters grouped data after aggregation.
In this scenario, it ensures only departments with a total
salary greater than 100,000 are displayed.
For Example:
This query displays departments whose combined salaries
exceed 100,000.
You need to combine employees from
two tables: employees_2023 and
employees_2024.
Question:
How would you use the UNION operator to combine the
data?
The UNION operator combines the result sets of two SELECT
queries and removes duplicates. Both queries must return
the same number of columns with compatible
data types.
For Example:
This query returns a combined list of employees from both
tables, without duplicates.
You want to keep duplicates while
combining two datasets.
Question:
How can you use UNION ALL to retain all rows, including
duplicates?
The UNION ALL operator combines result sets and keeps
all rows, including duplicates. It is more efficient since it
doesn’t check for duplicates.
For Example:
This query retains all duplicate rows from both datasets.
Liked these SQL
scenario based
questions?🤔
Follow for more
data insights,
interview tips,
and tech content!