You are on page 1of 78

SQL Practice Questions Queries with Answers

SQL Practice Questions for Learning and Making


SQL strong

General instructions:
This document is created by keeping in mind that student can do more and
more practice in SQL concepts. So, please first install MySQL in your
laptop/computer.
◼ Create a Database.
◼ Then create the tables given in questions.
◼ Insert data given in questions.
◼ Read questions and try to write Query on your own.
◼ If needed, then only see the answer.

Author
Ritesh Kumar Sinha
https://www.careerswitchhelp.com
Follow on Instagram:
https://www.instagram.com/sql_interview_question

Follow me on Linkedin for Job assistance


https://www.linkedin.com/in/ritesh-sinha-35423960/

1
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

Table of Contents
• Practice Set 1 – Online Bookstore ……………………... 10 Question
• Practice Set 2 – Employee Management system …….... 10 Question
• Practice Set 3 – Retail store …………………….............. 20 Question
• Aggregate function ……………………………………… 20 Question
• Analytical Function ……………………………................. 20 Question
• Joins and subqueries ……………………………………. 20 Question
• STRING Functions ……………………………………….. 20 Question
• CASE Statements ………………………………………... 20 Question
• REGEX (Regular Expressions) …………………………… 20 Question
• DATE Function …………………………………………… 20 Question
• Numeric Functions ……………………………………….. 20 Question

2
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

Scenario 1- Practice Set 1 Online Bookstore

Here's a case study with questions and answers that can be solved using
MySQL:
Consider an online bookstore that sells books to customers. The bookstore
maintains a database with the following tables:

Table: books
Columns:
- book_id (int, primary key)
- title (varchar)
- author (varchar)
- price (decimal)

Table: customers
Columns:
- customer_id (int, primary key)
- name (varchar)
- email (varchar)
- address (varchar)

3
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

Table: orders
Columns:
- order_id (int, primary key)
- customer_id (int, foreign key referencing customers.customer_id)
- book_id (int, foreign key referencing books.book_id)
- quantity (int)
- order_date (date)

Table: payments
Columns:
- payment_id (int, primary key)
- order_id (int, foreign key referencing orders.order_id)
- payment_date (date)
- amount (decimal)

Statement to create above tables:


CREATE TABLE books (
book_id INT PRIMARY KEY,
title VARCHAR(255),
author VARCHAR(255),
price DECIMAL(10, 2)
);
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
name VARCHAR(255),
email VARCHAR(255),
address VARCHAR(255)

4
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

);
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
book_id INT,
quantity INT,
order_date DATE,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id),
FOREIGN KEY (book_id) REFERENCES books(book_id)
);
CREATE TABLE payments (
payment_id INT PRIMARY KEY,
order_id INT,
payment_date DATE,
amount DECIMAL(10, 2),
FOREIGN KEY (order_id) REFERENCES orders(order_id)
);

INSERT data into above tables:

INSERT INTO books (book_id, title, author, price)


VALUES (1, 'Book 1', 'Author 1', 10.99),
(2, 'Book 2', 'Author 2', 12.99),
(3, 'Book 3', 'Author 3', 9.99),
(4, 'Book 4', 'Author 4', 15.99),
(5, 'Book 5', 'Author 5', 8.99);

INSERT INTO customers (customer_id, name, email, address)


VALUES (1, 'Customer 1', 'customer1@example.com', 'Address 1'),
(2, 'Customer 2', 'customer2@example.com', 'Address 2'),

5
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

(3, 'Customer 3', 'customer3@example.com', 'Address 3'),


(4, 'Customer 4', 'customer4@example.com', 'Address 4'),
(5, 'Customer 5', 'customer5@example.com', 'Address 5');

INSERT INTO orders (order_id, customer_id, book_id, quantity,


order_date)
VALUES (1, 1, 1, 2, '2023-06-01'),
(2, 2, 3, 1, '2023-06-02'),
(3, 3, 2, 3, '2023-06-03'),
(4, 4, 4, 2, '2023-06-04'),
(5, 5, 5, 1, '2023-06-05');

INSERT INTO payments (payment_id, order_id, payment_date, amount)


VALUES (1, 1, '2023-06-02', 21.98),
(2, 2, '2023-06-03', 9.99),
(3, 3, '2023-06-04', 38.97),
(4, 4, '2023-06-05', 31.98),
(5, 5, '2023-06-06', 8.99);

You can commit the data now.

Now, let's proceed with the questions and their corresponding SQL queries:

Question 1: Retrieve the details of all customers.


SELECT * FROM customers;

Question 2: Retrieve the titles and authors of all books.


SELECT title, author FROM books;

6
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

Question 3: Retrieve the total number of books sold.


SELECT SUM(quantity) AS total_books_sold FROM orders;

Question 4: Retrieve the customers who have placed orders.


SELECT DISTINCT customers.customer_id, customers.name
FROM customers
JOIN orders ON customers.customer_id = orders.customer_id;

Question 5: Retrieve the total revenue generated from book sales.


SELECT SUM(orders.quantity * books.price) AS total_revenue
FROM orders
JOIN books ON orders.book_id = books.book_id;

Question 6: Retrieve the customer who has made the highest payment.
SELECT customers.customer_id, customers.name,
MAX(payments.amount) AS highest_payment
FROM customers
JOIN orders ON customers.customer_id = orders.customer_id
JOIN payments ON orders.order_id = payments.order_id;

Question 7: Retrieve the book with the highest price.


SELECT * FROM books
WHERE price = (SELECT MAX(price) FROM books);

Question 8: Retrieve the number of books sold for each customer.


SELECT customers.name, SUM(orders.quantity) AS total_books_sold
FROM customers
JOIN orders ON customers.customer_id = orders.customer_id
GROUP BY customers.name;

7
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

Question 9: Retrieve the customer who has made the most orders.
SELECT customers.customer_id, customers.name,
COUNT(orders.order_id) AS order_count
FROM customers
JOIN orders ON customers.customer_id = orders.customer_id
GROUP BY customers.customer_id
ORDER BY order_count DESC
LIMIT 1;

Question 10: Retrieve the customers who have not placed any orders.
SELECT customers.customer_id, customers.name
FROM customers
LEFT JOIN orders ON customers.customer_id = orders.customer_id
WHERE orders.order_id IS NULL;

These are just a few examples of the kinds of queries you can perform on the
given database schema. Depending on your specific requirements, you can
create more complex queries to extract meaningful insights from the data.

8
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

Scenario 2- Practice Set 2 Employee Management System


Consider an Employee Management System that stores information about
employees in a company. The database includes the following tables:

Table: employees
Columns:
- employee_id (int, primary key)
- first_name (varchar)
- last_name (varchar)
- department_id (int, foreign key referencing departments.department_id)
- salary (decimal)

Table: departments
Columns:
- department_id (int, primary key)
- department_name (varchar)

CREATE table statements:


CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
department_id INT,
salary DECIMAL(10,2),
FOREIGN KEY (department_id) REFERENCES
departments(department_id)
);

9
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

CREATE TABLE departments (


department_id INT PRIMARY KEY,
department_name VARCHAR(50)
);

Insert sample data into the table and commit:

INSERT INTO employees (employee_id, first_name, last_name,


department_id, salary) VALUES
(1, 'John', 'Doe', 1, 50000),
(2, 'Jane', 'Smith', 2, 60000),
(3, 'Bob', 'Johnson', 1, 55000),
(4, 'Alice', 'Williams', 2, 65000);

INSERT INTO departments (department_id, department_name) VALUES


(1, 'Sales'),
(2, 'Marketing');

Now, let's proceed with the questions and their corresponding SQL queries,
using a sample dataset:

Question 1: Retrieve the details of all employees.


SELECT * FROM employees;

Question 2: Retrieve the names and departments of all employees.


SELECT employees.first_name, employees.last_name,
departments.department_name
FROM employees

10
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

