Krishnaik06 The-Grand-Complete-Data-Science-Materials
Krishnaik06 The-Grand-Complete-Data-Science-Materials
main
Here are 100+ MySQL interview questions with their answers, ranging from basic to more
intermediate topics:
What is the difference between the HAVING clause and the WHERE clause?
Answer: WHERE filters records before aggregating in GROUP BY , whereas HAVING
filters after aggregation.
How would you list the number of students enrolled in each course, but only
display courses with more than 5 students?
Answer:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE some_column = some_value;
SELECT student_id
FROM students
WHERE EXISTS (SELECT 1 FROM enrollments WHERE students.student_id = enroll
Write a SQL query to find the 3rd highest salary from a salaries table.
Answer:
START TRANSACTION;
-- SQL operations
COMMIT;
Write a SQL query to rank employees based on their salary in descending order.
Answer:
Answer: The default storage engine was MyISAM up to MySQL 5.5, but InnoDB
became the default from MySQL 5.5 onward.
Answer: The SET type is used to store a set of strings. You can store zero or more
string values chosen from a list defined at table creation time.
SELECT * FROM table_name LIMIT 10 OFFSET 20; -- Skips the first 20 record
How can you retrieve the month part from a DATE field in MySQL?
Answer: Using the MONTH() function.
How can you transpose rows into columns, and vice versa, in a query result?
Answer: This process is known as "Pivoting". To convert rows to columns, you use
a combination of aggregate functions with CASE statements. For the reverse,
known as "Unpivoting", you can use UNION ALL .
-- Pivoting:
SELECT
SUM(CASE WHEN column = 'value1' THEN 1 ELSE 0 END) AS 'Value1',
SUM(CASE WHEN column = 'value2' THEN 1 ELSE 0 END) AS 'Value2'
FROM table_name;
-- Unpivoting:
SELECT 'Value1' AS 'Column', Value1 AS 'Value' FROM table_name
UNION ALL
SELECT 'Value2' AS 'Column', Value2 AS 'Value' FROM table_name;
MyISAM typically offers better read performance, while InnoDB offers better
write performance.
How can you lock a table explicitly?
Answer:
How do you get the second highest value from a table column?
Answer:
SELECT column_name
FROM table_name t1
WHERE some_value = (SELECT MAX(column_name) FROM table_name t2 WHERE t1.id
To restore:
mysql -u username -p database_name < backup.sql
SELECT ROW_COUNT();
How can you delete all records from a table without deleting the table?
Answer:
How do you combine results from multiple SQL queries and return a single table?
Answer: You can use the UNION or UNION ALL operator, depending on whether or
not you want duplicate records.
How can you convert a string to upper-case in MySQL?
Answer:
How can you remove leading and trailing whitespace from a string in MySQL?
Answer:
How can you find all the tables that have a specific column name in a database?
Answer:
SELECT table_name
FROM information_schema.columns
WHERE column_name = 'desired_column' AND table_schema = 'your_database_nam
These questions cover a range of advanced topics and should help in assessing the depth
of knowledge of individuals familiar with MySQL.
Answer: The WITH clause, also known as Common Table Expressions (CTE), provides a
temporary result set that you can reference within a SELECT , INSERT , UPDATE , or
DELETE statement. It's useful for breaking down complex queries.
WITH CTE_Name AS (
SELECT column1, column2
FROM table_name
WHERE condition
)
SELECT * FROM CTE_Name;
Answer: A self- join is a join where a table is joined with itself. It's useful for finding
relationships within the same table.
91. What are the different types of subqueries? Explain with examples.
SELECT column_name
FROM table_name
WHERE another_column = (SELECT MAX(column_name) FROM table_name);
SELECT column_name
FROM (
SELECT column_name FROM table_name WHERE condition
) AS subquery_name;
92. How can you update data in one table based on data in another table?
Answer:
UPDATE table1
SET table1.column_name = table2.column_name
FROM table2
WHERE table1.another_column = table2.another_column;
Answer:
94. What's the difference between INNER JOIN and OUTER JOIN ?
Answer: INNER JOIN returns rows when there's a match in both tables. OUTER JOIN
returns all rows from one table and the matching rows from the other table, filling with
NULL if no match is found.
95. How can you clone a table, including both data and schema?
Answer:
Answer:
INSERT INTO table_name (column1, column2)
VALUES (value1a, value2a),
(value1b, value2b),
...;
Answer: Partitioning divides a table into smaller, more manageable pieces, yet still
being treated as a single table. It can improve performance and assist in organizing
large datasets.
Answer: It's used to concatenate values from multiple rows into a single string.
100. How do you show the current SQL mode, and how can you change it?
Answer:
START TRANSACTION;
INSERT INTO table_name1 ...;
INSERT INTO table_name2 ...;
COMMIT; -- Or ROLLBACK;
102. What are the differences between VARCHAR and TEXT data types?
Answer: While both are used to store strings, VARCHAR can store up to 65,535
characters and you can specify its max length, while TEXT can store up to 65,535
characters without specifying max length. VARCHAR can have a default value, but TEXT
cannot.
103. How do you find and fix broken foreign key constraints?
Answer: Identify them using a LEFT JOIN to find orphaned records, and either delete
these records or update them to restore referential integrity.
Answer: FULLTEXT indexes are used for full- text searches. You can create one with:
105. How can you check for index fragmentation on a table and defragment it?
Answer: You can check fragmentation using SHOW TABLE STATUS LIKE 'table_name';
and optimize (defragment) using OPTIMIZE TABLE table_name; .
Answer:
108. What are MySQL stored procedures and how do you use them?
Answer: Stored procedures are SQL codes saved in the database to be reused. Created
using CREATE PROCEDURE , and called via CALL procedure_name() .
109. How would you monitor the performance of your MySQL database in real-time?
110. How can you run SQL script from the command line without entering the MySQL
console?
Answer: Use:
Answer: EXPLAIN provides a query execution plan, showing how MySQL will execute
the query, which can be vital for optimization.
Answer: By adding the NOT NULL constraint during table creation or modification.
Answer:
116. How do you retrieve only a specified number of characters from a string column?
Answer:
117. What are views in MySQL and why are they used?
Answer: Views are virtual tables based on the result set of an SQL statement. They
encapsulate the SQL statement and present data in a simplified manner, ensuring data
abstraction, protection, and to represent a subset of the data.
Answer:
SELECT MAX(column_name)
FROM table_name
WHERE column_name NOT IN (SELECT MAX(column_name) FROM table_name);
These questions should serve well for interviews at product- based companies that expect a
deep understanding of MySQL.
krishnaik06 / The-Grand-Complete-Data-Science-Materials Public
main
Here is a list of 100+ advanced MySQL interview questions and providing detailed answers
1. How can you find the Nth highest salary from a table?
Answer:
Answer: JOIN is used to combine rows from two or more tables based on a related column
between them. Types of joins:
INNER JOIN: Returns records that have matching values in both tables.
LEFT JOIN (or LEFT OUTER JOIN): Returns all records from the left table, and the
matched records from the right table.
RIGHT JOIN (or RIGHT OUTER JOIN): Returns all records from the right table, and the
matched records from the left table.
FULL JOIN (or FULL OUTER JOIN): Returns all records when there's a match in one of
the tables.
3. How can you optimize a MySQL query?
Answer: CHAR has a fixed length whereas VARCHAR has a variable length. CHAR always
uses the same amount of storage space per entry, while VARCHAR uses only the space
required plus a small overhead.
5. Write a query to retrieve duplicate records from a table without using the DISTINCT
keyword.
Answer:
Answer: UNION combines the result sets of two or more queries and removes duplicates.
UNION ALL combines result sets but does not remove duplicates.
Answer: Use prepared statements with parameterized queries, escape user inputs, and
avoid using raw SQL queries with user input.
10. Write a query to find the second highest salary from a table.
Answer:
SELECT MAX(salary)
FROM employee
WHERE salary NOT IN (SELECT MAX(salary) FROM employee);
Answer:
Answer: ACID stands for Atomicity, Consistency, Isolation, and Durability. It ensures that
database transactions are processed reliably.
14. Write a query to find all employees who started after Jan 1, 2020, but before Jan 1,
2023.
Answer:
SELECT * FROM employees
WHERE start_date BETWEEN '2020-01-01' AND '2022-12-31';
Answer: A trigger is a set of instructions that are automatically executed (or fired) in
response to a specific event, such as inserting, updating, or deleting records in a table.
If you need more questions or further elaboration on any of the given questions, please let
me know!
Answer: A view is a virtual table based on the result set of an SQL statement. It contains
rows and columns from one or more tables. Views do not store data physically, but rather,
they provide a way to look at data in different ways without changing the underlying
schema.
Answer: Pagination can be implemented using the LIMIT and OFFSET clauses.
19. How can you find all tables that have specific column names in a database?
Answer:
SELECT table_name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'your_column_name'
AND TABLE_SCHEMA = 'your_database_name';
20. How can you backup and restore a MySQL database?
Answer: To backup:
To restore:
Answer: You can use the CONCAT function or the || operator (if the PIPES_AS_CONCAT
SQL mode is enabled).
22. How can you retrieve unique values from a column without using the DISTINCT
keyword?
Answer:
SELECT column_name
FROM table_name
GROUP BY column_name;
23. Explain the difference between a PRIMARY KEY and a UNIQUE constraint.
Answer: Both enforce uniqueness for the values in a column, but a table can have only one
primary key, whereas it can have multiple unique constraints. Additionally, primary keys
automatically create a clustered index on the column, whereas unique constraints create a
non-clustered index by default.
24. How can you create a copy of a table, including both structure and data, without using
any backup utilities?
Answer:
Answer:
SELECT FROM_UNIXTIME(your_unix_timestamp_column)
FROM your_table;
Answer: NOW() returns the current date and time, while CURRENT_DATE() returns only the
current date.
Answer:
SELECT LENGTH(column_name)
FROM table_name;
28. How do you delete all records from a table without deleting the table itself?
Answer:
Answer: GROUP_CONCAT function is used to concatenate values from multiple rows into a
single string. It's especially useful when used with GROUP BY .
Answer:
I hope these questions help. If you need more questions or any further clarifications, let me
know!
31. How would you retrieve the total count of rows, but only count each distinct value in a
column once?
Answer:
32. How would you find the three most frequent values in a column along with their
counts?
Answer:
33. Write a query to get the monthly sales amount for the last 12 months.
Answer:
34. Write a query to find employees who have managers with a salary greater than
$100,000.
Answer:
SELECT e1.*
FROM employees e1
INNER JOIN employees e2 ON e1.manager_id = e2.id
WHERE e2.salary > 100000;
35. How would you get the rank of students based on their scores in descending order?
Answer:
36. Find the employees who earn more than the average salary in their respective
departments.
Answer:
37. Retrieve all pairs of students who have the same scores.
Answer:
38. Write a query to retrieve the last 7 days' records, excluding weekends.
Answer:
SELECT *
FROM table_name
WHERE date_column BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDAT
AND DAYOFWEEK(date_column) NOT IN (1,7);
39. Find the employees who have the same job roles in different departments.
Answer:
Answer:
SELECT COALESCE(SUM(sales_amount), 0)
FROM sales;
These questions test the applicant's ability to write complex SQL queries, understand
advanced SQL functions, and combine multiple techniques into a single query. If you need
more questions or further details, feel free to ask!
41. How would you retrieve the name and salary of the top 3 earning employees?
Answer:
42. Find employees who earn above the average salary of their department and their
department's average salary is above the company's average.
Answer:
Answer:
SELECT department_id
FROM employees
GROUP BY department_id
HAVING COUNT(id) > (
SELECT AVG(employee_count)
FROM (
SELECT COUNT(id) as employee_count
FROM employees
GROUP BY department_id
) AS subquery
);
Answer:
SELECT MAX(avg_salary)
FROM (
SELECT department_id, AVG(salary) as avg_salary
FROM employees
GROUP BY department_id
) AS subquery
WHERE avg_salary < (
SELECT MAX(avg_salary)
FROM (
SELECT department_id, AVG(salary) as avg_salary
FROM employees
GROUP BY department_id
) AS subquery2
);
Answer:
Answer:
47. Find employees whose salary is above the median salary of the company.
Answer:
Answer:
49. Find the average salary of the departments which have more than five employees
earning above the overall average salary.
Answer:
50. Retrieve employees who have the same name as their manager.
Answer:
SELECT e1.name
FROM employees e1
WHERE e1.manager_id IS NOT NULL
AND e1.name = (
SELECT e2.name
FROM employees e2
WHERE e2.id = e1.manager_id
);
51. Determine if any department's average salary is higher than the maximum salary in
another department.
Answer:
SELECT d1.department_id
FROM employees e1
JOIN departments d1 ON e1.department_id = d1.department_id
WHERE (
SELECT AVG(e2.salary)
FROM employees e2
WHERE e2.department_id = d1.department_id
) > (
SELECT MAX(e3.salary)
FROM employees e3
WHERE e3.department_id != d1.department_id
)
LIMIT 1;
52. Find the employee who has the closest salary to the company's median salary but
doesn't earn the median salary.
Answer:
These deeply nested subqueries showcase the power of SQL when dissecting complex
requirements. They can often be found in analytical or reporting applications where data is
summarized or transformed in multi-step processes.
krishnaik06 / The-Grand-Complete-Data-Science-Materials Public
main
53. Retrieve the departments where the total salary expenditure exceeds the
average total salary expenditure across all departments.
Answer:
SELECT department_id
FROM employees
GROUP BY department_id
HAVING SUM(salary) > (
SELECT AVG(total_salary)
FROM (
SELECT department_id, SUM(salary) as total_salary
FROM employees
GROUP BY department_id
) AS subquery
);
54. Find the employee with the third highest salary without using the LIMIT clause.
Answer:
55. Identify departments that have less than the company-wide median number of
employees.
Answer:
SELECT department_id
FROM employees
GROUP BY department_id
HAVING COUNT(id) < (
SELECT AVG(employee_count)
FROM (
SELECT department_id, COUNT(id) as employee_count
FROM employees
GROUP BY department_id
) AS subquery
);
56. Get the most common job title among employees who earn above the company
average.
Answer:
SELECT job_title
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees)
GROUP BY job_title
ORDER BY COUNT(*) DESC
LIMIT 1;
57. Identify employees who earn more than the average salary in both their
department and the company.
Answer:
58. Retrieve the month (in numbers) with the highest total sales from a table of daily
sales.
Answer:
59. Get the department that has the maximum difference between the highest and
lowest salaries.
Answer:
60. Find the employee who earns the median salary in each department.
Answer:
61. Retrieve employees who earn more than their respective department's median
salary.
Answer:
62. Identify the departments where the minimum salary is greater than the maximum
salary of at least one other department.
Answer:
Answer:
64. Identify the department with the most diverse salary distribution, i.e., the largest
difference between the highest and lowest salaries.
Answer:
SELECT department_id
FROM employees
GROUP BY department_id
HAVING (MAX(salary) - MIN(salary)) = (
SELECT MAX(salary_range)
FROM (
SELECT (MAX(salary) - MIN(salary)) as salary_range
FROM employees
GROUP BY department_id
) AS subquery
);
65. Retrieve the employees who do not have the lowest salary in their department
but earn less than the department average.
Answer:
66. Determine which departments have an average salary close to the company's
median salary. Assume 'close' means a difference of less than 1000.
Answer:
SELECT department_id
FROM employees
GROUP BY department_id
HAVING ABS(AVG(salary) - (
SELECT AVG(median_salary)
FROM (
SELECT salary AS median_salary
FROM employees
ORDER BY salary
LIMIT 2 - (SELECT COUNT(*) FROM employees) MOD 2
OFFSET (SELECT (COUNT(*) - 1) / 2 FROM employees)
) AS median_subquery
)) < 1000;
67. Find the departments where the total number of employees is above the
company's average.
Answer:
SELECT department_id
FROM employees
GROUP BY department_id
HAVING COUNT(id) > (
SELECT AVG(employee_count)
FROM (
SELECT COUNT(id) AS employee_count
FROM employees
GROUP BY department_id
) AS avg_subquery
);
68. Identify employees who earn more than the second highest earner in their
respective department.
Answer:
SELECT e1.name, e1.salary, e1.department_id
FROM employees e1
WHERE e1.salary > (
SELECT MAX(e2.salary)
FROM employees e2
WHERE e2.department_id = e1.department_id AND e2.salary < (
SELECT MAX(e3.salary)
FROM employees e3
WHERE e3.department_id = e1.department_id
)
);
69. Find the departments where the top earner makes at least twice as much as the
second top earner.
Answer:
SELECT department_id
FROM employees
GROUP BY department_id
HAVING MAX(salary) >= 2 * (
SELECT MAX(salary)
FROM employees e2
WHERE e2.department_id = employees.department_id AND salary < MAX(emp
);
70. Retrieve the employees who have been in the company for longer than the
average tenure of their respective department managers.
Answer:
Answer:
SELECT department_id
FROM employees
GROUP BY department_id
HAVING (AVG(salary) - MIN(salary)) = (
SELECT MIN(gap)
FROM (
SELECT (AVG(salary) - MIN(salary)) AS gap
FROM employees
GROUP BY department_id
) AS gap_subquery
);
**72. Identify the employees who earn below the average salary of their p
**Answer**:
```sql
SELECT e1.name, e1.salary, YEAR(e1.join_date) AS join_year
FROM employees e1
WHERE e1.salary < (
SELECT AVG(e2.salary)
FROM employees e2
WHERE YEAR(e2.join_date) = YEAR(e1.join_date)
);
73. Retrieve the employee who has the closest salary to their department's median
but isn't the median earner.
Answer:
74. Determine the departments whose average tenure (time since joining) is greater
than the company average.
Answer:
SELECT department_id
FROM employees
GROUP BY department_id
HAVING AVG(DATEDIFF(CURDATE(), join_date)) > (
SELECT AVG(DATEDIFF(CURDATE(), join_date))
FROM employees
);
75. Identify departments where more than half of the employees earn above the
company's median salary.
Answer:
SELECT e1.department_id
FROM employees e1
WHERE e1.salary > (
SELECT AVG(median_salary)
FROM (
SELECT salary AS median_salary
FROM employees
ORDER BY salary
LIMIT 2 - (SELECT COUNT(*) FROM employees) MOD 2
OFFSET (SELECT (COUNT(*) - 1) / 2 FROM employees)
) AS median_subquery
)
GROUP BY e1.department_id
HAVING COUNT(e1.id) > 0.5 * (
SELECT COUNT(*)
FROM employees e2
WHERE e2.department_id = e1.department_id
);
76. Find employees who earn a salary in the top 3 of their department but are not in
the top 10 company-wide.
Answer:
77. Identify employees whose salary is above the average salary of the two
departments with the highest average salaries.
Answer:
78. Find employees who have a manager earning less than the lowest salary in their
department.
Answer:
79. Identify the department with the least difference between the top earner and the
average salary of the department.
Answer:
SELECT department_id
FROM employees
GROUP BY department_id
HAVING (MAX(salary) - AVG(salary)) = (
SELECT MIN(top_minus_avg)
FROM (
SELECT (MAX(salary) - AVG(salary)) AS top_minus_avg
FROM employees
GROUP BY department_id
) AS difference_subquery
);
80. Retrieve the employees who have the same rank (in terms of salary) in their
department as they do in the company overall.
Answer:
81. Determine the departments where the third-highest earner makes more than
double the department's average salary.
Answer:
SELECT department_id
FROM employees e1
WHERE (
SELECT DISTINCT salary
FROM (
SELECT salary
FROM employees e2
WHERE e2.department_id = e1.department_id
ORDER BY e2.salary DESC
LIMIT 3
) AS third_top_salary_subquery
ORDER BY salary
LIMIT 1 OFFSET 2
) > 2 * (
SELECT AVG(e3.salary)
FROM employees e3
WHERE e3.department_id = e1.department_id
)
GROUP BY department_id;
82. Find employees who have more direct reports (subordinates) than their manager.
Answer:
SELECT e1.name
FROM employees e1
WHERE (
SELECT COUNT(*)
FROM employees e2
WHERE e2.manager_id = e1.id
) > (
SELECT COUNT(*)
FROM employees e3
WHERE e3.manager_id = e1.manager_id
);