Let's come to the point.
I have created an Awesome SQL Interview GitHub repo to prepare for interview questions and practice SQL queries. I have divided the SQL queries into three sections: Basic (L0), Intermediate (L1), and Advanced (L2). This is the solution for the basic section.
This is L1 (Intermediate) SQL queries to practice, refer to L0 first for better practice.
Note: These examples are tested in MySQL. Syntax may vary for other databases like MS-SQL or Oracle.
L1: Intermediate SQL
- Queries that involve working with multiple tables, using
JOIN
,GROUP BY
,HAVING
, and complexWHERE
conditions. - Introduction to subqueries, aggregate functions, and case statements.
Questions:
- Write a query to retrieve the
customerName
andcity
for customers in 'USA' and 'France'. - How do you fetch the
employeeNumber
,lastName
, andofficeCode
of all employees who work in the 'San Francisco' office? - Write a query to find the total number of orders for each customer using
orders
andcustomers
tables. - How do you retrieve the
productName
,quantityInStock
, andbuyPrice
for products that have been ordered more than 10 times? - Write a query to fetch the
orderNumber
,status
, andcustomerName
for orders placed by a customer whosecustomerNumber
is 103. - Write a query to find the total sales value (
quantityOrdered * priceEach
) for each order in theorderdetails
table. - How do you find the average
quantityOrdered
for eachorderNumber
in theorderdetails
table? - Write a query to list the
productLine
with the highest total revenue (quantityOrdered * priceEach
) in theorderdetails
table. - Write a query to display the
employeeNumber
,firstName
,lastName
, and the office name where the employee works by joining theemployees
andoffices
tables. - How do you find the customers who have never placed an order?
- Write a query to retrieve the
customerName
and the total number of orders placed by each customer (include customers who haven’t placed any orders). - Write a query to find the
productName
andquantityOrdered
for all orders where the quantity of the product ordered is greater than 50. - Retrieve the
employeeNumber
,firstName
, andorderNumber
of employees who are assigned assales representatives to customers
that have placed an order. - Write a query to calculate the average price of products in the
products
table based onbuyPrice
. - How do you fetch the top 3 most expensive products in the
products
table? - Write a query to retrieve the
customerName
,orderNumber
, andorderDate
of all orders that have a status of 'Shipped'. - How do you display the total number of products sold for each
productLine
? - Write a query to find employees who report directly to the employee with
employeeNumber = 1143
. - Write a query to calculate the total number of orders in the
orders
table, grouped bystatus
. - List employees with their manager’s name.
I will mention wrong things also, It is important to know what do to but also very important what not to do, and where we make mistake. let's go to the point again...
Solution with the explanation WHERE
needed
-
Query to retrieve the
customerName
andcity
for customers in 'USA' and 'France'.
-
OR
-> Slightly slower if there are a lot of conditions, as the query checks each condition one by one. -
IN
-> slightly optimized internally by the database engine, especially for long lists. - Both are fine for 2-3 conditions. For readability and scalability,
IN
is better, especially when handling larger lists of values. -
IS
is used for checking conditions like IS NULL or IS NOT NULL, not for string comparison.
-
Fetch the
employeeNumber
,lastName
, andofficeCode
of all employees who work in the 'San Francisco' office.
-
Query to find the total number of orders for each customer using
orders
andcustomers
tables.
- Always include non-aggregated columns in the GROUP BY clause when using aggregate functions in your query.
- This ensures SQL knows how to group rows and avoids ambiguity when selecting additional columns.
- In our example:
customerNumber
andcustomerName
must both be in theGROUP BY
clause since we are selecting them along withCOUNT(*)
.
💡 Golden Rule:
Every column in theSELECT
list must either:
Be in theGROUP BY
clause, OR
Use an aggregate function likeCOUNT()
,SUM()
, etc. -
Retrieve the
productName
,quantityInStock
, andbuyPrice
for products that have been ordered more than 10 times?
- This query is efficient for small and medium size databases, for large sizes we can use indexes, and reduce data scanned using
WHERE
clause instead of relying solely onHAVING
clause
- This query is efficient for small and medium size databases, for large sizes we can use indexes, and reduce data scanned using
-
Fetch the
orderNumber
,status
, andcustomerName
for orders placed by a customer whosecustomerNumber
is 103.
Explanation:
- Tables Used:
- orders: Contains orderNumber and status.
- customers: Contains customerName.
- INNER JOIN:
- Combines orders and customers tables using the customerNumber column (common key).
- WHERE Clause:
- Filters the data to include only records where customerNumber = 103.
- Columns Selected:
- o.orderNumber: The order number.
- o.status: The order status.
- c.customerName: The name of the customer placing the order.
- Tables Used:
Find the total sales value (
quantityOrdered * priceEach
) for each order in theorderdetails
table.
-
Find the average
quantityOrdered
for eachorderNumber
in theorderdetails
table.
- Explanation:
- orderNumber:
- Groups the rows by the orderNumber.
- AVG(quantityOrdered):
- Calculates the average quantityOrdered for all rows that belong to the same orderNumber.
- GROUP BY:
- Ensures the average is calculated for each orderNumber separately.
-
Query to list the
productLine
with the highest total revenue (quantityOrdered * priceEach
) in theorderdetails
table.
- Explanation:
- productLine:
- Categorizes the products into different lines, like "Motorcycles" or "Planes."
- SUM(od.
quantityOrdered
* od.priceEach
):- Calculates the total revenue for each productLine.
- INNER JOIN:
- Joins products and
orderdetails
tables onproductCode
to associate product lines with their order details.
- Joins products and
- GROUP BY p.productLine:
-
Groups
the results by eachproductLine
.
-
- ORDER BY
totalRevenue
DESC:- Sorts the grouped results in descending order of revenue, so the highest revenue appears first.
- LIMIT 1:
- Restricts the result to only the
productLine
with the highest revenue.
- Restricts the result to only the
-
Query to display the
employeeNumber
,firstName
,lastName
, and the office name where the employee works by joining theemployees
andoffices
tables.
CONCAT(column, 'separater', column, 'separater', column)
CONCAT_WS('separater', columns)
-
Find the customers who have never placed an order
Explanation:
-
LEFT JOIN: Retrieves all customers from the
customers
table, whether or not they have matching rows in the orders table. -
o.orderNumber
IS NULL: Identifies customers who do not have any corresponding orders (i.e., orderNumber is NULL because there's no match in the orders table). -
Columns:
-
customerNumber
: Unique identifier for the customer. -
customerName
: Name of the customer.
-
-
LEFT JOIN: Retrieves all customers from the
Query to retrieve the
customerName
and the total number of orders placed by each customer (include customers who haven’t placed any orders).Find the
productName
andquantityOrdered
for all orders where the quantity of the product ordered is greater than 50.
-
Retrieve the
employeeNumber
,firstName
, andorderNumber
of employees who are assigned assales representatives to customers
that have placed an order.
Explanation:
-
FROM employees e
:- We start with the
employees
table (aliased as e) because we want the employee details, specifically theemployeeNumber
andfirstName
.
- We start with the
-
JOIN customers c ON e.employeeNumber = c.salesRepEmployeeNumber
:- We join the customers table (aliased as c) on the
employeeNumber
from employees andsalesRepEmployeeNumber
from customers. This creates the relationship betweenemployees
(sales reps) and customers. Now, we can identify which employee is assigned to each customer.
- We join the customers table (aliased as c) on the
-
JOIN orders o ON c.customerNumber = o.customerNumber
:- We further join the orders table (aliased as o) with the
customers
table using thecustomerNumber
. This gives us the orders placed by each customer.
- We further join the orders table (aliased as o) with the
-
SELECT e.employeeNumber, e.firstName, o.orderNumber
:- Finally, we select the
employeeNumber
and firstName from theemployees
table (sales reps) and theorderNumber
from the orders table for each customer who has placed an order.
- Finally, we select the
-
Query to calculate the average price of products in the
products
table based onbuyPrice
.
Fetch the top 3 most expensive products in the
products
table?
Rretrieve the
customerName
,orderNumber
, andorderDate
of all orders that have a status of 'Shipped'.
Display the total number of products sold for each
productLine
Find employees who report directly to the employee with
employeeNumber = 1143
.
Query to calculate the total number of orders in the
orders
table, grouped bystatus
.
Hey, My name is Jaimin Baria AKA Cloud Boy..., If you have enjoyed and learned something useful, like this post, add a comment, and visit my Awesome SQL Interview GitHub repo.
Don't forget to give it a start 😅.
Happy Coding 🧑💻
Other Posts
- SQL Practices:
- Part 1
- L0: Basic SQL
- L1: Intermediate SQL
- L2: Advanced SQL - Will Come soon
- Part 1
- System Design
Top comments (4)
You need to declare your SQL dialect: most of those queries won't run in MS-SQL
Thank you for pointing that out! 😊 You're absolutely right that SQL syntax can vary between different databases like MySQL, PostgreSQL, and MS-SQL. These queries are primarily designed for MySQL, and I should have clarified that in the article. I'll update it soon to specify the SQL dialect and include any necessary notes about compatibility. Thanks again for the valuable feedback!
-
.