0% found this document useful (0 votes)
6 views7 pages

SQL Questions

This document provides a comprehensive set of SQL interview questions and answers for freshers, organized into basic, intermediate, and advanced levels. It covers essential SQL concepts, including data types, queries, joins, and performance optimization techniques, with examples relevant to interviews at IT firms. Additionally, it offers preparation tips for candidates to enhance their SQL skills and interview readiness.

Uploaded by

iamnoone2211
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views7 pages

SQL Questions

This document provides a comprehensive set of SQL interview questions and answers for freshers, organized into basic, intermediate, and advanced levels. It covers essential SQL concepts, including data types, queries, joins, and performance optimization techniques, with examples relevant to interviews at IT firms. Additionally, it offers preparation tips for candidates to enhance their SQL skills and interview readiness.

Uploaded by

iamnoone2211
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

SQL Interview Questions for Freshers (MySQL)

Introduction
This document provides a curated set of SQL (MySQL) interview questions for freshers,
progressing from basic to advanced levels. These questions are designed based on patterns
observed in interviews at companies like LTI Mindtree, Infosys, and similar IT firms.
Answers are provided at the end for reference.

Basic Level Questions


These questions test foundational SQL knowledge, focusing on syntax, simple queries,
and basic database operations.
1. What is the difference between CHAR and VARCHAR data types in MySQL?
2. Write a query to create a table named Employees with columns: emp_id (integer,
primary key), first_name (varchar), last_name (varchar), salary (decimal), and
hire_date (date).
3. Write a query to retrieve all columns from the Employees table where the salary is
greater than 50000.
4. What is the difference between DELETE and TRUNCATE in MySQL?
5. Write a query to insert a new record into the Employees table.
6. Write a query to update the salary of an employee with emp_id = 101 to 60000.
7. What is a primary key, and why is it important in a database?
8. Write a query to find the total number of employees in the Employees table.
9. Explain the difference between WHERE and HAVING clauses.
10. Write a query to retrieve the top 5 employees with the highest salaries.

Intermediate Level Questions


These questions focus on joins, grouping, and subqueries, common in real-world applica-
tions.

1
11. Given two tables, Employees (emp_id, first_name, last_name, dept_id) and
Departments (dept_id, dept_name), write a query to display the first name, last
name, and department name for all employees.
12. Write a query to find employees who do not belong to any department (i.e., dept_id
is NULL or does not exist in the Departments table).
13. Write a query to find the average salary per department.
14. Write a query to find the employee with the second-highest salary without using
LIMIT.
15. What is the difference between INNER JOIN and LEFT JOIN? Provide an example
query for each.
16. Write a query to find duplicate records in the Employees table based on first_name
and last_name.
17. Write a query to retrieve employees whose salary is above the average salary of
their department.
18. What is a foreign key, and how does it enforce referential integrity?
19. Write a query to delete all employees hired before January 1, 2020.
20. Explain the use of INDEX in MySQL and how it improves query performance.

Advanced Level Questions


These questions involve complex queries, window functions, and performance considera-
tions.
21. Write a query to rank employees within each department based on their salary
using a window function.
22. Write a query to find the nth highest salary in the Employees table.
23. Given a table Orders (order_id, customer_id, order_date, amount), write a
query to find customers who placed more than 3 orders in the last 6 months.
24. Write a query to pivot the Employees table to show the total salary for each de-
partment as columns for a given year.
25. Explain the difference between UNION and UNION ALL. Write a query to combine
employee names from two tables (Employees and Contractors) using UNION ALL.
26. Write a query to find the longest consecutive sequence of days when an employee
was absent, given an Absences table (emp_id, absence_date).
27. What is a self-join, and when would you use it? Provide an example query.
28. Write a query to find employees whose salary increased by more than 10% compared
to the previous year, given a SalaryHistory table (emp_id, salary, year).
29. How would you optimize a slow-running query that joins multiple large tables?

2
30. Write a query to find the top 3 departments with the highest average salary, in-
cluding ties.

