Saturday, April 19, 2025

Adv sql

 ✅ 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) or Query 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

SELECT c.CustomerID, c.CustomerName, COUNT(o.OrderID) AS TotalOrders
FROM Customers c JOIN Orders o ON c.CustomerID = o.CustomerID GROUP BY c.CustomerID, c.CustomerName HAVING COUNT(o.OrderID) > 3;

This query:

  • Joins Customers and Orders.

  • 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:

SELECT
Category, SUM(SalesAmount) AS CategoryTotal, ROUND(SUM(SalesAmount) * 100.0 / (SELECT SUM(SalesAmount) FROM Sales), 2) AS PercentageOfTotal FROM Sales GROUP BY Category;

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:

SELECT
OrderID, OrderAmount, CASE WHEN OrderAmount >= 1000 THEN 'High Value' WHEN OrderAmount >= 500 THEN 'Medium Value' ELSE 'Low Value' END AS OrderCategory FROM Orders;



Mastering Conditional Aggregation in SQL: Conditional aggregation is a powerful SQL technique that lets you perform aggregate functions based on specific conditions. This approach allows you to calculate values more selectively, adding flexibility to your data analysis. Let's break it down with examples to see how you can leverage this method in SQL. πŸ“ What Is Conditional Aggregation? Standard aggregation functions like SUM(), COUNT(), and AVG() summarize data across rows without any distinction. However, there are times when you only want to aggregate data that meets certain conditions. Conditional aggregation helps with that by applying aggregate functions based on specific criteria. πŸ“ Example: Sales Data Analysis Let’s say you have a table called sales with information on store sales: store ID (stor_id), quantity sold (qty), and order date (ord_date). You want to calculate total sales for each store in the year 1993. πŸ“Example 1: Total Sales in 1993 SELECT stor_id, SUM(CASE WHEN YEAR(ord_date) = 1993 THEN qty ELSE 0 END) AS total_sales FROM sales GROUP BY stor_id ORDER BY total_sales DESC; Here, the SUM() function aggregates only the sales data from 1993 by using a CASE statement. Rows from other years contribute 0 to the total. #### Example 2: Average Monthly Sales in 1993 SELECT stor_id, MONTH(ord_date) AS month, AVG(CASE WHEN YEAR(ord_date) = 1993 THEN qty ELSE 0 END) AS avg_sales FROM sales WHERE YEAR(ord_date) = 1993 GROUP BY stor_id, month ORDER BY stor_id; In this query, we calculate the average monthly sales for each store in 1993. The AVG() function works conditionally by including only rows from that year. We use WHERE to filter out irrelevant data, focusing on the year 1993. πŸ“ Example 3: Categorizing Sales SELECT stor_id, SUM(CASE WHEN YEAR(ord_date) = 1993 THEN qty ELSE 0 END) AS total_sales_1993, CASE WHEN SUM(CASE WHEN YEAR(ord_date) = 1993 THEN qty ELSE 0 END) < 1000 THEN 'Low Sales' WHEN SUM(CASE WHEN YEAR(ord_date) = 1993 THEN qty ELSE 0 END) BETWEEN 1000 AND 5000 THEN 'Medium Sales' ELSE 'High Sales' END AS sales_category FROM sales GROUP BY stor_id; This query goes one step further by creating a new column that categorizes stores based on their total sales in 1993. We use a CASE statement to label the sales as 'Low', 'Medium', or 'High' based on specific thresholds. πŸ“ Key Takeaways - Conditional aggregation allows you to apply functions like SUM(), AVG(), and others based on specific criteria. - Using CASE statements inside aggregate functions gives you control over which rows contribute to the result. - Conditional aggregation is useful for more tailored insights, such as filtering by specific timeframes, creating categories, and more. Incorporating these techniques into your #SQL queries enhances your ability to extract meaningful, granular insights from your data.
Start experimenting with conditional aggregation to take your SQL analysis to the next level!

No comments:

Post a Comment

Python using AI

  Python using AI - Prompts & Codes Tools useful for Python + AI ChatGPT - https://chatgpt.com/ Claude AI - https://claude.ai/new ...