JOIN departments ON employees.department_id =


departments.department_id;

Question 3: Retrieve the total number of employees in each department.


SELECT departments.department_name, COUNT(employees.employee_id)
AS total_employees
FROM departments
LEFT JOIN employees ON departments.department_id =
employees.department_id
GROUP BY departments.department_name;

Question 4: Retrieve the highest salary among all employees.


SELECT MAX(salary) AS highest_salary FROM employees;

Question 5: Retrieve the employees who earn a salary higher than 55000.
SELECT * FROM employees WHERE salary > 55000;

Question 6: Retrieve the average salary in each department.


SELECT departments.department_name, AVG(employees.salary) AS
average_salary
FROM departments
LEFT JOIN employees ON departments.department_id =
employees.department_id
GROUP BY departments.department_name;

Question 7: Retrieve the employees who belong to the Sales department.


SELECT employees.first_name, employees.last_name
FROM employees

11
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

JOIN departments ON employees.department_id =


departments.department_id
WHERE departments.department_name = 'Sales';

Question 8: Retrieve the total salary expenditure for each department.


SELECT departments.department_name, SUM(employees.salary) AS
total_salary_expenditure
FROM departments
LEFT JOIN employees ON departments.department_id =
employees.department_id
GROUP BY departments.department_name;

Question 9: Retrieve the department with the highest total salary expenditure.
SELECT departments.department_name, SUM(employees.salary) AS
total_salary_expenditure
FROM departments
JOIN employees ON departments.department_id =
employees.department_id
GROUP BY departments.department_name
ORDER BY total_salary_expenditure DESC
LIMIT 1;

Question 10: Retrieve the employees with the highest salary in each
department.
SELECT employees.first_name, employees.last_name,
departments.department_name, employees.salary
FROM employees
JOIN departments ON employees.department_id =
departments.department_id
WHERE (employees.department_id, employees.salary) IN (
SELECT department_id, MAX(salary)

12
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

FROM employees
GROUP BY department;

13
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

Scenario 3- Practice Set 3 Retail Store Management


Consider a retail store that sells products to customers. The database
includes the following tables:

Table: products
Columns:
- product_id (int, primary key)
- product_name (varchar)
- category_id (int, foreign key referencing categories.category_id)
- price (decimal)

Table: categories
Columns:
- category_id (int, primary key)
- category_name (varchar)

Table: customers
Columns:
- customer_id (int, primary key)
- customer_name (varchar)
- email (varchar)
- address (varchar)

Table: orders
Columns:
- order_id (int, primary key)

14
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

- customer_id (int, foreign key referencing customers.customer_id)


- product_id (int, foreign key referencing products.product_id)
- quantity (int)
- order_date (date)

Table: payments
Columns:
- payment_id (int, primary key)
- order_id (int, foreign key referencing orders.order_id)
- payment_date (date)
- amount (decimal)

CREATE TABLE statements:

Table: products
CREATE TABLE products (
product_id INT PRIMARY KEY,
product_name VARCHAR(50),
category_id INT,
price DECIMAL(10,2),
FOREIGN KEY (category_id) REFERENCES categories(category_id)
);

Table: categories

CREATE TABLE categories (


category_id INT PRIMARY KEY,

15
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

category_name VARCHAR(50)
);

Table: customers
CREATE TABLE customers (
customer_id INT PRIMARY
KEY,
customer_name VARCHAR(50),
email VARCHAR(100),
address VARCHAR(100)
);

Table: orders
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
product_id INT,
quantity INT,
order_date DATE,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id),
FOREIGN KEY (product_id) REFERENCES products(product_id)
);

Table: payments
CREATE TABLE payments (
payment_id INT PRIMARY KEY,
order_id INT,
payment_date DATE,

16
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

amount DECIMAL(10,2),
FOREIGN KEY (order_id) REFERENCES orders(order_id)
);

INSERT statements for the sample dataset:

Table: products
INSERT INTO products (product_id, product_name, category_id,
price) VALUES
(1, 'Laptop', 1, 1000),
(2, 'Smartphone', 2, 800),
(3, 'TV', 3, 1200),
(4, 'Camera', 4, 500);

Table: categories
INSERT INTO categories (category_id, category_name) VALUES
(1, 'Electronics'),
(2, 'Mobile'),
(3, 'Appliances'),
(4, 'Cameras');

Table: customers
INSERT INTO customers (customer_id, customer_name, email,
address) VALUES
(1, 'John Doe', 'johndoe@example.com', '123 Main St'),
(2, 'Jane Smith', 'janesmith@example.com', '456 Elm St'),
(3, 'Bob Johnson', 'bobjohnson@example.com', '789 Oak St');

17
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

Table: orders
INSERT INTO orders (order_id, customer_id, product_id, quantity,
order_date) VALUES
(1, 1, 2, 2, '2023-05-01'),
(2, 2, 1, 1, '2023-05-02'),
(3, 3, 3, 3, '2023-05-03');

Table: payments
INSERT INTO payments (payment_id, order_id, payment_date,
amount) VALUES
(1, 1, '2023-05-02', 1600),
(2, 2, '2023-05-03', 1000),
(3, 3, '2023-05-04', 3600);

Here are 20 questions and their corresponding answers based on the


provided retail store case study:

Question 1: Retrieve the details of all products.


SELECT * FROM products;

Question 2: Retrieve the names and categories of all products.


SELECT products.product_name, categories.category_name
FROM products
JOIN categories ON products.category_id =
categories.category_id;

18
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

Question 3: Retrieve the total number of products in each category.


SELECT categories.category_name, COUNT(products.product_id) AS
total_products
FROM categories
LEFT JOIN products ON categories.category_id =
products.category_id
GROUP BY categories.category_name;

Question 4: Retrieve the highest price among all products.


SELECT MAX(price) AS highest_price FROM products;

Question 5: Retrieve the products with a price higher than 1000.


SELECT * FROM products WHERE price > 1000;

Question 6: Retrieve the average price in each category.


SELECT categories.category_name, AVG(products.price) AS
average_price
FROM categories
LEFT JOIN products ON categories.category_id =
products.category_id
GROUP BY categories.category_name;

Question 7: Retrieve the products in the Electronics category.


SELECT products.product_name, products.price
FROM products
JOIN categories ON products.category_id = categories.category_id
WHERE categories.category_name = 'Electronics';

19
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

Question 8: Retrieve the total price spent by each customer.


SELECT customers.customer_name, SUM(orders.quantity *
products.price) AS total_price_spent
FROM customers
JOIN orders ON customers.customer_id = orders.customer_id
JOIN products ON orders.product_id = products.product_id
GROUP BY customers.customer_name;

Question 9: Retrieve the customer who has spent the most.


SELECT customers.customer_name, SUM(orders.quantity *
products.price) AS total_spent
FROM customers
JOIN orders ON customers.customer_id = orders.customer_id
JOIN products ON orders.product_id = products.product_id
GROUP BY customers.customer_name
ORDER BY total_spent DESC
LIMIT 1;

Question 10: Retrieve the products with the highest price in each category.
SELECT products.product_name, products.price,
categories.category_name
FROM products
JOIN categories ON products.category_id = categories.category_id
WHERE (products.category_id, products.price) IN (
SELECT category_id, MAX(price)
FROM products
GROUP BY category_id
);

20
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

Question 11: Retrieve the total revenue generated from sales.


SELECT SUM(orders.quantity * products.price) AS total_revenue
FROM orders
JOIN products ON orders.product_id = products.product_id;

Question 12: Retrieve the orders placed by a specific customer.


SELECT orders.order_id, products.product_name, orders.quantity
FROM orders
JOIN products ON orders.product_id = products.product_id
WHERE orders.customer_id = <customer_id>;

(Note: Replace `<customer_id>` with the actual customer ID you want to


retrieve orders for.)