Answers
Basic Level Answers
1. Difference between CHAR and VARCHAR: CHAR is fixed-length, padding spaces if
data is shorter than defined length; VARCHAR is variable-length, storing only actual
data. CHAR is faster for fixed-size data (e.g., codes), while VARCHAR saves space for
variable-length data (e.g., names).
2. Create table query:
CREATE TABLE Employees (
emp_id INT PRIMARY KEY ,
first_name VARCHAR (50) ,
last_name VARCHAR (50) ,
salary DECIMAL (10 ,2) ,
hire_date DATE
);

3. Retrieve employees with salary > 50000:


SELECT * FROM Employees WHERE salary > 50000;

4. Difference between DELETE and TRUNCATE: DELETE removes specific rows with
optional WHERE clause, logs transactions, and can be rolled back. TRUNCATE removes
all rows, resets auto-increment, is faster, and cannot be rolled back in MySQL.
5. Insert a record:
INSERT INTO Employees ( emp_id , first_name , last_name , salary ,
hire_date )
VALUES (101 , ’ John ’ , ’ Doe ’ , 55000.00 , ’ 2023 -01 -15 ’) ;

6. Update salary for emp_id = 101:


UPDATE Employees SET salary = 60000 WHERE emp_id = 101;

7. Primary key importance: A primary key uniquely identifies each record in a


table, enforces data integrity, and enables efficient indexing and joins.
8. Total number of employees:
SELECT COUNT (*) AS employee_count FROM Employees ;

9. Difference between WHERE and HAVING: WHERE filters individual rows before
grouping; HAVING filters groups after GROUP BY. Example: WHERE salary > 50000
filters rows; HAVING AVG(salary) > 60000 filters grouped results.
10. Top 5 highest salaries:
SELECT * FROM Employees ORDER BY salary DESC LIMIT 5;

3
Intermediate Level Answers
11. Join Employees and Departments:
SELECT e . first_name , e . last_name , d . dept_name
FROM Employees e
INNER JOIN Departments d ON e . dept_id = d . dept_id ;

12. Employees with no department:


SELECT e . first_name , e . last_name
FROM Employees e
LEFT JOIN Departments d ON e . dept_id = d . dept_id
WHERE d . dept_id IS NULL ;

13. Average salary per department:


SELECT d . dept_name , AVG ( e . salary ) AS avg_salary
FROM Employees e
INNER JOIN Departments d ON e . dept_id = d . dept_id
GROUP BY d . dept_name ;

14. Second-highest salary without LIMIT:


SELECT MAX ( salary )
FROM Employees
WHERE salary < ( SELECT MAX ( salary ) FROM Employees ) ;

15. INNER JOIN vs. LEFT JOIN: INNER JOIN returns only matching records from both
tables. LEFT JOIN returns all records from the left table and matching records from
the right, with NULLs for non-matches.
• INNER JOIN example:
SELECT e . first_name , e . last_name , d . dept_name
FROM Employees e
INNER JOIN Departments d ON e . dept_id = d . dept_id ;

• LEFT JOIN example:


SELECT e . first_name , e . last_name , d . dept_name
FROM Employees e
LEFT JOIN Departments d ON e . dept_id = d . dept_id ;

16. Find duplicate records:


SELECT first_name , last_name , COUNT (*) AS count
FROM Employees
GROUP BY first_name , last_name
HAVING count > 1;

17. Employees above department average salary:

4
SELECT e1 . first_name , e1 . last_name , e1 . salary , e1 . dept_id
FROM Employees e1
WHERE e1 . salary > (
SELECT AVG ( e2 . salary )
FROM Employees e2
WHERE e2 . dept_id = e1 . dept_id
);

18. Foreign key and referential integrity: A foreign key is a column that links to
a primary key in another table, ensuring referential integrity by preventing invalid
data (e.g., an employee with a non-existent dept_id).
19. Delete employees hired before 2020:
DELETE FROM Employees WHERE hire_date < ’ 2020 -01 -01 ’;

20. Use of INDEX: An index improves query performance by allowing faster data re-
trieval. Example: CREATE INDEX idx_salary ON Employees(salary); speeds up
queries filtering or sorting by salary. However, it increases write operation overhead.

