To find the second-highest salary, we can use the LIMIT clause with a subquery.
SELECT MAX(salary) AS second_highest_salary FROM Employees WHERE salary < (SELECT MAX(salary) FROM Employees);
The subquery (SELECT MAX(salary) FROM Employees) finds the highest salary.
The main query finds the maximum salary that is less than the highest salary, giving us the second-highest salary.
Optimizing a slow SQL query involves several strategies, including:
Indexing: Create indexes on columns that are frequently used in WHERE, JOIN, ORDER BY, or GROUP BY clauses.
*Avoiding SELECT : Instead of selecting all columns, select only the columns you need.
Using Joins Efficiently: Replace subqueries with joins wherever possible, as joins are generally faster.
Query Refactoring: Simplify complex queries by breaking them down into smaller subqueries or using common table expressions (CTEs).
Checking Execution Plan: Use tools like EXPLAIN or EXPLAIN ANALYZE to view the query execution plan and identify bottlenecks.
Example: If you have a query like:
SELECT * FROM Orders WHERE customer_id = 5;
You can optimize it by adding an index on the customer_id column:
CREATE INDEX idx_customer_id ON Orders(customer_id);
INNER JOIN returns only the rows that have matching values in both tables.
OUTER JOIN can be of three types:
LEFT OUTER JOIN: Returns all rows from the left table and the matched rows from the right table. If no match is found, NULL is returned.
RIGHT OUTER JOIN: Returns all rows from the right table and the matched rows from the left table. If no match is found, NULL is returned.
FULL OUTER JOIN: Returns all rows when there is a match in either left or right table. If no match is found, NULL values are returned for the unmatched rows.
Employees
Departments
SELECT Employees.name, Departments.dept_name FROM Employees INNER JOIN Departments ON Employees.dept_id = Departments.dept_id;
SELECT Employees.name, Departments.dept_name FROM Employees RIGHT JOIN Departments ON Employees.dept_id = Departments.dept_id;
INNER JOIN returns rows where dept_id is 10 and 20.
LEFT JOIN returns all employees with NULL for unmatched departments (if any).
RIGHT JOIN returns all departments with NULL for unmatched employees.
Employees
Departments
SELECT d.dept_name, AVG(e.salary) AS avg_salary FROM Employees e JOIN Departments d ON e.dept_id = d.dept_id GROUP BY d.dept_name ORDER BY avg_salary DESC LIMIT 3;
We join Employees and Departments on dept_id.
Group by department and calculate the average salary.
Sort by average salary in descending order and limit the result to the top 3 departments.
To handle duplicate rows, you can use the DISTINCT keyword, or you can remove duplicates using ROW_NUMBER() with a CTE.
SELECT DISTINCT customer_id, product FROM Orders; SELECT name, dept_id, COUNT(*) FROM Employees GROUP BY name, dept_id HAVING COUNT(*) > 1;
We group by name and dept_id.
Use HAVING COUNT(*) > 1 to filter out names that appear more than once in the same department.
UNION: Combines the results of two or more SELECT statements and removes duplicates.
UNION ALL: Combines the results of two or more SELECT statements without removing duplicates.
UNION will return unique names from both tables: John, Jane, Mike.
UNION ALL will return all names including duplicates: John, Jane, Jane, Mike.
Employees
Departments
We perform a LEFT JOIN between Departments and Employees.
Filter where emp_id is NULL to find departments with no employees.
Indexing improves SQL query performance by allowing the database to find rows faster instead of scanning the entire table. Indexes can be created on columns that are frequently used in WHERE, JOIN, ORDER BY, or GROUP BY clauses.
Example: If you have a table Orders and often query by customer_id, you can create an index:
CREATE INDEX idx_customer_id ON Orders(customer_id);
This index will speed up queries like:
SELECT * FROM Orders WHERE customer_id = 123;
Subquery: A query nested inside another query. It can return a single value or a result set that can be used in the main query.
JOIN: Combines rows from two or more tables based on a related column between them.
Subquery is often used when you need to filter results based on an aggregated value or other criteria from a different table.
JOIN is used to retrieve related data from multiple tables in a single query.
Stored procedures can improve SQL query performance by:
Precompilation: Stored procedures are compiled and stored in the database, which speeds up execution.
Reduced Network Traffic: A stored procedure can execute multiple queries at once, reducing the number of calls between the application and the database.
Reusability: Stored procedures can be reused across different applications, ensuring consistency and reducing development time.
This stored procedure GetEmployeeDetails accepts an emp_id as input and returns the corresponding employee’s details.
GROUP BY: Groups rows that have the same values in specified columns into aggregate data.
HAVING: Filters the result set after grouping. It’s similar to WHERE but used for aggregate functions.
GROUP BY groups orders by customer_id.
HAVING filters out customers with a total order amount of 600 or less.
Window functions are used to perform calculations across a set of table rows related to the current row. Unlike aggregate functions, window functions do not cause rows to become grouped into a single output row.
DELETE: Removes rows from a table based on a WHERE condition. It can be rolled back and triggers can fire.
TRUNCATE: Removes all rows from a table without logging individual row deletions. It cannot be rolled back and is faster than DELETE.
Employees
Leaves
These 20 SQL interview questions cover a wide range of concepts and techniques that are essential for anyone looking to strengthen their SQL skills. By understanding these questions and practicing the provided examples, you’ll be better prepared to tackle medium-level SQL queries in interviews and real-world scenarios.
20 Sentences That Will Sharpen Your Analytical Thinking: Elevate Your Problem-Solving Skills In today’s fast-paced…
What is ETL? A Comprehensive Guide to Extract, Transform, Load In today's data-driven world, businesses…
Artificial intelligence (AI) has become a powerful tool for accelerating learning. Whether you’re mastering a…
When preparing for the PMP® (Project Management Professional) exam, finding the right study materials and…
NVIDIA Launches Free AI Courses: Top 6 Courses to Explore in 2024 NVIDIA has just…
Running a business is both rewarding and challenging. As an entrepreneur or business leader, you…