Question 13: Retrieve the customers who have placed orders for a specific
product.
SELECT customers.customer_name, orders.quantity
FROM customers
JOIN orders ON customers.customer_id = orders.customer_id
JOIN products ON orders.product_id = products.product_id
WHERE products.product_name = '<product_name>';

(Note: Replace `<product_name>` with the actual product name you want to
retrieve customers for.)

Question 14: Retrieve the average quantity of products sold.


SELECT AVG(quantity) AS average_quantity FROM orders;

21
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

Question 15: Retrieve the total number of customers.


SELECT COUNT(*) AS total_customers FROM customers;

Question 16: Retrieve the most popular category (with the highest number of
products sold).
SELECT categories.category_name, COUNT(orders.order_id) AS
total_orders
FROM categories
JOIN products ON categories.category_id = products.category_id
JOIN orders ON products.product_id = orders.product_id
GROUP BY categories.category_name
ORDER BY total_orders DESC
LIMIT 1;

Question 17: Retrieve the customer with the highest number of orders.
SELECT customers.customer_name, COUNT(orders.order_id) AS
total_orders
FROM customers
JOIN orders ON customers.customer_id = orders.customer_id
GROUP BY customers.customer_name
ORDER BY total_orders DESC
LIMIT 1;

Question 18: Retrieve the total amount paid for each order.
SELECT orders.order_id, SUM(payments.amount) AS
total_amount_paid
FROM orders
JOIN payments ON orders.order_id = payments.order_id

22
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

GROUP BY orders.order_id;

Question 19: Retrieve the orders that have not been paid yet.
SELECT orders.order_id, customers.customer_name
FROM orders
JOIN customers ON orders.customer_id = customers.customer_id
LEFT JOIN payments ON orders.order_id = payments.order_id
WHERE payments.payment_id IS NULL;

Question 20: Retrieve the average payment amount.


SELECT AVG(amount) AS average_payment_amount FROM payments;

Feel free to replace the placeholders (`<customer_id>`, `<product_name>`)


with the actual values you want to query.

23
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

1. Function Based Query writing (Aggregate functions)


Here are 20 queries and their corresponding answers based on aggregate
functions in MySQL:
As you have created tables and inserted data into tables in previous sections.
So now, I am expecting you to write create table statement for the tables in
these sections, also write insert statement to insert data as given in the
sample data.

Table: orders

| order_id | customer_id | product_id | quantity |


|----------|-------------|------------|----------|
| 1 | 1 | 2 | 2 |
| 2 | 2 | 1 | 1 |
| 3 | 3 | 3 | 3 |
| 4 | 1 | 1 | 4 |
| 5 | 3 | 2 | 2 |
| 6 | 2 | 3 | 1 |

Table: products

| product_id | product_name | price |


|------------|--------------|-------|
| 1 | Laptop | 1000 |
| 2 | Smartphone | 800 |
| 3 | TV | 1200 |

Question 1: What is the total quantity of products ordered?

24
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

SELECT SUM(quantity) AS total_quantity


FROM orders;
Answer: The total quantity of products ordered is 13.

Question 2: What is the average quantity of products ordered per order?


SELECT AVG(quantity) AS average_quantity
FROM orders;
Answer: The average quantity of products ordered per order is
2.1667.

Question 3: What is the maximum quantity of products ordered?


SELECT MAX(quantity) AS max_quantity
FROM orders;
Answer: The maximum quantity of products ordered is 4.

Question 4: What is the minimum quantity of products ordered?


SELECT MIN(quantity) AS min_quantity
FROM orders;
Answer: The minimum quantity of products ordered is 1.

Question 5: How many orders have been placed?


SELECT COUNT(order_id) AS total_orders
FROM orders;
Answer: There have been 6 orders placed.

Question 6: What is the total price of products ordered?


SELECT SUM(orders.quantity * products.price) AS total_price
FROM orders

25
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

JOIN products ON orders.product_id = products.product_id;


Answer: The total price of products ordered is 14200.

Question 7: What is the average price of products?


SELECT AVG(price) AS average_price
FROM products;
Answer: The average price of products is 1000.

Question 8: What is the maximum price of a product?


SELECT MAX(price) AS max_price
FROM products;
Answer: The maximum price of a product is 1200.

Question 9: What is the minimum price of a product?


SELECT MIN(price) AS min_price
FROM products;
Answer: The minimum price of a product is 800.

Question 10: How many customers have placed orders?


SELECT COUNT(DISTINCT customer_id) AS total_customers
FROM orders;
Answer: There are 3 customers who have placed orders.

Question 11: What is the total quantity of each product ordered?


SELECT product_name, SUM(quantity) AS total_quantity
FROM orders
JOIN products ON orders.product_id = products.product_id
GROUP BY product_name;

26
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

Answer:
| product_name | total_quantity |
|--------------|----------------|
| Laptop | 5 |
| Smartphone | 4 |
| TV | 4 |

Question 12: What is the average quantity of each product ordered?


SELECT product_name, AVG(quantity) AS average_quantity
FROM orders
JOIN products ON orders.product_id = products.product_id
GROUP BY product_name;

Answer:
| product_name | average_quantity |
|--------------|------------------|
| Laptop | 2.5 |
| Smartphone | 2 |
| TV | 2 |

Question 13: What is the total price of products ordered by each customer?
SELECT customer_id, SUM(orders.quantity * products.price) AS
total_price
FROM orders
JOIN products ON orders.product_id = products.product_id
GROUP BY customer_id;
Answer:
| customer_id | total_price |

27
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

|-------------|-------------|
| 1 | 6800 |
| 2 | 3200 |
| 3 | 4200 |

Question 14: What is the average price of products ordered by each


customer?
SELECT customer_id, AVG(products.price) AS average_price
FROM orders
JOIN products ON orders.product_id = products.product_id
GROUP BY customer_id;
Answer:
| customer_id | average_price |
|-------------|---------------|
| 1 | 900 |
| 2 | 1000 |
| 3 | 1400 |

Question 15: What is the maximum quantity of products ordered by each


customer?
SELECT customer_id, MAX(quantity) AS max_quantity
FROM orders
GROUP BY customer_id;
Answer:
| customer_id | max_quantity |
|-------------|--------------|
| 1 | 4 |
| 2 | 1 |
| 3 | 3 |

28
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

Question 16: What is the minimum quantity of products ordered by each


customer?
SELECT customer_id, MIN(quantity) AS min_quantity
FROM orders
GROUP BY customer_id;
Answer:
| customer_id | min_quantity |
|-------------|--------------|
| 1 | 2 |
| 2 | 1 |
| 3 | 2 |

Question 17: What is the total quantity of products ordered per customer?
SELECT customer_id, SUM(quantity) AS total_quantity
FROM orders
GROUP BY customer_id;
Answer:
| customer_id | total_quantity |
|-------------|----------------|
| 1 | 6 |
| 2 | 2 |
| 3 | 5 |

Question 18: What is the average price of products ordered per customer?
SELECT customer_id, AVG(products.price) AS average_price

29
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

FROM orders
JOIN products ON orders.product_id = products.product_id
GROUP BY customer_id;
Answer:
| customer_id | average_price |
|-------------|---------------|
| 1 | 1133.3333 |
| 2 | 900 |
| 3 | 1000 |

Question 19: What is the total revenue generated from sales?


SELECT SUM(orders.quantity * products.price) AS total_revenue
FROM orders
JOIN products ON orders.product_id = products.product_id;
Answer: The total revenue generated from sales is 14200.

Question 20: What is the average quantity of products ordered per customer?
SELECT AVG(quantity) AS average_quantity
FROM orders
GROUP BY customer_id;
Answer:
| average_quantity |
|------------------|
| 3.0000 |
| 1.0000 |
| 2.5000 |

30
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

2. Function Based Query writing (Analytical functions)

Here are 20 queries and their corresponding answers based on window


functions in MySQL:
As you have created tables and inserted data into tables in previous sections.
So now, I am expecting you to write create table statement for the tables in
this sections, also write insert statement to insert data as given in the sample
data.

