✅ 1. How do you optimize a slow SQL query?
When optimizing a slow SQL query, I typically follow these steps:
-
Analyze the Execution Plan: Use
EXPLAIN
(MySQL, PostgreSQL) orQuery Plan
tools (SQL Server) to understand how the query is executed — look for full table scans, expensive joins, or missing indexes. -
Add Proper Indexes: Ensure frequently filtered or joined columns are indexed to reduce data scans.
-
**Avoid SELECT ***: Always select only the necessary columns to reduce the amount of data fetched.
-
Optimize Joins: Use the right type of join (INNER, LEFT, etc.) and ensure join columns are indexed.
-
Use WHERE Clauses Effectively: Filter data early using WHERE clauses instead of filtering after joins or in application code.
-
Partitioning: Break large tables into partitions if possible, to reduce scanned data.
-
Limit Subqueries & Nested Loops: Rewrite subqueries as joins or common table expressions (CTEs) if they perform better.
✅ 2. What is indexing in SQL, and how does it improve performance?
An index is a database structure that improves the speed of data retrieval operations. It works like the index in a book — rather than scanning every row, the database can go directly to the relevant data.
-
Without an index, the database performs a full table scan.
-
With an index, it can quickly locate the position of the desired data, which significantly reduces I/O and speeds up queries — especially for large datasets.
Common types:
-
B-Tree Index (default in most databases)
-
Bitmap Index (good for columns with low cardinality)
-
Full-Text Index (for text searching)
-
Clustered / Non-Clustered Indexes (SQL Server)
✅ 3. Write an SQL query to find customers who have placed more than 3 orders.
Assuming you have two tables: Customers
and Orders
This query:
-
Joins
Customers
andOrders
. -
Groups results by customer.
-
Filters using
HAVING
to return only those with more than 3 orders.
✅ 4. How do you calculate the percentage of total sales for each category?
Assuming you have a Sales
table with Category
and SalesAmount
:
This:
-
Calculates total sales per category.
-
Divides each category total by the overall total.
-
Multiplies by 100 to get the percentage.
✅ 5. What is the use of CASE statements in SQL?
The CASE
statement is used to implement conditional logic inside SQL queries, similar to IF-THEN-ELSE
in programming.
It allows you to:
-
Transform values on the fly.
-
Create custom groupings.
-
Replace
NULL
or missing values. -
Implement conditional aggregations.
Example: Label orders based on their total:
No comments:
Post a Comment