Advanced Level Answers


21. Rank employees by salary within department:
SELECT e . first_name , e . last_name , e . salary , d . dept_name ,
RANK () OVER ( PARTITION BY e . dept_id ORDER BY e . salary
DESC ) AS salary_rank
FROM Employees e
INNER JOIN Departments d ON e . dept_id = d . dept_id ;

22. Nth highest salary:


SELECT DISTINCT salary
FROM (
SELECT salary , DENSE_RANK () OVER ( ORDER BY salary DESC )
AS rnk
FROM Employees
) t
WHERE rnk = n ; % Replace ’n ’ with desired rank , e . g . , 3

23. Customers with >3 orders in last 6 months:


SELECT customer_id , COUNT (*) AS order_count
FROM Orders
WHERE order_date >= DATE_SUB ( CURDATE () , INTERVAL 6 MONTH )
GROUP BY customer_id
HAVING order_count > 3;

24. Pivot salaries by department:


SELECT year ,

5
SUM ( CASE WHEN dept_id = 1 THEN salary ELSE 0 END ) AS
dept_1_salary ,
SUM ( CASE WHEN dept_id = 2 THEN salary ELSE 0 END ) AS
dept_2_salary
FROM Employees
WHERE YEAR ( hire_date ) = 2023
GROUP BY year ;

25. UNION vs. UNION ALL: UNION removes duplicates and sorts results; UNION ALL
keeps duplicates and is faster.
• Example:
SELECT first_name , last_name FROM Employees
UNION ALL
SELECT first_name , last_name FROM Contractors ;

26. Longest consecutive absence sequence:


WITH RankedAbsences AS (
SELECT emp_id , absence_date ,
ROW_NUMBER () OVER ( PARTITION BY emp_id ORDER BY
absence_date ) AS rn ,
DATE_SUB ( absence_date , INTERVAL ROW_NUMBER () OVER
( PARTITION BY emp_id ORDER BY absence_date ) DAY
) AS group_id
FROM Absences
)
SELECT emp_id , MIN ( absence_date ) AS start_date , MAX (
absence_date ) AS end_date , COUNT (*) AS consecutive_days
FROM RankedAbsences
GROUP BY emp_id , group_id
ORDER BY consecutive_days DESC
LIMIT 1;

27. Self-join and example: A self-join joins a table to itself, useful for hierarchical
data or comparing rows within the same table.
• Example (find employees with the same manager):
SELECT e1 . first_name , e1 . last_name , e2 . first_name AS
manager_name
FROM Employees e1
INNER JOIN Employees e2 ON e1 . manager_id = e2 . emp_id ;

28. Salary increase >10% from previous year:


SELECT emp_id , salary , year
FROM (
SELECT emp_id , salary , year ,
LAG ( salary ) OVER ( PARTITION BY emp_id ORDER BY
year ) AS prev_salary
FROM SalaryHistory

6
) t
WHERE salary > prev_salary * 1.10;

29. Optimize slow query: Use indexes on join columns and WHERE conditions. Avoid
SELECT *; specify needed columns. Use EXPLAIN to analyze query execution plan.
Partition large tables or use appropriate join types. Cache frequently accessed data.
30. Top 3 departments with ties:
SELECT d . dept_name , AVG ( e . salary ) AS avg_salary
FROM Employees e
INNER JOIN Departments d ON e . dept_id = d . dept_id
GROUP BY d . dept_name
ORDER BY avg_salary DESC
LIMIT 3;

Preparation Tips
• Practice on Platforms: Use LeetCode, HackerRank, or SQLZoo for hands-on
query practice.
• Understand Database Design: Be comfortable with normalization, constraints,
and ER diagrams.
• Learn MySQL-Specific Features: Study functions like DATE_SUB, CONCAT, and
window functions.
• Mock Interviews: Simulate interviews with peers or use platforms like Interview-
Bit.
• Review Real-World Scenarios: Companies like Infosys and LTI Mindtree of-
ten ask questions tied to reporting, data aggregation, or basic optimization for
enterprise systems.

You might also like