Table: sales

| sales_id | product_id | sale_date | quantity |


|----------|------------|------------|----------|
| 1 | 1 | 2023-01-01 | 10 |
| 2 | 1 | 2023-01-02 | 5 |
| 3 | 2 | 2023-01-01 | 8 |
| 4 | 2 | 2023-01-02 | 12 |
| 5 | 3 | 2023-01-01 | 15 |
| 6 | 3 | 2023-01-02 | 20 |

Question 1: What is the total quantity of products sold on each sale date?
SELECT sale_date, SUM(quantity) OVER (PARTITION BY sale_date) AS
total_quantity
FROM sales;
Answer:
| sale_date | total_quantity |
|------------|----------------|
| 2023-01-01 | 33 |
| 2023-01-02 | 37 |

31
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

Question 2: What is the running total of quantity sold for each product?
SELECT product_id, sale_date, quantity,
SUM(quantity) OVER (PARTITION BY product_id ORDER BY
sale_date) AS running_total
FROM sales;
Answer:
| product_id | sale_date | quantity | running_total |
|------------|------------|----------|---------------|
| 1 | 2023-01-01 | 10 | 10 |
| 1 | 2023-01-02 | 5 | 15 |
| 2 | 2023-01-01 | 8 | 8 |
| 2 | 2023-01-02 | 12 | 20 |
| 3 | 2023-01-01 | 15 | 15 |
| 3 | 2023-01-02 | 20 | 35 |

Question 3: What is the rank of each product based on the total quantity
sold?
SELECT product_id, SUM(quantity) AS total_quantity,
RANK() OVER (ORDER BY SUM(quantity) DESC) AS product_rank
FROM sales
GROUP BY product_id;
Answer:
| product_id | total_quantity | product_rank |
|------------|----------------|--------------|
| 3 | 35 | 1 |
| 2 | 20 | 2 |
| 1 | 15 | 3 |

32
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

Question 4: What is the dense rank of each product based on the total
quantity sold?
SELECT product_id, SUM(quantity) AS total_quantity,
DENSE_RANK() OVER (ORDER BY SUM(quantity) DESC) AS
product_dense_rank
FROM sales
GROUP BY product_id;
Answer:
| product_id | total_quantity | product_dense_rank |
|------------|----------------|--------------------|
| 3 | 35 | 1 |
| 2 | 20 | 2 |
| 1 | 15 | 3 |

Question 5: What is the row number of each sale?


SELECT sales_id, product_id, sale_date, quantity,
ROW_NUMBER() OVER (ORDER BY sale_date) AS row_number
FROM sales;
Answer:
| sales_id | product_id | sale_date | quantity | row_number |
|----------|------------|------------|----------|------------|
| 1 | 1 | 2023-01-01 | 10 | 1 |
| 3 | 2 | 2023-01-01 | 8 | 2 |
| 5 | 3 | 2023-01-01 | 15 | 3 |
| 2 | 1 | 2023-01-02 | 5 | 4 |
| 4 | 2 | 2023-01-02 | 12 | 5 |
| 6 | 3 | 2023-01-02 | 20 | 6 |

33
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

Question 6: What is the maximum quantity sold on each sale date?


SELECT sale_date, MAX(quantity) OVER (PARTITION BY sale_date) AS
max_quantity
FROM sales;
Answer:
| sale_date | max_quantity |
|------------|--------------|
| 2023-01-01 | 15 |
| 2023-01-02 | 20 |

Question 7: What is the minimum quantity sold on each sale date?


SELECT sale_date, MIN(quantity) OVER (PARTITION BY sale_date) AS
min_quantity
FROM sales;
Answer:
| sale_date | min_quantity |
|------------|--------------|
| 2023-01-01 | 8 |
| 2023-01-02 | 5 |

Question 8: What is the average quantity sold on each sale date?


SELECT sale_date, AVG(quantity) OVER (PARTITION BY sale_date) AS
average_quantity
FROM sales;
Answer:
| sale_date | average_quantity |
|------------|------------------|
| 2023-01-01 | 11 |
| 2023-01-02 | 12.3333 |

34
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

Question 9: What is the difference in quantity sold compared to the previous


sale date?
SELECT sale_date, quantity,
LAG(quantity) OVER (ORDER BY sale_date) AS
previous_quantity,
quantity - LAG(quantity) OVER (ORDER BY sale_date) AS
quantity_difference
FROM sales;
Answer:
| sale_date | quantity | previous_quantity |
quantity_difference |
|------------|----------|------------------|--------------------
-|
| 2023-01-01 | 10 | NULL | NULL
|
| 2023-01-02 | 5 | 10 | -5
|
| 2023-01-01 | 8 | 5 | 3
|
| 2023-01-02 | 12 | 8 | 4
|
| 2023-01-01 | 15 | 12 | 3
|
| 2023-01-02 | 20 | 15 | 5
|

Question 10: What is the cumulative sum of quantity sold per product?
SELECT product_id, sale_date, quantity,
SUM(quantity) OVER (PARTITION BY product_id ORDER BY
sale_date) AS cumulative_sum
FROM sales;

35
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

Answer:
| product_id | sale_date | quantity | cumulative_sum |
|------------|------------|----------|----------------|
| 1 | 2023-01-01 | 10 | 10 |
| 1 | 2023-01-02 | 5 | 15 |
| 2 | 2023-01-01 | 8 | 8 |
| 2 | 2023-01-02 | 12 | 20 |
| 3 | 2023-01-01 | 15 | 15 |
| 3 | 2023-01-02 | 20 | 35 |

Question 11: What is the first sale date for each product?
SELECT product_id, sale_date,
FIRST_VALUE(sale_date) OVER (PARTITION BY product_id
ORDER BY sale_date) AS first_sale_date
FROM sales;
Answer:
| product_id | sale_date | first_sale_date |
|------------|------------|-----------------|
| 1 | 2023-01-01 | 2023-01-01 |
| 1 | 2023-01-02 | 2023-01-01 |
| 2 | 2023-01-01 | 2023-01-01 |
| 2 | 2023-01-02 | 2023-01-01 |
| 3 | 2023-01-01 | 2023-01-01 |
| 3 | 2023-01-02 | 2023-01-01 |

Question 12: What is the last sale date for each product?
SELECT product_id, sale_date,
LAST_VALUE(sale_date) OVER (PARTITION BY product_id ORDER
BY sale_date) AS last_sale_date

36
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

FROM sales;
Answer:
| product_id | sale_date | last_sale_date |
|------------|------------|----------------|
| 1 | 2023-01-01 | 2023-01-02 |
| 1 | 2023-01-02 | 2023-01-02 |
| 2 | 2023-01-01 | 2023-01-02 |
| 2 | 2023-01-02 | 2023-01-02 |
| 3 | 2023-01-01 | 2023-01-02 |
| 3 | 2023-01-02 | 2023-01-02 |

Question 13: What is the cumulative sum of quantity sold for all products?
SELECT sale_date, quantity,
SUM(quantity) OVER (ORDER BY sale_date) AS cumulative_sum
FROM sales;
Answer:
| sale_date | quantity | cumulative_sum |
|------------|----------|----------------|
| 2023-01-01 | 10 | 10 |
| 2023-01-01 | 8 | 18 |
| 2023-01-01 | 15 | 33 |
| 2023-01-02 | 5 | 38 |
| 2023-01-02 | 12 | 50 |
| 2023-01-02 | 20 | 70 |

Question 14: What is the percentage of quantity sold compared to the total
quantity?
SELECT sale_date, quantity,

37
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

quantity / SUM(quantity) OVER () * 100 AS


