DAY 20: SQL - Views, Stored Procedures, Optimization + WEEK 4 TEST
Learning Objectives: - Create and manage Views - Write basic Stored Procedures - Understand query execution plans - Apply indexing strategies - Review Week 4 concepts
Topics Covered (60 min):
1. Views
- Virtual tables based on query
- CREATE VIEW view_name AS SELECT ...
- Simplify complex queries
- Security: hide underlying table structure
- Can SELECT from views like tables
2. Stored Procedures
- Saved SQL code with parameters
- CREATE PROCEDURE proc_name @param datatype AS BEGIN ... END
- Execute: EXEC proc_name @param = value
- Benefits: reusability, security, performance
- Can include logic, variables, loops
3. Query Optimization Basics - Execution plans (Ctrl+L in SSMS) - Identify costly operations - Use indexes on WHERE, JOIN columns - Avoid SELECT *, use specific columns - WHERE before JOIN when possible
4. Indexing
- CREATE INDEX idx_name ON table(column)
- Clustered vs Non-clustered indexes
- Speed up searches, slow down inserts
- Index columns used in WHERE, JOIN, ORDER BY
- Don't over-index
Video Resources:
-
Advanced SQL for Beginners | Views & Indexes Explained (01:00)
https://www.youtube.com/watch?v=OcGFNYZ8osY -
Mastering SQL Views 2025 (2:29)
https://www.youtube.com/watch?v=hzG7ZVWONfc -
SQL Indexes Explained in 20 Minutes (10:00)
https://www.youtube.com/watch?v=5t1fW3KG920
AI Learning Prompts (Concept Understanding Only):
Understanding Views and Procedures:
I'm learning SQL Views and Stored Procedures. Please explain:
1. What is a View and when should I use it?
2. How are Views different from tables?
3. What is a Stored Procedure and what are its benefits?
4. Show me how to create a simple procedure with parameters
5. Provide examples using customer and sales data
Use SQL Server syntax with practical examples.
Understanding Query Optimization:
Help me understand SQL query optimization:
1. What is an execution plan and how do I read it?
2. When should I create an index?
3. What is the difference between clustered and non-clustered indexes?
4. Show me common query performance problems and solutions
5. Provide best practices for writing efficient queries
Explain with beginner-friendly examples.
Guided Practice (60 min):
📝 How to approach Guided Practice:
- Follow step-by-step: Work through each exercise in order
- Use provided resources: Reference the video tutorials and AI prompts if you get stuck
- Verify your work: Check your results match expected outcomes
- Take notes: Document key learnings and shortcuts you discover
- Ask for help: Use AI assistants to clarify concepts you don't understand
Exercise 1: Create a VIEW for Reusable Queries
Goal: Learn to create views that simplify complex queries and provide consistent data access.
Step-by-Step Instructions:
- Understand views: A view is a saved SELECT query that acts like a virtual table
- Create a sales summary view:
CREATE VIEW vw_SalesSummary AS SELECT CustomerID, CustomerName, COUNT(*) AS OrderCount, SUM(Sales) AS TotalSales, AVG(Sales) AS AvgOrderValue FROM Orders O INNER JOIN Customers C ON O.CustomerID = C.CustomerID GROUP BY CustomerID, CustomerName; - Use the view like a table:
SELECT * FROM vw_SalesSummary WHERE TotalSales > 10000; - Drop and recreate view:
DROP VIEW IF EXISTS vw_SalesSummary; CREATE VIEW vw_SalesSummary AS -- Updated version with new column SELECT CustomerID, CustomerName, COUNT(*) AS OrderCount, SUM(Sales) AS TotalSales, MAX(OrderDate) AS LastOrderDate FROM Orders O INNER JOIN Customers C ON O.CustomerID = C.CustomerID GROUP BY CustomerID, CustomerName;
💡 Tips:
- Views don't store data: They execute the underlying query each time
- Naming convention: Use vw_ prefix to identify views
- Security benefit: Grant access to view instead of underlying tables
- Simplification: Hide complex JOINs from end users
- Performance: Views don't improve performance by themselves
✅ Expected Result: Views created and queryable like regular tables
Exercise 2: Create a Stored Procedure with Parameters
Goal: Write reusable SQL logic with parameters for dynamic execution.
Step-by-Step Instructions:
- Create basic stored procedure:
CREATE PROCEDURE sp_GetCustomerOrders @CustomerID INT AS BEGIN SELECT OrderID, OrderDate, Sales, ProductName FROM Orders O INNER JOIN Products P ON O.ProductID = P.ProductID WHERE O.CustomerID = @CustomerID ORDER BY OrderDate DESC; END; - Execute the stored procedure:
EXEC sp_GetCustomerOrders @CustomerID = 123; - Create procedure with multiple parameters:
CREATE PROCEDURE sp_GetSalesByDateRange @StartDate DATE, @EndDate DATE, @MinSales DECIMAL(10,2) = 0 AS BEGIN SELECT OrderDate, SUM(Sales) AS DailySales FROM Orders WHERE OrderDate BETWEEN @StartDate AND @EndDate GROUP BY OrderDate HAVING SUM(Sales) >= @MinSales; END;
💡 Tips:
- Parameters: Can have default values (e.g., @MinSales = 0)
- Benefits: Reusable, parameterized, can include logic
- Security: Prevents SQL injection when used properly
- Performance: Execution plans cached for faster runs
- Debugging: Use PRINT statements to output variable values
✅ Expected Result: Stored procedures callable with parameters
Exercise 3: Create and Use Indexes for Performance
Goal: Understand indexing and create indexes to speed up queries.
Step-by-Step Instructions:
- Create a non-clustered index:
CREATE INDEX idx_Orders_CustomerID ON Orders(CustomerID); - Create composite index:
CREATE INDEX idx_Orders_Date_Customer ON Orders(OrderDate, CustomerID); - Test performance difference:
-- Check execution time before/after SELECT * FROM Orders WHERE CustomerID = 123; - Drop index if needed:
DROP INDEX idx_Orders_CustomerID ON Orders;
💡 Tips:
- When to index: Columns in WHERE, JOIN, ORDER BY clauses
- Trade-off: Indexes speed reads but slow writes
- Don't over-index: Each index uses storage
- Column order matters: Most selective column first in composite indexes
- Unique index: Use CREATE UNIQUE INDEX to enforce uniqueness
✅ Expected Result: Indexes created, queries run faster
Exercise 4: Analyze Query Execution Plans
Goal: Learn to read execution plans to identify bottlenecks.
Step-by-Step Instructions:
- Use EXPLAIN (PostgreSQL/MySQL):
EXPLAIN SELECT * FROM Orders WHERE OrderDate > '2024-01-01'; - Analyze a complex query:
EXPLAIN ANALYZE SELECT C.CustomerName, SUM(O.Sales) AS TotalSales FROM Orders O INNER JOIN Customers C ON O.CustomerID = C.CustomerID WHERE O.OrderDate >= '2024-01-01' GROUP BY C.CustomerName HAVING SUM(O.Sales) > 10000; - Look for problems: Table scans, high cost operations, missing indexes
💡 Tips:
- Table scan vs Index seek: Scan is bad (reads all), Seek is good (uses index)
- Focus on high cost: Operations with >10% cost
- Actual vs Estimated: Use EXPLAIN ANALYZE for actual stats
- Common fixes: Add indexes, rewrite query, update statistics
- Compare before/after: Check plan after adding indexes
✅ Expected Result: Ability to read plans and identify issues
Exercise 5: Query Optimization Best Practices
Goal: Apply best practices to write efficient SQL queries.
Step-by-Step Instructions:
- Use EXISTS instead of IN:
-- Faster for large datasets SELECT * FROM Customers C WHERE EXISTS (SELECT 1 FROM Orders O WHERE O.CustomerID = C.CustomerID); - Avoid SELECT *:
-- Only select needed columns SELECT OrderID, OrderDate, Sales FROM Orders; - Use WHERE instead of HAVING:
-- Filter before aggregation when possible SELECT Category, COUNT(*) FROM Products WHERE Category = 'Electronics' GROUP BY Category; - Avoid functions on indexed columns:
-- Use range instead of function SELECT * FROM Orders WHERE OrderDate >= '2024-01-01' AND OrderDate < '2025-01-01';
💡 Tips:
- Limit result sets: Use TOP/LIMIT during testing
- Batch operations: INSERT/UPDATE many rows at once
- Use appropriate data types: Smaller types improve performance
- Update statistics: Keep table stats current
- Monitor slow queries: Use query logs to find optimization candidates
✅ Expected Result: Understanding of optimization techniques
🔄 Connection to Excel: Like optimizing Excel formulas - avoid volatile functions, use efficient calculations!
Independent Practice (60 min):
💡 Hints for Independent Practice:
- Start simple: Begin with basic variations before attempting complex modifications
- Break it down: Divide complex problems into smaller, manageable steps
- Test incrementally: Verify each step works before moving to the next
- Use documentation: Refer to official docs or tutorials when needed
- Experiment: Try different approaches to find what works best
Apply the concepts learned to different datasets and scenarios.
Daily Assignment (60 min):
Assignment:
- Stored Procedure:Create procedure to get sales by date range with parameters
- Optimization:Analyze slow query, add appropriate indexes, compare before/after performance
Expected Outcomes:
- Create and manage Views
- Write basic Stored Procedures
- Understand query execution plans
- Apply indexing strategies
- Review Week 4 concepts
📝 Day 20 Quick Quiz - Test Your Knowledge!
Q1. What is a SQL View?
Q2. What is a Stored Procedure?
Q3. What's a key benefit of using indexes?
Q4. What is query optimization?
Q5. Why might too many indexes hurt performance?