SQL Queries
SQL Queries
sql
Copy
SELECT employee_id, salary, AVG(salary) OVER () AS average_salary
FROM employees
ORDER BY salary DESC
FETCH FIRST 5 ROWS ONLY;
2. Q: Calculate the running total of sales for each month in the
sales table.
A:
sql
Copy
SELECT month, sales, SUM(sales) OVER (ORDER BY month) AS running_total
FROM sales_table;
3. Q: Find the percentage of total revenue generated by each
product category in the sales table.
A:
sql
Copy
SELECT category, revenue,
(revenue / SUM(revenue) OVER ()) * 100 AS percentage
FROM sales_table;
4. Q: Retrieve the top 3 customers with the highest total order
amounts, along with the cumulative order amount for each
customer.
A:
sql
Copy
SELECT customer_id, total_order_amount,
SUM(total_order_amount) OVER (ORDER BY total_order_amount DESC)
AS cumulative_amount
FROM customers
ORDER BY total_order_amount DESC
FETCH FIRST 3 ROWS ONLY;
5. Q: Calculate the average rating for each movie, considering
only the previous ratings up to the current row.
A:
sql
Copy
SELECT movie_id, rating,
AVG(rating) OVER (ORDER BY movie_id ROWS BETWEEN UNBOUNDED
PRECEDING AND CURRENT ROW) AS average_rating
FROM movies;
6. Q: Retrieve the top 5 products with the highest sales, along
with the rank of each product based on sales.
A:
sql
Copy
SELECT product_id, sales, RANK() OVER (ORDER BY sales DESC) AS
sales_rank
FROM products
FETCH FIRST 5 ROWS ONLY;
7. Q: Find the difference between the revenue of each country
and the average revenue across all countries.
A:
sql
Copy
SELECT country, revenue, revenue - AVG(revenue) OVER () AS
revenue_difference
FROM sales_table;
8. Q: Calculate the average order quantity for each customer,
considering only the orders placed after a specific date.
A:
sql
Copy
SELECT customer_id, order_quantity,
AVG(order_quantity) OVER (PARTITION BY customer_id ORDER BY
order_date
ROWS BETWEEN UNBOUNDED PRECEDING AND
CURRENT ROW) AS average_order_quantity
FROM orders
WHERE order_date > '2022-01-01';
9. Q: Retrieve the top 3 employees with the highest sales, along
with the percentage of total sales they contribute.
A:
sql
Copy
SELECT employee_id, sales,
(sales / SUM(sales) OVER ()) * 100 AS sales_percentage
FROM employees
ORDER BY sales DESC
FETCH FIRST 3 ROWS ONLY;
10. Q: Calculate the moving average of sales for every three
consecutive months in the sales table.
A:
sql
Copy
SELECT month, sales,
AVG(sales) OVER (ORDER BY month ROWS BETWEEN 2 PRECEDING AND
CURRENT ROW) AS moving_average
FROM sales_table;
sql
Copy
SELECT employee_id, salary,
LAG(salary) OVER (ORDER BY employee_id) AS previous_salary,
LEAD(salary) OVER (ORDER BY employee_id) AS next_salary
FROM employees;
2. Question: Find the time difference between consecutive log
entries.
Answer:
sql
Copy
SELECT log_timestamp,
LAG(log_timestamp) OVER (ORDER BY log_timestamp) AS
previous_timestamp,
log_timestamp - LAG(log_timestamp) OVER (ORDER BY log_timestamp)
AS time_difference
FROM logs;
3. Question: Get the previous and next product names for each
product.
Answer:
sql
Copy
SELECT product_id, product_name,
LAG(product_name) OVER (ORDER BY product_id) AS
previous_product,
LEAD(product_name) OVER (ORDER BY product_id) AS next_product
FROM products;
4. Question: Calculate the percentage change in revenue from
the previous year.
Answer:
sql
Copy
SELECT year, revenue,
(revenue - LAG(revenue) OVER (ORDER BY year)) / LAG(revenue)
OVER (ORDER BY year) * 100 AS percentage_change
FROM sales;
5. Question: Find the difference in stock quantity compared to the
previous day.
Answer:
sql
Copy
SELECT date, stock_quantity,
stock_quantity - LAG(stock_quantity) OVER (ORDER BY date) AS
quantity_difference
FROM inventory;
6. Question: Retrieve the next and previous order dates for each
customer.
Answer:
sql
Copy
SELECT customer_id, order_date,
LAG(order_date) OVER (PARTITION BY customer_id ORDER BY
order_date) AS previous_order,
LEAD(order_date) OVER (PARTITION BY customer_id ORDER BY
order_date) AS next_order
FROM orders;
7. Question: Get the previous and next exam scores for each
student.
Answer:
sql
Copy
SELECT student_id, exam_score,
LAG(exam_score) OVER (PARTITION BY student_id ORDER BY
exam_date) AS previous_score,
LEAD(exam_score) OVER (PARTITION BY student_id ORDER BY
exam_date) AS next_score
FROM exams;
8. Question: Calculate the time difference between consecutive
sales transactions for each product.
Answer:
sql
Copy
SELECT product_id, sale_timestamp,
sale_timestamp - LAG(sale_timestamp) OVER (PARTITION BY
product_id ORDER BY sale_timestamp) AS time_difference
FROM sales_transactions;
9. Question: Retrieve the previous and next login timestamps for
each user.
Answer:
sql
Copy
SELECT user_id, login_timestamp,
LAG(login_timestamp) OVER (PARTITION BY user_id ORDER BY
login_timestamp) AS previous_login,
LEAD(login_timestamp) OVER (PARTITION BY user_id ORDER BY
login_timestamp) AS next_login
FROM user_logins;
10. Question: Find the percentage change in temperature
from the previous hour.
Answer:
sql
Copy
SELECT hour, temperature,
(temperature - LAG(temperature) OVER (ORDER BY hour)) /
LAG(temperature) OVER (ORDER BY hour) * 100 AS percentage_change
FROM weather_data;
Copy
SELECT CONCAT('Hello', 'World') AS ConcatenatedString;
SELECT 'Hello' + 'World' AS ConcatenatedString;
2. Question: How can you extract a substring from a string in
SQL?
Answer: You can use the SUBSTRING function to extract a
substring from a string. For example:
sql_more
Copy
SELECT SUBSTRING('Hello World', 7) AS Substring;
SELECT SUBSTRING('Hello World', 7, 5) AS Substring;
3. Question: How can you find the length of a string in SQL?
Answer: You can use the LEN function to find the length of a
string. For example:
Copy
SELECT LEN('Hello World') AS StringLength;
4. Question: How can you convert a string to uppercase in SQL?
Answer: You can use the UPPER function to convert a string to
uppercase. For example:
Copy
SELECT UPPER('Hello World') AS UppercaseString;
5. Question: How can you convert a string to lowercase in SQL?
Answer: You can use the LOWER function to convert a string to
lowercase. For example:
Copy
SELECT LOWER('Hello World') AS LowercaseString;
6. Question: How can you replace a substring within a string in
SQL?
Answer: You can use the REPLACE function to replace a
substring within a string. For example:
Copy
SELECT REPLACE('Hello World', 'World', 'Universe') AS ReplacedString;
7. Question: How can you trim leading or trailing spaces from a
string in SQL?
Answer: You can use the LTRIM function to trim leading spaces
and the RTRIM function to trim trailing spaces from a string.
For example:
Copy
SELECT LTRIM(' Hello World ') AS TrimmedString;
SELECT RTRIM(' Hello World ') AS TrimmedString;
8. Question: How can you find the position of a substring within a
string in SQL?
Answer: You can use the CHARINDEX function to find the
position of a substring within a string. For example:
Copy
SELECT CHARINDEX('World', 'Hello World') AS SubstringPosition;
9. Question: How can you reverse a string in SQL?
Answer: You can use a combination of string functions like
REVERSE and LEN to reverse a string. For example:
Copy
SELECT REVERSE('Hello World') AS ReversedString;
10. Question: How can you extract a specific number of
characters from the left or right side of a string in SQL?
Answer: You can use the LEFT function to extract characters
from the left side of a string or the RIGHT function to extract
characters from the right side of a string. For example:
Copy
SELECT LEFT('Hello World', 5) AS LeftSubstring;
SELECT RIGHT('Hello World', 5) AS RightSubstring;
sql
Copy
SELECT CAST('123' AS INT);
2. Question: How can you convert a numeric data type to a string
in SQL?
Answer: You can use the CAST or CONVERT function, along
with the appropriate data type. For example, to convert an
integer 123 to a string, you can use:
sql
Copy
SELECT CAST(123 AS VARCHAR);
3. Question: How can you convert a date to a specific format in
SQL?
Answer: You can use the CONVERT function with the
appropriate style parameter. For example, to convert a date to
the format 'YYYY-MM-DD', you can use:
sql
Copy
SELECT CONVERT(VARCHAR, GETDATE(), 23);
4. Question: How can you extract only the year from a date in
SQL?
Answer: You can use the YEAR function. For example, to
extract the year from a date column called 'birthdate', you can
use:
sql
Copy
SELECT YEAR(birthdate) FROM your_table;
5. Question: How can you convert a string representation of a
date to an actual date in SQL?
Answer: You can use the CAST or CONVERT function with the
appropriate style parameter. For example, to convert the string
'2022-01-01' to a date, you can use:
sql
Copy
SELECT CAST('2022-01-01' AS DATE);
6. Question: How can you convert a date to UNIX timestamp in
SQL?
Answer: You can use the DATEDIFF function with the
appropriate parameters. For example, to convert a date
column called 'my_date' to a UNIX timestamp, you can use:
sql
Copy
SELECT DATEDIFF(second, '1970-01-01', my_date) AS unix_timestamp FROM
your_table;
7. Question: How can you convert a decimal number to a
percentage in SQL?
Answer: You can use the FORMAT function. For example, to
convert a decimal column called 'percentage' to a percentage
format, you can use:
sql
Copy
SELECT FORMAT(percentage, 'P') FROM your_table;
8. Question: How can you convert a string to a datetime data
type in SQL?
Answer: You can use the CONVERT function with the
appropriate style parameter. For example, to convert the string
'2022-01-01 12:00:00' to a datetime, you can use:
sql
Copy
SELECT CONVERT(DATETIME, '2022-01-01 12:00:00', 120);
9. Question: How can you convert a time to a specific format in
SQL?
Answer: You can use the CONVERT function with the
appropriate style parameter. For example, to convert a time
column called 'my_time' to the format 'HH:MI AM/PM', you can
use:
sql
Copy
SELECT CONVERT(VARCHAR, my_time, 100);
10. Question: How can you convert a binary data type to a
string in SQL?
Answer: You can use the CONVERT function with the
appropriate style parameter. For example, to convert a binary
column called 'my_binary' to a string, you can use:
sql
Copy
SELECT CONVERT(VARCHAR(MAX), my_binary, 2) FROM your_table;
1. Question:
Write an SQL query to find the length of the longest name
(character count) among all the customers.
Answer:
sql
Copy
SELECT MAX(LENGTH(name)) AS longest_name_length
FROM customers;
2. Question:
Write an SQL query to calculate the average salary of
employees, rounded to the nearest integer.
Answer:
sql
Copy
SELECT ROUND(AVG(salary)) AS average_salary
FROM employees;
3. Question:
Write an SQL query to find the number of orders placed by
each customer, sorted in descending order of order count.
Answer:
sql
Copy
SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
ORDER BY order_count DESC;
4. Question:
Write an SQL query to concatenate the first name and last
name of employees, separated by a space.
Answer:
sql
Copy
SELECT CONCAT(first_name, ' ', last_name) AS full_name
FROM employees;
5. Question:
Write an SQL query to find the total revenue generated by
each product, including the sum of quantity multiplied by price.
Answer:
sql
Copy
SELECT product_id, SUM(quantity * price) AS total_revenue
FROM sales
GROUP BY product_id;
6. Question:
Write an SQL query to extract the month and year from a given
date column.
Answer:
sql
Copy
SELECT MONTH(date_column) AS month, YEAR(date_column) AS year
FROM table_name;
7. Question:
Write an SQL query to find the number of occurrences of a
specific character within a string.
Answer:
sql
Copy
SELECT (LENGTH(string_column) - LENGTH(REPLACE(string_column, 'character',
''))) / LENGTH('character') AS character_count
FROM table_name;
8. Question:
Write an SQL query to calculate the difference in days between
two given dates.
Answer:
sql
Copy
SELECT DATEDIFF('2022-05-10', '2022-03-15') AS date_difference_in_days;
9. Question:
Write an SQL query to convert a string to uppercase.
Answer:
sql
Copy
SELECT UPPER(string_column) AS uppercase_string
FROM table_name;
10. Question:
Write an SQL query to find the maximum and minimum values
from a column and display them with custom labels.
Answer:
sql
Copy
SELECT MAX(column_name) AS maximum_value, MIN(column_name) AS minimum_value
FROM table_name;
sql
Copy
SELECT *
FROM (
SELECT Category, Year, Sales
FROM YourTable
) AS SourceTable
PIVOT (
SUM(Sales)
FOR Year IN ([2020], [2021], [2022])
) AS PivotTable;
2. Question: Show the number of orders placed by each customer
in separate columns for different months.
Answer:
sql
Copy
SELECT *
FROM (
SELECT Customer, Month, COUNT(OrderID) AS OrderCount
FROM YourTable
GROUP BY Customer, Month
) AS SourceTable
PIVOT (
SUM(OrderCount)
FOR Month IN ([January], [February], [March])
) AS PivotTable;
3. Question: Display the highest and lowest temperatures
recorded for each city in separate columns for different dates.
Answer:
sql
Copy
SELECT *
FROM (
SELECT City, Date, Temperature
FROM YourTable
) AS SourceTable
PIVOT (
MIN(Temperature) AS MinTemp, MAX(Temperature) AS MaxTemp
FOR Date IN ([2022-01-01], [2022-01-02], [2022-01-03])
) AS PivotTable;
4. Question: Show the total quantity sold for each product in
separate columns for different regions.
Answer:
sql
Copy
SELECT *
FROM (
SELECT Product, Region, Quantity
FROM YourTable
) AS SourceTable
PIVOT (
SUM(Quantity)
FOR Region IN ([North], [South], [East], [West])
) AS PivotTable;
5. Question: Display the average ratings given by each user for
different movies in separate columns.
Answer:
sql
Copy
SELECT *
FROM (
SELECT User, Movie, Rating
FROM YourTable
) AS SourceTable
PIVOT (
AVG(Rating)
FOR Movie IN ([Movie1], [Movie2], [Movie3])
) AS PivotTable;
6. Question: Show the count of employees in different
departments for each year.
Answer:
sql
Copy
SELECT *
FROM (
SELECT Department, Year, COUNT(EmployeeID) AS EmployeeCount
FROM YourTable
GROUP BY Department, Year
) AS SourceTable
PIVOT (
SUM(EmployeeCount)
FOR Year IN ([2020], [2021], [2022])
) AS PivotTable;
7. Question: Display the total revenue generated by each product
for different quarters.
Answer:
sql
Copy
SELECT *
FROM (
SELECT Product, Quarter, Revenue
FROM YourTable
) AS SourceTable
PIVOT (
SUM(Revenue)
FOR Quarter IN ([Q1], [Q2], [Q3], [Q4])
) AS PivotTable;
8. Question: Show the number of students enrolled in different
courses for each semester.
Answer:
sql
Copy
SELECT *
FROM (
SELECT Course, Semester, COUNT(StudentID) AS StudentCount
FROM YourTable
GROUP BY Course, Semester
) AS SourceTable
PIVOT (
SUM(StudentCount)
FOR Semester IN ([Spring], [Summer], [Fall])
) AS PivotTable;
9. Question: Display the total sales for each product category in
separate columns for different quarters.
Answer:
sql
Copy
SELECT *
FROM (
SELECT Category, Quarter, Sales
FROM YourTable
) AS SourceTable
PIVOT (
SUM(Sales)
FOR Quarter IN ([Q1], [Q2], [Q3], [Q4])
) AS PivotTable;
10. Question: Show the average duration of tasks completed
by each employee in different projects.
Answer:
sql
Copy
SELECT *
FROM (
SELECT Employee, Project, Duration
FROM YourTable
) AS SourceTable
PIVOT (
AVG(Duration)
FOR Project IN ([Project1], [Project2], [Project3])
) AS PivotTable;
1. Question:
Given two tables, "Customers" and "Orders," retrieve the
names of customers who have placed orders for all available
products.
Answer:
sql
Copy
SELECT c.name
FROM Customers c
WHERE NOT EXISTS (
SELECT *
FROM Products p
WHERE NOT EXISTS (
SELECT *
FROM Orders o
WHERE o.customer_id = c.id
AND o.product_id = p.id
)
);
2. Question:
Retrieve the names of customers who have placed orders for
at least three different products.
Answer:
sql
Copy
SELECT c.name
FROM Customers c
JOIN Orders o ON c.id = o.customer_id
GROUP BY c.id, c.name
HAVING COUNT(DISTINCT o.product_id) >= 3;
3. Question:
Retrieve all products that have been ordered by customers
who have not placed any orders for product ID 5.
Answer:
sql
Copy
SELECT p.*
FROM Products p
JOIN Orders o ON p.id = o.product_id
WHERE o.customer_id NOT IN (
SELECT customer_id
FROM Orders
WHERE product_id = 5
);
4. Question:
Retrieve the names of customers who have placed orders for
both product ID 3 and product ID 7.
Answer:
sql
Copy
SELECT c.name
FROM Customers c
JOIN Orders o1 ON c.id = o1.customer_id
JOIN Orders o2 ON c.id = o2.customer_id
WHERE o1.product_id = 3 AND o2.product_id = 7;
5. Question:
Retrieve the names of customers who have placed orders for
all products with odd product IDs.
Answer:
sql
Copy
SELECT c.name
FROM Customers c
JOIN Orders o ON c.id = o.customer_id
JOIN Products p ON o.product_id = p.id
WHERE p.id % 2 = 1
GROUP BY c.id, c.name
HAVING COUNT(DISTINCT p.id) = (
SELECT COUNT(*)
FROM Products
WHERE id % 2 = 1
);
6. Question:
Retrieve the names of customers who have placed orders for
any product that has not been ordered by any other customer.
Answer:
sql
Copy
SELECT c.name
FROM Customers c
JOIN Orders o ON c.id = o.customer_id
JOIN Products p ON o.product_id = p.id
WHERE NOT EXISTS (
SELECT *
FROM Orders o2
WHERE o2.product_id = p.id
AND o2.customer_id <> o.customer_id
);
7. Question:
Retrieve all products that have been ordered by every
customer.
Answer:
sql
Copy
SELECT p.*
FROM Products p
WHERE NOT EXISTS (
SELECT *
FROM Customers c
WHERE NOT EXISTS (
SELECT *
FROM Orders o
WHERE o.customer_id = c.id
AND o.product_id = p.id
)
);
8. Question:
Retrieve the names of customers who have placed orders for
both product ID 2 and product ID 4 but have not ordered
product ID 6.
Answer:
sql
Copy
SELECT c.name
FROM Customers c
JOIN Orders o1 ON c.id = o1.customer_id
JOIN Orders o2 ON c.id = o2.customer_id
WHERE o1.product_id = 2 AND o2.product_id = 4
AND c.id NOT IN (
SELECT customer_id
FROM Orders
WHERE product_id = 6
);
9. Question:
Retrieve all products that have been ordered by at least two
different customers.
Answer:
sql
Copy
SELECT p.*
FROM Products p
JOIN Orders o ON p.id = o.product_id
GROUP BY p.id, p.name
HAVING COUNT(DISTINCT o.customer_id) >= 2;
10. Question:
Retrieve the names of customers who have placed orders for
every available product.
Answer:
sql
Copy
SELECT c.name
FROM Customers c
WHERE NOT EXISTS (
SELECT *
FROM Products p
WHERE NOT EXISTS (
SELECT *
FROM Orders o
WHERE o.customer_id = c.id
AND o.product_id = p.id
)
);
Question 1:
Given a table "Employees" with columns "EmployeeID" and "Salary",
write a query to display the employee's ID and a column called
"SalaryStatus" that shows "High" if the salary is greater than 5000,
"Medium" if it is between 3000 and 5000, and "Low" if it is less than
3000.
Answer:
sql
Copy
SELECT EmployeeID,
CASE
WHEN Salary > 5000 THEN 'High'
WHEN Salary BETWEEN 3000 AND 5000 THEN 'Medium'
ELSE 'Low'
END AS SalaryStatus
FROM Employees;
Question 2:
Given a table "Customers" with columns "CustomerID", "FirstName",
and "LastName", write a query to display the customer's ID and a
column called "FullName" that concatenates the first name and last
name with a space in between.
Answer:
sql
Copy
SELECT CustomerID,
CONCAT(FirstName, ' ', LastName) AS FullName
FROM Customers;
Question 3:
Given a table "Orders" with columns "OrderID", "OrderDate", and
"Status", write a query to display the order's ID and a column called
"OrderStatus" that shows "Completed" if the status is 'C', "Pending"
if it is 'P', and "Cancelled" if it is 'X'.
Answer:
sql
Copy
SELECT OrderID,
CASE Status
WHEN 'C' THEN 'Completed'
WHEN 'P' THEN 'Pending'
WHEN 'X' THEN 'Cancelled'
END AS OrderStatus
FROM Orders;
Question 4:
Given a table "Students" with columns "StudentID", "FirstName",
"LastName", and "Grade", write a query to display the student's ID
and a column called "Result" that shows 'Pass' if the grade is greater
than or equal to 70, and 'Fail' if it is less than 70.
Answer:
sql
Copy
SELECT StudentID,
CASE
WHEN Grade >= 70 THEN 'Pass'
ELSE 'Fail'
END AS Result
FROM Students;
Question 5:
Given a table "Products" with columns "ProductID", "ProductName",
and "UnitsInStock", write a query to display the product's ID and a
column called "StockStatus" that shows 'In Stock' if the units in
stock are greater than 0, and 'Out of Stock' otherwise.
Answer:
sql
Copy
SELECT ProductID,
CASE
WHEN UnitsInStock > 0 THEN 'In Stock'
ELSE 'Out of Stock'
END AS StockStatus
FROM Products;
Question 6:
Given a table "Employees" with columns "EmployeeID", "FirstName",
"LastName", and "HireDate", write a query to display the employee's
ID and a column called "EmploymentStatus" that shows 'Current' if
the hire date is less than or equal to today's date, and 'Former'
otherwise.
Answer:
sql
Copy
SELECT EmployeeID,
CASE
WHEN HireDate <= CURDATE() THEN 'Current'
ELSE 'Former'
END AS EmploymentStatus
FROM Employees;
Question 7:
Given a table "Orders" with columns "OrderID", "OrderDate", and
"TotalAmount", write a query to display the order's ID and a column
called "DiscountedAmount" that shows the total amount minus 10%
if the order date is before a specific date (e.g., '2022-01-01'), and
the total amount otherwise.
Answer:
sql
Copy
SELECT OrderID,
CASE
WHEN OrderDate < '2022-01-01' THEN TotalAmount - (TotalAmount *
0.1)
ELSE TotalAmount
END AS DiscountedAmount
FROM Orders;
Question 8:
Given a table "Employees" with columns "EmployeeID", "FirstName",
"LastName", and "Age", write a query to display the employee's ID
and a column called "Category" that shows 'Junior' if the age is less
than 30, 'Senior' if it is between 30 and 50, and 'Executive' if it is
greater than 50.
Answer:
sql
Copy
SELECT EmployeeID,
CASE
WHEN Age < 30 THEN 'Junior'
WHEN Age BETWEEN 30 AND 50 THEN 'Senior'
ELSE 'Executive'
END AS Category
FROM Employees;
Question 9:
Given a table "Products" with columns "ProductID", "ProductName",
and "Price", write a query to display the product's ID and a column
called "PriceStatus" that shows 'Expensive' if the price is greater
than 100, 'Affordable' if it is between 50 and 100Sure! Here are 10
difficult SQL questions with answers that utilize the CASE statement:
Question 1:
Given a table "Employees" with columns "EmployeeID" and "Salary",
write a query to display the employee's ID and a column called
"SalaryStatus" that shows "High" if the salary is greater than 5000,
"Medium" if it is between 3000 and 5000, and "Low" if it is less than
3000.
Answer:
sql
Copy
SELECT EmployeeID,
CASE
WHEN Salary > 5000 THEN 'High'
WHEN Salary BETWEEN 3000 AND 5000 THEN 'Medium'
ELSE 'Low'
END AS SalaryStatus
FROM Employees;
Question 2:
Given a table "Customers" with columns "CustomerID", "FirstName",
and "LastName", write a query to display the customer's ID and a
column called "FullName" that concatenates the first name and last
name with a space in between.
Answer:
sql
Copy
SELECT CustomerID,
CONCAT(FirstName, ' ', LastName) AS FullName
FROM Customers;
Question 3:
Given a table "Orders" with columns "OrderID", "OrderDate", and
"Status", write a query to display the order's ID and a column called
"OrderStatus" that shows "Completed" if the status is 'C', "Pending"
if it is 'P', and "Cancelled" if it is 'X'.
Answer:
sql
Copy
SELECT OrderID,
CASE Status
WHEN 'C' THEN 'Completed'
WHEN 'P' THEN 'Pending'
WHEN 'X' THEN 'Cancelled'
END AS OrderStatus
FROM Orders;
Question 4:
Given a table "Students" with columns "StudentID", "FirstName",
"LastName", and "Grade", write a query to display the student's ID
and a column called "Result" that shows 'Pass' if the grade is greater
than or equal to 70, and 'Fail' if it is less than 70.
Answer:
sql
Copy
SELECT StudentID,
CASE
WHEN Grade >= 70 THEN 'Pass'
ELSE 'Fail'
END AS Result
FROM Students;
Question 5:
Given a table "Products" with columns "ProductID", "ProductName",
and "UnitsInStock", write a query to display the product's ID and a
column called "StockStatus" that shows 'In Stock' if the units in
stock are greater than 0, and 'Out of Stock' otherwise.
Answer:
sql
Copy
SELECT ProductID,
CASE
WHEN UnitsInStock > 0 THEN 'In Stock'
ELSE 'Out of Stock'
END AS StockStatus
FROM Products;
Question 6:
Given a table "Employees" with columns "EmployeeID", "FirstName",
"LastName", and "HireDate", write a query to display the employee's
ID and a column called "EmploymentStatus" that shows 'Current' if
the hire date is less than or equal to today's date, and 'Former'
otherwise.
Answer:
sql
Copy
SELECT EmployeeID,
CASE
WHEN HireDate <= CURDATE() THEN 'Current'
ELSE 'Former'
END AS EmploymentStatus
FROM Employees;
Question 7:
Given a table "Orders" with columns "OrderID", "OrderDate", and
"TotalAmount", write a query to display the order's ID and a column
called "DiscountedAmount" that shows the total amount minus 10%
if the order date is before a specific date (e.g., '2022-01-01'), and
the total amount otherwise.
Answer:
sql
Copy
SELECT OrderID,
CASE
WHEN OrderDate < '2022-01-01' THEN TotalAmount - (TotalAmount *
0.1)
ELSE TotalAmount
END AS DiscountedAmount
FROM Orders;
Question 8:
Given a table "Employees" with columns "EmployeeID", "FirstName",
"LastName", and "Age", write a query to display the employee's ID
and a column called "Category" that shows 'Junior' if the age is less
than 30, 'Senior' if it is between 30 and 50, and 'Executive' if it is
greater than 50.
Answer:
sql
Copy
SELECT EmployeeID,
CASE
WHEN Age < 30 THEN 'Junior'
WHEN Age BETWEEN 30 AND 50 THEN 'Senior'
ELSE 'Executive'
END AS Category
FROM Employees;
Question 9:
Given a table "Products" with columns "ProductID", "ProductName",
and "Price", write a query to display the product's ID and a column
called "PriceStatus" that shows 'Expensive' if the price is greater
than 100, 'Affordable' if it is between 50 and 100
Question 1:
Write an SQL query to display the top 3 employees with the highest
salaries.
Answer:
sql
Copy
SELECT employee_name, salary
FROM (
SELECT employee_name, salary, RANK() OVER (ORDER BY salary DESC) AS rank
FROM employees
) AS ranked_employees
WHERE rank <= 3;
Question 2:
Write an SQL query to find the second lowest salary from the
"employees" table.
Answer:
sql
Copy
SELECT MIN(salary) AS second_lowest_salary
FROM (
SELECT salary, RANK() OVER (ORDER BY salary) AS rank
FROM employees
) AS ranked_employees
WHERE rank = 2;
Question 3:
Write an SQL query to calculate the average salary for each
department, along with the employee(s) with the highest salary in
that department.
Answer:
sql
Copy
SELECT department_id, AVG(salary) AS avg_salary, employee_name, salary
FROM (
SELECT department_id, employee_name, salary,
RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS
rank
FROM employees
) AS ranked_employees
WHERE rank = 1
GROUP BY department_id, employee_name, salary;
Question 4:
Write an SQL query to find the top 5 departments with the highest
average salary.
Answer:
sql
Copy
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
ORDER BY avg_salary DESC
FETCH FIRST 5 ROWS ONLY;
Question 5:
Write an SQL query to find the employee(s) with the second highest
salary in each department.
Answer:
sql
Copy
SELECT department_id, employee_name, salary
FROM (
SELECT department_id, employee_name, salary,
RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS
rank
FROM employees
) AS ranked_employees
WHERE rank = 2;
Question 6:
Write an SQL query to calculate the difference between the salary of
each employee and the average salary of their department.
Answer:
sql
Copy
SELECT employee_name, salary, department_id,
salary - AVG(salary) OVER (PARTITION BY department_id) AS
salary_difference
FROM employees;
Question 7:
Write an SQL query to find the employee(s) with the highest salary
in each department, excluding the department with ID 5.
Answer:
sql
Copy
SELECT department_id, employee_name, salary
FROM (
SELECT department_id, employee_name, salary,
RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS
rank
FROM employees
WHERE department_id <> 5
) AS ranked_employees
WHERE rank = 1;
Question 8:
Write an SQL query to calculate the cumulative salary for each
department, ordered by the employee's hire date.
Answer:
sql
Copy
SELECT department_id, employee_name, salary,
SUM(salary) OVER (PARTITION BY department_id ORDER BY hire_date) AS
cumulative_salary
FROM employees;
Question 9:
Write an SQL query to find the employee(s) who have the same
salary as the employee with ID 1001.
Answer:
sql
Copy
SELECT employee_name, salary
FROM employees
WHERE salary = (SELECT salary FROM employees WHERE employee_id = 1001);
Question 10:
Write an SQL query to calculate the difference between the salary of
each employee and the salary of the employee with the highest
salary in their department.
Answer:
sql
Copy
SELECT employee_name, salary, department_id,
salary - MAX(salary) OVER (PARTITION BY department_id) AS
salary_difference
FROM employees;
sql
Copy
SELECT employee_name, salary, DENSE_RANK() OVER (ORDER BY salary DESC)
AS rank
FROM employees
WHERE rank <= 3;
2. Question: Write an SQL query to find the second-highest salary
in each department.
Answer:
sql
Copy
SELECT department_id, MAX(salary) AS second_highest_salary
FROM (
SELECT department_id, salary, DENSE_RANK() OVER (PARTITION BY
department_id ORDER BY salary DESC) AS rank
FROM employees
) AS ranked_employees
WHERE rank = 2
GROUP BY department_id;
3. Question: Write an SQL query to calculate the average salary
for each department, including ties.
Answer:
sql
Copy
SELECT department_id, AVG(salary) AS average_salary
FROM employees
GROUP BY department_id
ORDER BY DENSE_RANK() OVER (ORDER BY AVG(salary) DESC);
4. Question: Write an SQL query to retrieve the employees with
the highest salary in each department, without ties.
Answer:
sql
Copy
SELECT department_id, employee_name, salary
FROM (
SELECT department_id, employee_name, salary, DENSE_RANK() OVER
(PARTITION BY department_id ORDER BY salary DESC) AS rank
FROM employees
) AS ranked_employees
WHERE rank = 1;
5. Question: Write an SQL query to find the top 5 departments
with the highest average salary, including ties.
Answer:
sql
Copy
SELECT department_id, AVG(salary) AS average_salary, DENSE_RANK() OVER
(ORDER BY AVG(salary) DESC) AS rank
FROM employees
GROUP BY department_id
HAVING rank <= 5;
6. Question: Write an SQL query to calculate the difference in
salary between each employee and the employee with the
highest salary.
Answer:
sql
Copy
SELECT employee_name, salary, (salary - MAX(salary) OVER ()) AS
salary_difference
FROM employees;
7. Question: Write an SQL query to find the employees with
salaries above the average salary in their respective
departments.
Answer:
sql
Copy
SELECT employee_name, salary, department_id
FROM (
SELECT employee_name, salary, department_id, AVG(salary) OVER
(PARTITION BY department_id) AS avg_salary
FROM employees
) AS avg_salaries
WHERE salary > avg_salary;
8. Question: Write an SQL query to retrieve the employees with
the highest salary, without ties.
Answer:
sql
Copy
SELECT employee_name, salary
FROM (
SELECT employee_name, salary, DENSE_RANK() OVER (ORDER BY salary
DESC) AS rank
FROM employees
) AS ranked_employees
WHERE rank = 1;
9. Question: Write an SQL query to calculate the cumulative
salary for each department, ordered by department and salary.
Answer:
sql
Copy
SELECT department_id, employee_name, salary, SUM(salary) OVER
(PARTITION BY department_id ORDER BY salary) AS cumulative_salary
FROM employees
ORDER BY department_id, salary;
10. Question: Write an SQL query to find the employees with
salaries in the top 10% of the salary range.
Answer:
sql
Copy
SELECT employee_name, salary
FROM (
SELECT employee_name, salary, NTILE(10) OVER (ORDER BY salary DESC)
AS ntile
FROM employees
) AS sal_ntile
WHERE ntile = 1;
1. Question:
Find the names of customers who have made at least two
purchases.
Answer:
sql
Copy
SELECT name
FROM customers
WHERE customer_id IN (
SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING COUNT(*) >= 2
);
2. Question:
Display the product names and their corresponding categories
for products that are currently out of stock.
Answer:
sql
Copy
SELECT product_name, category
FROM products
WHERE product_id IN (
SELECT product_id
FROM inventory
WHERE quantity = 0
);
3. Question:
Find the names of employees who have a higher salary than
their manager.
Answer:
sql
Copy
SELECT e.name
FROM employees e
WHERE salary > (
SELECT salary
FROM employees
WHERE employee_id = e.manager_id
);
4. Question:
Display the order IDs and total amounts for orders that have a
higher total amount than the average order amount.
Answer:
sql
Copy
SELECT order_id, total_amount
FROM orders
WHERE total_amount > (
SELECT AVG(total_amount)
FROM orders
);
5. Question:
Find the customer names who have made a purchase in all
available categories.
Answer:
sql
Copy
SELECT name
FROM customers
WHERE NOT EXISTS (
SELECT category
FROM categories
WHERE category NOT IN (
SELECT DISTINCT category
FROM orders o
JOIN products p ON o.product_id = p.product_id
WHERE o.customer_id = customers.customer_id
)
);
6. Question:
Display the product names that have been ordered by all
customers.
Answer:
sql
Copy
SELECT product_name
FROM products
WHERE NOT EXISTS (
SELECT customer_id
FROM customers
WHERE customer_id NOT IN (
SELECT customer_id
FROM orders
WHERE product_id = products.product_id
)
);
7. Question:
Find the employees who have the same job title and
department as their manager.
Answer:
sql
Copy
SELECT e.name
FROM employees e
WHERE job_title = (
SELECT job_title
FROM employees
WHERE employee_id = e.manager_id
) AND department = (
SELECT department
FROM employees
WHERE employee_id = e.manager_id
);
8. Question:
Display the order IDs and customer names for orders that have
a total amount greater than the sum of their previous orders.
Answer:
sql
Copy
SELECT o.order_id, c.name
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
WHERE total_amount > (
SELECT SUM(total_amount)
FROM orders
WHERE customer_id = o.customer_id AND order_id < o.order_id
);
9. Question:
Find the names of customers who have not made any
purchases.
Answer:
sql
Copy
SELECT name
FROM customers
WHERE customer_id NOT IN (
SELECT customer_id
FROM orders
);
10. Question:
Display the product names and their corresponding categories
for products that have not been ordered.
Answer:
sql
Copy
SELECT product_name, category
FROM products
WHERE product_id NOT IN (
SELECT product_id
FROM orders
);
sql
Copy
SELECT LENGTH(sentence) - LENGTH(REPLACE(sentence, ' ', '')) + 1 AS
word_count
FROM your_table;
2. Question: How can you count the number of words in a
sentence, excluding any punctuation marks?
Answer:
sql
Copy
SELECT LENGTH(REGEXP_REPLACE(sentence, '[[:punct:]]', '')) -
LENGTH(REGEXP_REPLACE(sentence, '[[:punct:]]', ' ')) + 1 AS word_count
FROM your_table;
3. Question: Can you count the number of words in each sentence
of a given column and display the results?
Answer:
sql
Copy
SELECT sentence, LENGTH(sentence) - LENGTH(REPLACE(sentence, ' ', ''))
+ 1 AS word_count
FROM your_table;
4. Question: How do you count the number of unique words in a
sentence?
Answer:
sql
Copy
SELECT COUNT(DISTINCT word) AS unique_word_count
FROM (
SELECT REGEXP_SPLIT_TO_TABLE(sentence, ' ') AS word
FROM your_table
) subquery;
5. Question: Write an SQL query to find the sentences with the
maximum number of words.
Answer:
sql
Copy
SELECT sentence, LENGTH(sentence) - LENGTH(REPLACE(sentence, ' ', ''))
+ 1 AS word_count
FROM your_table
WHERE LENGTH(sentence) - LENGTH(REPLACE(sentence, ' ', '')) + 1 = (
SELECT MAX(LENGTH(sentence) - LENGTH(REPLACE(sentence, ' ', '')) + 1)
FROM your_table
);
6. Question: How can you count the number of sentences that
have more than five words?
Answer:
sql
Copy
SELECT COUNT(*) AS sentence_count
FROM your_table
WHERE LENGTH(sentence) - LENGTH(REPLACE(sentence, ' ', '')) + 1 > 5;
7. Question: Write an SQL query to find the average number of
words per sentence in a column.
Answer:
sql
Copy
SELECT AVG(LENGTH(sentence) - LENGTH(REPLACE(sentence, ' ', '')) + 1)
AS average_word_count
FROM your_table;
8. Question: How do you count the number of sentences that
contain a specific word?
Answer:
sql
Copy
SELECT COUNT(*) AS sentence_count
FROM your_table
WHERE LOWER(sentence) LIKE '%' || LOWER('your_word') || '%';
9. Question: Can you find the sentences with the highest and
lowest number of words?
Answer:
sql
Copy
SELECT sentence, LENGTH(sentence) - LENGTH(REPLACE(sentence, ' ', ''))
+ 1 AS word_count
FROM your_table
ORDER BY word_count DESC
LIMIT 1;
sql
Copy
SELECT COUNT(*) AS sentence_count
FROM your_table
WHERE LOWER(sentence) LIKE LOWER('your_word') || ' %';
1. Question:
Write a SQL query to retrieve all records where the date is in
the format 'YYYY-MM-DD'.
Answer:
SELECT * FROM table_name WHERE date_column LIKE '____--';
2. Question:
Write a SQL query to calculate the age of each person in years
based on their birthdate.
Answer:
SELECT name, DATEDIFF(CURDATE(), birthdate) / 365 AS age FROM
table_name;
3. Question:
Write a SQL query to find all records where the date is in the
format 'DD/MM/YYYY'.
Answer:
SELECT * FROM table_name WHERE date_column REGEXP '^[0-9]
{2}/[0-9]{2}/[0-9]{4}$';
4. Question:
Write a SQL query to retrieve all records where the date is in
the format 'Month DD, YYYY'.
Answer:
SELECT * FROM table_name WHERE DATE_FORMAT(date_column,
'%M %d, %Y') = 'June 15, 2022';
5. Question:
Write a SQL query to retrieve all records where the date is in
the format 'DDth Month, YYYY'.
Answer:
SELECT * FROM table_name WHERE DATE_FORMAT(date_column,
'%D %M, %Y') = '25th December, 2022';
6. Question:
Write a SQL query to calculate the total number of days
between two dates.
Answer:
SELECT DATEDIFF(end_date, start_date) AS total_days FROM
table_name;
7. Question:
Write a SQL query to retrieve all records where the date is in
the format 'MM/DD/YY'.
Answer:
SELECT * FROM table_name WHERE date_column LIKE '//__';
8. Question:
Write a SQL query to retrieve all records where the date is in
the format 'YYYY-MM-DD HH:MM:SS'.
Answer:
SELECT * FROM table_name WHERE date_column LIKE '____-- ::__';
9. Question:
Write a SQL query to find all records where the date is in the
format 'Day, Month DD, YYYY'.
Answer:
SELECT * FROM table_name WHERE DATE_FORMAT(date_column,
'%W, %M %d, %Y') = 'Monday, July 04, 2022';
10. Question:
Write a SQL query to retrieve all records where the date is in
the format 'YYMMDD'.
Answer:
SELECT * FROM table_name WHERE date_column REGEXP '^[0-9]
{6}$';
1. Question: Write a SQL query to extract the first name and last
name from a full name column.
Answer:
sql
Copy
SELECT SUBSTRING_INDEX(full_name, ' ', 1) AS first_name,
SUBSTRING_INDEX(full_name, ' ', -1) AS last_name
FROM table_name;
2. Question: Write a SQL query to concatenate two columns and
remove any leading or trailing spaces.
Answer:
sql
Copy
SELECT TRIM(column1 || ' ' || column2) AS concatenated_columns
FROM table_name;
3. Question: Write a SQL query to extract the middle character(s)
from a string.
Answer:
sql
Copy
SELECT SUBSTRING(column_name, (LENGTH(column_name) + 1) / 2, 1) AS
middle_character
FROM table_name;
4. Question: Write a SQL query to replace all occurrences of a
specific substring within a column.
Answer:
sql
Copy
SELECT REPLACE(column_name, 'substring_to_replace', 'replacement_string') AS
modified_column
FROM table_name;
5. Question: Write a SQL query to extract only the numeric
characters from a string.
Answer:
sql
Copy
SELECT REGEXP_REPLACE(column_name, '[^0-9]', '') AS numeric_characters
FROM table_name;
6. Question: Write a SQL query to reverse a string.
Answer:
sql
Copy
SELECT REVERSE(column_name) AS reversed_string
FROM table_name;
7. Question: Write a SQL query to count the occurrences of a
specific character within a string.
Answer:
sql
Copy
SELECT LENGTH(column_name) - LENGTH(REPLACE(column_name,
'character_to_count', '')) AS occurrence_count
FROM table_name;
8. Question: Write a SQL query to capitalize the first letter of each
word in a string.
Answer:
sql
Copy
SELECT CONCAT(UPPER(SUBSTRING(column_name, 1, 1)),
LOWER(SUBSTRING(column_name, 2))) AS capitalized_string
FROM table_name;
9. Question: Write a SQL query to find the longest word in a string
column.
Answer:
sql
Copy
SELECT SUBSTRING_INDEX(column_name, ' ', LENGTH(column_name) -
LENGTH(REPLACE(column_name, ' ', '')) + 1) AS longest_word
FROM table_name
ORDER BY LENGTH(column_name) DESC
LIMIT 1;
10. Question: Write a SQL query to extract the domain name
from a URL column.
Answer:
sql
Copy
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(url_column, '/', 3), '//', -1) AS
domain_name
FROM table_name;