quantity_percentage
FROM sales;
Answer:
| sale_date | quantity | quantity_percentage |
|------------|----------|---------------------|
| 2023-01-01 | 10 | 14.2857 |
| 2023-01-02 | 5 | 7.1429 |
| 2023-01-01 | 8 | 11.4286 |
| 2023-01-02 | 12 | 17.1429 |
| 2023-01-01 | 15 | 21.4286 |
| 2023-01-02 | 20 | 28.5714 |

Question 15: What is the difference in quantity sold compared to the average
quantity?
SELECT sale_date, quantity,
quantity - AVG(quantity) OVER () AS quantity_difference
FROM sales;
Answer:
| sale_date | quantity | quantity_difference |
|------------|----------|---------------------|
| 2023-01-01 | 10 | -2 |
| 2023-01-02 | 5 | -7 |
| 2023-01-01 | 8 | -4 |
| 2023-01-02 | 12 | 0 |
| 2023-01-01 | 15 | 3 |
| 2023-01-02 | 20 | 8 |

38
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

Question 16: What is the maximum quantity sold for each product?
SELECT product_id, MAX(quantity) OVER (PARTITION BY product_id)
AS max_quantity
FROM sales;
Answer:
| product_id | max_quantity |
|------------|--------------|
| 1 | 10 |
| 1 | 10 |
| 2 | 12 |
| 2 | 12 |
| 3 | 20 |
| 3 | 20 |

Question 17: What is the minimum quantity sold for each product?
SELECT product_id, MIN(quantity) OVER (PARTITION BY product_id)
AS min_quantity
FROM sales;
Answer:
| product_id | min_quantity |
|------------|--------------|
| 1 | 5 |
| 1 | 5 |
| 2 | 8 |
| 2 | 8 |
| 3 | 15 |
| 3 | 15 |

39
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

Question 18: What is the average quantity sold for each product?
SELECT product_id, AVG(quantity) OVER (PARTITION BY product_id)
AS average_quantity
FROM sales;
Answer:
| product_id | average_quantity |
|------------|------------------|
| 1 | 7.5 |
| 1 | 7.5 |
| 2 | 10 |
| 2 | 10 |
| 3 | 17.5 |
| 3 | 17.5 |

Question 19: What is the cumulative maximum quantity sold per product?
SELECT product_id, sale_date, quantity,
MAX(quantity) OVER (PARTITION BY product_id ORDER BY
sale_date) AS cumulative_max
FROM sales;
Answer:
| product_id | sale_date | quantity | cumulative_max |
|------------|------------|----------|----------------|
| 1 | 2023-01-01 | 10 | 10 |
| 1 | 2023-01-02 | 5 | 10 |
| 2 | 2023-01-01 | 8 | 8 |
| 2 | 2023-01-02 | 12 | 12 |
| 3 | 2023-01-01 | 15 | 15 |
| 3 | 2023-01-02 | 20 | 20 |

40
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

Question 20: What is the cumulative minimum quantity sold per product?
SELECT product_id, sale_date, quantity,
MIN(quantity) OVER (PARTITION BY product_id ORDER BY
sale_date) AS cumulative_min
FROM sales;

Answer:
| product_id | sale_date | quantity | cumulative_min |
|------------|------------|----------|----------------|
| 1 | 2023-01-01 | 10 | 5 |
| 1 | 2023-01-02 | 5 | 5 |
| 2 | 2023-01-01 | 8 | 8 |
| 2 | 2023-01-02 | 12 | 8 |
| 3 | 2023-01-01 | 15 | 15 |
| 3 | 2023-01-02 | 20 | 15 |

41
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

3. Function Based Query writing (JOINS and Subqueries)

Here are 20 queries that involve joins and subqueries in MySQL, using the
tables 'item_master' and 'order_head', along with the necessary create and
insert statements for the tables and data:

1. Create the "item_master" table:

CREATE TABLE item_master (


item_id INT PRIMARY KEY,
item_name VARCHAR(50),
unit_price DECIMAL(8,2)
);

2. Insert data into the "item_master" table:


INSERT INTO item_master (item_id, item_name, unit_price) VALUES
(1, 'Item A', 10.99),
(2, 'Item B', 8.99),
(3, 'Item C', 15.99);

3. Create the "order_head" table:


CREATE TABLE order_head (
order_id INT PRIMARY KEY,
customer_name VARCHAR(50),
order_date DATE
);

42
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

4. Insert data into the "order_head" table:


INSERT INTO order_head (order_id, customer_name, order_date)
VALUES
(1, 'John Doe', '2023-01-01'),
(2, 'Jane Smith', '2023-02-15'),
(3, 'Mike Johnson', '2023-03-20');

5. Query to get all orders and their respective items:

SELECT order_head.order_id, order_head.customer_name,


item_master.item_name, item_master.unit_price
FROM order_head
JOIN item_master ON 1=1;

6. Query to get orders and their total order amount:

SELECT order_head.order_id, order_head.customer_name,


SUM(item_master.unit_price) AS total_amount
FROM order_head
JOIN item_master ON 1=1
GROUP BY order_head.order_id, order_head.customer_name;

7. Query to get orders placed by a specific customer:

SELECT order_head.order_id, order_head.customer_name,


item_master.item_name, item_master.unit_price
FROM order_head
JOIN item_master ON 1=1
WHERE order_head.customer_name = 'John Doe';

43
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

8. Query to get orders placed on a specific date:

SELECT order_head.order_id, order_head.customer_name,


item_master.item_name, item_master.unit_price
FROM order_head
JOIN item_master ON 1=1
WHERE order_head.order_date = '2023-02-15';

9. Query to get the total number of orders:

SELECT COUNT(order_head.order_id) AS total_orders


FROM order_head;

10. Query to get the average order amount:

SELECT AVG(order_amount) AS average_order_amount


FROM (
SELECT order_head.order_id, SUM(item_master.unit_price) AS
order_amount
FROM order_head
JOIN item_master ON 1=1
GROUP BY order_head.order_id
) AS subquery;

44
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

11. Query to get orders and the highest-priced item in each order:

SELECT order_head.order_id, order_head.customer_name,


MAX(item_master.unit_price) AS highest_price
FROM order_head
JOIN item_master ON 1=1
GROUP BY order_head.order_id, order_head.customer_name;

12. Query to get the total number of items ordered:

SELECT SUM(item_count) AS total_items_ordered


FROM (
SELECT order_head.order_id, COUNT(item_master.item_id) AS
item_count
FROM order_head
JOIN item_master ON 1=1
GROUP BY order_head.order_id
) AS subquery;

13. Query to get orders placed by customers who have ordered more than
once:

SELECT order_head.order_id, order_head.customer_name,


item_master.item_name, item_master.unit_price
FROM order_head
JOIN item_master ON 1=1
WHERE order_head.customer_name IN (
SELECT customer_name
FROM order_head

45
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

GROUP BY customer_name
HAVING COUNT(order_id) > 1
);

14. Query to get orders and the average unit price of items in each order:

SELECT order_head.order_id, order_head.customer_name,


AVG(item_master.unit_price) AS average_unit_price
FROM order_head
JOIN item_master ON 1=1
GROUP BY order_head.order_id, order_head.customer_name;

15. Query to get orders and the most recent order date for each customer:

SELECT order_head.order_id, order_head.customer_name,


MAX(order_head.order_date) AS most_recent_order_date
FROM order_head
JOIN item_master ON 1=1
GROUP BY order_head.order_id, order_head.customer_name;

16. Query to get orders and the total number of items in each order:

SELECT order_head.order_id, order_head.customer_name,


COUNT(item_master.item_id) AS total_items
FROM order_head
JOIN item_master ON 1=1
GROUP BY order_head.order_id, order_head.customer_name;

46
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

17. Query to get orders and the total revenue generated from each order:

SELECT order_head.order_id, order_head.customer_name,


SUM(item_master.unit_price) AS total_revenue
FROM order_head
JOIN item_master ON 1=1
GROUP BY order_head.order_id, order_head.customer_name;

18. Query to get orders and the most expensive item in each order:

SELECT order_head.order_id, order_head.customer_name,


MAX(item_master.unit_price) AS most_expensive_item
FROM order_head
JOIN item_master ON 1=1
GROUP BY order_head.order_id, order_head.customer_name;

19. Query to get orders and the total number of unique items in each order:

SELECT order_head.order_id, order_head.customer_name,


COUNT(DISTINCT item_master.item_id) AS unique_items
FROM order_head
JOIN item_master ON 1=1
GROUP BY order_head.order_id, order_head.customer_name;

20. Query to get orders and the customer name in uppercase for each order:
SELECT order_head.order_id, UPPER(order_head.customer_name) AS
customer_name
FROM order_head
JOIN item_master ON 1=1;

47
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

4. Function Based Query writing (STRING functions)

Here are 20 MySQL queries that utilize STRING functions, along with the
necessary create table and insert statements for an "employee_details" table:

1. Create the "employee_details" table:

CREATE TABLE employee_details (


emp_id INT PRIMARY KEY,
emp_name VARCHAR(50),
emp_email VARCHAR(50),
emp_address VARCHAR(100),
emp_salary DECIMAL(8,2)
);

2. Insert data into the "employee_details" table:

INSERT INTO employee_details (emp_id, emp_name, emp_email,


emp_address, emp_salary) VALUES
(1, 'John Doe', 'john@example.com', '123 Main St, City',
50000.00),
(2, 'Jane Smith', 'jane@example.com', '456 Elm St, City',
60000.00),
(3, 'Mike Johnson', 'mike@example.com', '789 Oak St, City',
70000.00);

3. Query to get the length of employee names:


SELECT emp_name, LENGTH(emp_name) AS name_length
FROM employee_details;

48
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

4. Query to get the lowercase version of employee email addresses:

SELECT emp_name, LOWER(emp_email) AS lower_email


FROM employee_details;

5. Query to get the uppercase version of employee addresses:

SELECT emp_name, UPPER(emp_address) AS upper_address


FROM employee_details;

6. Query to get the substring of employee names:

SELECT emp_name, SUBSTRING(emp_name, 1, 3) AS name_substr


FROM employee_details;

7. Query to concatenate employee names and addresses:

SELECT CONCAT(emp_name, ' - ', emp_address) AS emp_info


FROM employee_details;

8. Query to check if employee email addresses contain a specific string:

SELECT emp_name, emp_email


FROM employee_details
WHERE emp_email LIKE '%example.com%';

49
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

9. Query to replace a substring in employee addresses:

SELECT emp_name, REPLACE(emp_address, 'St', 'Street') AS


new_address
FROM employee_details;

10. Query to get the position of a substring in employee names:

SELECT emp_name, LOCATE('ohn', emp_name) AS substring_position


FROM employee_details;

11. Query to extract a portion of employee email addresses after the '@'
symbol:

SELECT emp_name, SUBSTRING_INDEX(emp_email, '@', -1) AS domain


FROM employee_details;

12. Query to trim whitespace from employee names:

SELECT emp_name, TRIM(emp_name) AS trimmed_name


FROM employee_details;

13. Query to check if employee names start with a specific letter:

SELECT emp_name
FROM employee_details
WHERE emp_name LIKE 'J%';

50
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

14. Query to get the leftmost characters of employee names:

SELECT emp_name, LEFT(emp_name, 3) AS left_chars


FROM employee_details;

15. Query to get the rightmost characters of employee addresses:

SELECT emp_name, RIGHT(emp_address, 4) AS right_chars


FROM employee_details;

16. Query to count the occurrences of a specific character in employee email


addresses:

SELECT emp_name, LENGTH(emp_email) - LENGTH(REPLACE(emp_email,


'a', '')) AS num_occurrences
FROM employee_details;

17. Query to get the reversed version of employee names:

SELECT emp_name, REVERSE(emp_name) AS reversed_name


FROM employee_details;

18. Query to get the character at a specific position in employee names:

SELECT emp_name, SUBSTRING(emp_name, 3, 1) AS char_at_position


FROM employee_details;

51
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

19. Query to capitalize the first letter of employee addresses:

SELECT emp_name, CONCAT(UCASE(SUBSTRING(emp_address, 1, 1)),


LCASE(SUBSTRING(emp_address, 2))) AS capitalized_address
FROM employee_details;

20. Query to pad employee IDs with leading zeros:

SELECT emp_id, LPAD(emp_id, 5, '0') AS padded_id


FROM employee_details;

52
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

5. Function Based Query writing (CASE Statements)

Here are 20 MySQL queries that utilize the CASE function, along with the
necessary create table and insert statements for a "cricket_players_details"
table:

1. Create the "cricket_players_details" table:

CREATE TABLE cricket_players_details (


player_id INT PRIMARY KEY,
player_name VARCHAR(50),
country VARCHAR(50),
matches_played INT,
runs_scored INT,
centuries INT
);

2. Insert data into the "cricket_players_details" table:

INSERT INTO cricket_players_details (player_id, player_name,


country, matches_played, runs_scored, centuries) VALUES
(1, 'Sachin Tendulkar', 'India', 463, 18426, 49),
(2, 'Ricky Ponting', 'Australia', 375, 13704, 30),
(3, 'Kumar Sangakkara', 'Sri Lanka', 404, 14234, 25);

53
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

3. Query to categorize players based on the number of centuries they have


scored:

SELECT player_name, centuries,


CASE
WHEN centuries >= 50 THEN 'Legend'
WHEN centuries >= 30 THEN 'Great Player'
ELSE 'Promising Player'
END AS player_category
FROM cricket_players_details;

4. Query to calculate the batting average for players based on runs scored
and matches played:

SELECT player_name, runs_scored, matches_played,


CASE
WHEN matches_played > 0 THEN runs_scored / matches_played
ELSE 0
END AS batting_average
FROM cricket_players_details;

5. Query to display the country of players with the highest runs scored:

SELECT player_name, runs_scored,


CASE
WHEN runs_scored = (SELECT MAX(runs_scored) FROM
cricket_players_details) THEN country
ELSE ''
END AS country_highest_runs

54
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

FROM cricket_players_details;

6. Query to assign a grade to players based on their batting average:

SELECT player_name, batting_average,


CASE
WHEN batting_average >= 50 THEN 'A'
WHEN batting_average >= 40 THEN 'B'
WHEN batting_average >= 30 THEN 'C'
ELSE 'D'
END AS grade
FROM (
SELECT player_name, runs_scored, matches_played,
CASE
WHEN matches_played > 0 THEN runs_scored / matches_played
ELSE 0
END AS batting_average
FROM cricket_players_details
) AS subquery;

7. Query to calculate the total runs scored by players from each country:

SELECT country,
SUM(runs_scored) AS total_runs_scored
FROM cricket_players_details
GROUP BY country;

55
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

8. Query to display the player name and number of centuries scored, with a
label indicating if they are a "centurion":

SELECT player_name, centuries,


CASE
WHEN centuries > 0 THEN 'Centurion'
ELSE 'Not a Centurion'
END AS centurion_label
FROM cricket_players_details;

9. Query to categorize players based on the number of matches played:

SELECT player_name, matches_played,


CASE
WHEN matches_played >= 400 THEN 'Veteran'
WHEN matches_played >= 300 THEN 'Experienced'
WHEN matches_played >= 200 THEN 'Established'
ELSE 'Emerging'
END AS player_category
FROM cricket_players_details;

10. Query to calculate the strike rate for players based on runs scored and
matches played:

SELECT player_name, runs_scored, matches_played,


CASE
WHEN matches_played > 0 THEN (runs_scored / matches_played)
* 100
ELSE 0

56
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

END AS strike_rate
FROM cricket_players_details;

11. Query to assign a label to players based on their strike rate:

SELECT player_name, strike_rate,


CASE
WHEN strike_rate >= 100 THEN 'Aggressive'
WHEN strike_rate >= 80 THEN 'Moderate'
ELSE 'Defensive'
END AS label
FROM (
SELECT player_name, runs_scored, matches_played,
CASE
WHEN matches_played > 0 THEN (runs_scored /
matches_played) * 100
ELSE 0
END AS strike_rate
FROM cricket_players_details
) AS subquery;

12. Query to display the player name and country, with a label indicating if
they have played international matches:

SELECT player_name, country,


CASE
WHEN country <> 'N/A' THEN 'International Player'
ELSE 'Domestic Player'
END AS player_label

57
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

FROM cricket_players_details;

13. Query to calculate the average runs scored per match for players:

SELECT player_name, runs_scored, matches_played,


CASE
WHEN matches_played > 0 THEN runs_scored / matches_played
ELSE 0
END AS average_runs_per_match
FROM cricket_players_details;

14. Query to categorize players based on their average runs per match:

SELECT player_name, average_runs_per_match,


CASE
WHEN average_runs_per_match >= 50 THEN 'Excellent'
WHEN average_runs_per_match >= 30 THEN 'Good'
WHEN average_runs_per_match >= 20 THEN 'Average'
ELSE 'Below Average'
END AS player_category
FROM (
SELECT player_name, runs_scored, matches_played,
CASE
WHEN matches_played > 0 THEN runs_scored / matches_played
ELSE 0
END AS average_runs_per_match
FROM cricket_players_details
) AS subquery;

58
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

15. Query to display the player name and country, with a label indicating if
they are from a specific country:

SELECT player_name, country,


CASE
WHEN country = 'India' THEN 'Indian Player'
WHEN country = 'Australia' THEN 'Australian Player'
ELSE 'Other Country Player'
END AS player_label
FROM cricket_players_details;

16. Query to calculate the average number of centuries scored per match for
players:

SELECT player_name, centuries, matches_played,


CASE
WHEN matches_played > 0 THEN centuries / matches_played
ELSE 0
END AS average_centuries_per_match
FROM cricket_players_details;

17. Query to assign a label to players based on the number of centuries


scored:

SELECT player_name, centuries,


CASE
WHEN centuries >= 40 THEN 'Legend'
WHEN centuries >= 20 THEN 'Great Player'
WHEN centuries >= 10 THEN 'Promising Player'

59
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

ELSE 'Upcoming Player'


END AS player_label
FROM cricket_players_details;

18. Query to display the player name and country, with a label indicating if
they are the highest run-scorer in their country:

SELECT player_name, country,


CASE
WHEN runs_scored = (
SELECT MAX(runs_scored)
FROM cricket_players_details AS cpd
WHERE cpd.country = cricket_players_details.country
) THEN 'Highest Run-scorer'
ELSE ''
END AS player_label
FROM cricket_players_details;

19. Query to calculate the total number of players from each country and
assign a label indicating if it's a dominant cricketing nation:

SELECT country, COUNT(*) AS player_count,


CASE
WHEN COUNT(*) >= 5 THEN 'Dominant Nation'
ELSE ''
END AS country_label
FROM cricket_players_details
GROUP BY country;

60
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

20. Query to assign a label to players based on the combination of matches


played and centuries scored:

SELECT player_name, matches_played, centuries,


CASE
WHEN matches_played > 200 AND centuries >= 50 THEN
'Superstar'
WHEN matches_played > 100 AND centuries >= 30 THEN 'Star
Player'
ELSE 'Regular Player'
END AS player_label
FROM cricket_players_details;

61
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

6. Function Based Query writing (Regex (regular Expression))

Here are 20 MySQL queries that utilize regular expressions (regex) functions,
along with the necessary create table and insert statements for a
"movie_details" table:

1. Create the "movie_details" table:

CREATE TABLE movie_details (


movie_id INT PRIMARY KEY,
movie_title VARCHAR(100),
genre VARCHAR(50),
release_year INT,
director VARCHAR(50),
rating DECIMAL(3, 1)
);

2. Insert data into the "movie_details" table:

INSERT INTO movie_details (movie_id, movie_title, genre,


release_year, director, rating) VALUES
(1, 'The Shawshank Redemption', 'Drama', 1994, 'Frank
Darabont', 9.3),
(2, 'The Godfather', 'Crime', 1972, 'Francis Ford Coppola',
9.2),
(3, 'Pulp Fiction', 'Crime', 1994, 'Quentin Tarantino', 8.9);

62
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

3. Query to retrieve movies with titles starting with 'The':

SELECT movie_title
FROM movie_details
WHERE movie_title REGEXP '^The';

4. Query to retrieve movies with titles ending with 'tion':

SELECT movie_title
FROM movie_details
WHERE movie_title REGEXP 'tion$';

5. Query to retrieve movies with titles containing 'Godfather' or 'Godfather II':

SELECT movie_title
FROM movie_details
WHERE movie_title REGEXP 'Godfather|Godfather II';

6. Query to retrieve movies with titles having exactly five words:

SELECT movie_title
FROM movie_details
WHERE movie_title REGEXP '^(\S+\s+){4}\S+$';

7. Query to retrieve movies with titles starting with a digit:

SELECT movie_title
FROM movie_details

63
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

WHERE movie_title REGEXP '^[0-9]';

8. Query to retrieve movies with titles containing at least one digit:

SELECT movie_title
FROM movie_details
WHERE movie_title REGEXP '[0-9]';

9. Query to retrieve movies released in the 1990s:

SELECT movie_title
FROM movie_details
WHERE release_year REGEXP '199[0-9]';

10. Query to retrieve movies with directors whose names contain 'Tarantino':

SELECT movie_title
FROM movie_details
WHERE director REGEXP 'Tarantino';

11. Query to retrieve movies with ratings greater than or equal to 9.0:

SELECT movie_title
FROM movie_details
WHERE rating REGEXP '^[9-9]\.[0-9]$|^10\.0$';

64
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

12. Query to retrieve movies with titles containing exactly two consecutive
vowels:

SELECT movie_title
FROM movie_details
WHERE movie_title REGEXP '[aeiou]{2}';

13. Query to retrieve movies with genres starting with 'C' or 'D':

SELECT movie_title
FROM movie_details
WHERE genre REGEXP '^(C|D)';

14. Query to retrieve movies with directors having exactly two words in their
names:

SELECT movie_title
FROM movie_details
WHERE director REGEXP '^[^ ]+ [^ ]+$';

15. Query to retrieve movies with ratings between 8.0 and 8.9:

SELECT movie_title
FROM movie_details
WHERE rating REGEXP '^8\.[0-9]$';

65
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

16. Query to retrieve movies with titles containing the word 'Redemption':

SELECT movie_title
FROM

movie_details
WHERE movie_title REGEXP 'Redemption';

17. Query to retrieve movies with directors whose names end with 'Coppola':

SELECT movie_title
FROM movie_details
WHERE director REGEXP 'Coppola$';

18. Query to retrieve movies with genres containing the word 'Crime':

SELECT movie_title
FROM movie_details
WHERE genre REGEXP 'Crime';

19. Query to retrieve movies with titles starting with any letter except 'A':

SELECT movie_title
FROM movie_details
WHERE movie_title REGEXP '^[^A]';

66
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

20. Query to retrieve movies with ratings containing exactly one decimal digit:

SELECT movie_title
FROM movie_details
WHERE rating REGEXP '^[0-9]\.[0-9]$';

67
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

7. Function Based Query writing (Date functions)

Here are 20 MySQL queries that utilize date functions, along with the
necessary create table and insert statements for a "students_details" table:

1. Create the "students_details" table:

CREATE TABLE students_details (


student_id INT PRIMARY KEY,
student_name VARCHAR(50),
date_of_birth DATE,
admission_date DATE
);

2. Insert data into the "students_details" table:

INSERT INTO students_details (student_id, student_name,


date_of_birth, admission_date) VALUES
(1, 'John Doe', '2002-05-10', '2020-09-01'),
(2, 'Jane Smith', '2003-02-15', '2021-01-15'),
(3, 'Mike Johnson', '2001-11-20', '2019-08-10');

3. Query to retrieve students born after a specific date:

SELECT student_name
FROM students_details
WHERE date_of_birth > '2002-01-01';

68
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

4. Query to retrieve students admitted in a specific year:

SELECT student_name
FROM students_details
WHERE YEAR(admission_date) = 2020;

5. Query to retrieve the current date:

SELECT CURDATE();

6. Query to retrieve students who were admitted in the current month:

SELECT student_name
FROM students_details
WHERE MONTH(admission_date) = MONTH(CURDATE());

7. Query to retrieve students who were admitted on a specific day of the


week:

SELECT student_name
FROM students_details
WHERE DAYNAME(admission_date) = 'Friday';

8. Query to retrieve students with their age calculated based on the current
date:
SELECT student_name, TIMESTAMPDIFF(YEAR, date_of_birth,
CURDATE()) AS age
FROM students_details;

69
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

9. Query to retrieve students who have birthdays in the current month:

SELECT student_name
FROM students_details
WHERE MONTH(date_of_birth) = MONTH(CURDATE());

10. Query to retrieve students with their admission dates formatted in a


specific way:

SELECT student_name, DATE_FORMAT(admission_date, '%d-%m-%Y') AS


formatted_admission_date
FROM students_details;

11. Query to retrieve the number of days between the date of birth and
admission date for each student:

SELECT student_name, DATEDIFF(admission_date, date_of_birth) AS


days_between
FROM students_details;

12. Query to retrieve students who were admitted before a specific date:

SELECT student_name
FROM students_details
WHERE admission_date < '2021-01-01';

70
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

13. Query to retrieve students with their age calculated based on a specific
date:

SELECT student_name, TIMESTAMPDIFF(YEAR, date_of_birth, '2023-


06-12') AS age
FROM students_details;

14. Query to retrieve students with their admission dates in descending


order:

SELECT student_name, admission_date


FROM students_details
ORDER BY admission_date DESC;

15. Query to retrieve students who were born on a specific day of the week:

SELECT student_name
FROM students_details
WHERE DAYNAME(date_of_birth) = 'Monday';

16. Query to retrieve students with their admission year and month
combined:

SELECT student_name, CONCAT(YEAR(admission_date), '-',


LPAD(MONTH(admission_date), 2, '0')) AS admission_year_month
FROM students_details;

71
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

17. Query to retrieve students who were born in a specific year:

SELECT student_name
FROM students_details
WHERE YEAR(date_of_birth) = 2001;

18. Query to retrieve students with their age calculated in months based on
the current date:

SELECT student_name, TIMESTAMPDIFF(MONTH, date_of_birth,


CURDATE()) AS age_in_months
FROM students_details;

19. Query to retrieve students with their admission dates in a specific date
format:

SELECT student_name, DATE_FORMAT(admission_date, '%M %e, %Y') AS


formatted_admission_date
FROM students_details;

20. Query to retrieve students who were admitted in a specific month and
year:

SELECT student_name
FROM students_details
WHERE YEAR(admission_date) = 2020 AND MONTH(admission_date) = 9;

72
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

8. Function Based Query writing (Numeric functions)

Here are 20 MySQL queries that utilize numeric functions, along with the
necessary create table and insert statements for an "exam_score_details"
table:

1. Create the "exam_score_details" table:

CREATE TABLE exam_score_details (


student_id INT PRIMARY KEY,
student_name VARCHAR(50),
math_score INT,
science_score INT,
english_score INT
);

2. Insert data into the "exam_score_details" table:

INSERT INTO exam_score_details (student_id, student_name,


math_score, science_score, english_score) VALUES
(1, 'John Doe', 80, 85, 90),
(2, 'Jane Smith', 90, 75, 95),
(3, 'Mike Johnson', 70, 80, 85);

3. Query to calculate the total score for each student:

SELECT student_name, math_score + science_score + english_score


AS total_score
FROM exam_score_details;

73
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

4. Query to calculate the average score for each subject:

SELECT AVG(math_score) AS avg_math_score, AVG(science_score) AS


avg_science_score, AVG(english_score) AS avg_english_score
FROM exam_score_details;

5. Query to calculate the highest score in math:

SELECT MAX(math_score) AS highest_math_score


FROM exam_score_details;

6. Query to calculate the lowest score in science:

SELECT MIN(science_score) AS lowest_science_score


FROM exam_score_details;

7. Query to calculate the difference between math and science scores for each
student:

SELECT student_name, math_score - science_score AS


math_science_diff
FROM exam_score_details;

8. Query to calculate the square of the math score for each student:

SELECT student_name, POWER(math_score, 2) AS math_score_squared


FROM exam_score_details;

74
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

9. Query to calculate the average score across all subjects for each student:

SELECT student_name, (math_score + science_score +


english_score) / 3 AS avg_subject_score
FROM exam_score_details;

10. Query to round the math score to the nearest ten for each student:

SELECT student_name, ROUND(math_score, -1) AS rounded_math_score


FROM exam_score_details;

11. Query to calculate the absolute difference between science and english
scores for each student:

SELECT student_name, ABS(science_score - english_score) AS


science_english_diff
FROM exam_score_details;

12. Query to calculate the average score for each subject and round it to two
decimal places:

SELECT ROUND(AVG(math_score), 2) AS avg_math_score,


ROUND(AVG(science_score), 2) AS avg_science_score,
ROUND(AVG(english_score), 2) AS avg_english_score
FROM exam_score_details;

13. Query to calculate the square root of the math score for each student:

SELECT student_name, SQRT(math_score) AS math_score_sqrt


FROM exam_score_details;

75
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

14. Query to calculate the percentage of the math score for each student out
of 100:

SELECT student_name, (math_score / 100) * 100 AS


math_score_percentage
FROM exam_score_details;

15. Query to calculate the ceiling value of the science score for each student:

SELECT student_name, CEILING(science_score) AS


ceil_science_score
FROM exam_score_details;

16. Query to calculate the average score across all subjects and round it to
the nearest integer for each student:

SELECT student_name, ROUND((math_score + science_score +


english_score) / 3) AS avg_subject_score
FROM exam_score_details;

17. Query to calculate the logarithm base 10 of the english score for each
student:

SELECT student_name, LOG10(english_score) AS english_score_log


FROM exam_score_details;

76
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

18. Query to calculate the average score for each subject and assign a grade
based on specific criteria:

SELECT student_name,
CASE
WHEN math_score >= 80 THEN 'A'
WHEN math_score >= 70 THEN 'B'
WHEN math_score >= 60 THEN 'C'
ELSE 'D'
END AS math_grade,
CASE
WHEN science_score >= 80 THEN 'A'
WHEN science_score >= 70 THEN 'B'
WHEN science_score >= 60 THEN 'C'
ELSE 'D'
END AS science_grade,
CASE
WHEN english_score >= 80 THEN 'A'
WHEN english_score >= 70 THEN 'B'
WHEN english_score >= 60 THEN 'C'
ELSE 'D'
END AS english_grade
FROM exam_score_details;

19. Query to calculate the standard deviation of the math scores:

SELECT STD(math_score) AS math_score_std_deviation


FROM exam_score_details;

77
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it
SQL Practice Questions Queries with Answers

20. Query to calculate the median of the science scores:

SELECT science_score
FROM exam_score_details
ORDER BY science_score
LIMIT 1 OFFSET (SELECT COUNT(*) FROM exam_score_details) / 2;

SPECIAL NOTE For ALL


If you need Theory for SQL and Theoretical interview Questions with answers,
then you can also buy our Ebook—Its really helpful for you before going to
any interview.

Use this link SQL Interview Revision Guide

Thank you for purchasing the Query practice e book.

78
All right reserved by careerswitchhelp.com | Please refrain yourself of copying it

You might also like