Views Functions and Stored Procedures
Earn 25 points (50 with Pro) in two steps
- ① Read through the lesson — each section gets a ✓ as you scroll through it.
- ② When every section has a ✓, tap Complete lesson.
0 of 8 read · keep scrolling
✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro
Mastering Data Transformation: Views, Functions, and Stored Procedures
Introduction: The Architecture of Data Transformation
When you work with relational databases, your primary goal is rarely just to store raw information. Instead, you are almost always building a system designed to retrieve, calculate, and present data in a way that answers specific business questions. While simple SELECT statements are the bread and butter of SQL, they quickly become unmanageable as your database grows in complexity. If you find yourself rewriting the same complicated join logic or repeating the same mathematical calculations across five different reports, you are creating technical debt that will eventually slow down your development and introduce data inconsistencies.
This is where the database layer’s programmatic tools—Views, Functions, and Stored Procedures—become essential. These objects allow you to encapsulate logic directly within the database engine. By moving the "how" of data retrieval into the database itself, you ensure that every application, report, or analyst using that data is getting the same result, calculated in the same way. This lesson explores these three foundational components, detailing how they work, when to use them, and how to structure them for performance and maintainability.
Not read yet
1. Understanding Views: The Virtual Table
A View is essentially a saved SQL query. When you create a view, you are not creating a new table that stores physical data; rather, you are creating a virtual table that acts as a window into your existing data. When you query a view, the database engine executes the underlying query defined in the view's definition.
Why Use Views?
Views are primarily used for three reasons: security, simplification, and consistency. From a security standpoint, you can grant a user access to a view that selects only specific columns, effectively hiding sensitive information like social security numbers or salary data from unauthorized eyes. From a simplification standpoint, you can hide the complexity of a five-table join behind a single name. If a developer needs to query "Active Customer Orders," they don't need to know the schema of the Orders, Customers, Products, and Order_Items tables; they simply query the view.
Creating and Managing Views
Creating a view is straightforward. You use the CREATE VIEW statement followed by your SELECT query.
CREATE VIEW active_customer_orders AS
SELECT
c.customer_name,
o.order_date,
p.product_name,
oi.quantity
FROM Customers c
JOIN Orders o ON c.customer_id = o.customer_id
JOIN Order_Items oi ON o.order_id = oi.order_id
JOIN Products p ON oi.product_id = p.product_id
WHERE o.status = 'Shipped';
Once this view is created, you can interact with it just like any other table: SELECT * FROM active_customer_orders WHERE customer_name = 'Acme Corp';. The database engine will combine your WHERE clause with the view's internal query logic to produce the result.
Callout: Views vs. Materialized Views A standard view is "virtual"—it calculates the result every time you query it. A Materialized View, conversely, stores the result of the query physically on the disk. Use standard views for real-time data accuracy, and use materialized views when the underlying query is extremely heavy and the data does not need to be updated second-by-second.
Common Pitfalls with Views
One common mistake is creating "nested views," where View A relies on View B, which relies on View C. While this can seem organized, it often leads to performance degradation and makes debugging extremely difficult. If a report is running slowly, tracing the performance bottleneck through three layers of abstraction is a nightmare. Keep your view definitions flat and focused on specific business entities whenever possible.
Not read yet
2. User-Defined Functions (UDFs): Encapsulating Logic
While views are designed to return sets of data, functions are designed to perform calculations or transformations. A User-Defined Function (UDF) is a routine that accepts parameters, performs a calculation, and returns a single value or, in some cases, a table.
Scalar Functions vs. Table-Valued Functions
There are two primary types of functions you will encounter:
- Scalar Functions: These return a single value (like an integer, string, or date). They are perfect for consistent formatting or mathematical operations that need to be reused.
- Table-Valued Functions (TVFs): These return a result set. Unlike a view, these can accept input parameters, making them dynamic.
Implementing a Scalar Function
Imagine you need to calculate the tax on an order across your entire database. Instead of writing (price * 0.08) in every query, you can create a function.
CREATE FUNCTION dbo.CalculateTax (@Price DECIMAL(10,2))
RETURNS DECIMAL(10,2)
AS
BEGIN
RETURN @Price * 0.08;
END;
Now, you can use this function in any SELECT statement:
SELECT product_name, dbo.CalculateTax(price) AS tax_amount FROM Products;
Implementing a Table-Valued Function
TVFs are incredibly powerful because they act like parameterized views. If you have a view that shows all orders, but you want to filter by date range dynamically, a TVF is the perfect tool.
CREATE FUNCTION dbo.GetOrdersByDateRange (@StartDate DATE, @EndDate DATE)
RETURNS TABLE
AS
RETURN (
SELECT * FROM Orders
WHERE order_date BETWEEN @StartDate AND @EndDate
);
Note: Be cautious when using scalar functions in the
WHEREclause of a query that processes millions of rows. Because the database engine must execute the function for every single row to determine if it meets the criteria, this can prevent the engine from using indexes, leading to a significant performance hit known as a "row-by-row" or "RBAR" operation.
Not read yet
3. Stored Procedures: The Powerhouse of Automation
Stored procedures are the most robust tool in the SQL programmer's toolkit. Unlike views or functions, which are primarily designed to return data, stored procedures can perform complex tasks, including data manipulation (INSERT, UPDATE, DELETE), transaction management, and conditional logic.
Why Use Stored Procedures?
Stored procedures are excellent for batch processing and security. Because you can grant a user permission to execute a stored procedure without giving them direct access to the underlying tables, you create a controlled interface for data interaction. Furthermore, stored procedures are pre-compiled by the database engine, which can lead to better execution plans and faster performance for complex tasks.
Structure of a Stored Procedure
A stored procedure can include variables, loops, IF/ELSE logic, and error handling. Here is a practical example of a procedure that handles a common task: updating inventory levels after an order is placed.
CREATE PROCEDURE UpdateInventory
@ProductID INT,
@QuantitySold INT
AS
BEGIN
-- Start a transaction to ensure data integrity
BEGIN TRANSACTION;
BEGIN TRY
UPDATE Products
SET stock_level = stock_level - @QuantitySold
WHERE product_id = @ProductID;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION;
-- Log the error here
PRINT 'Error: Inventory update failed.';
END CATCH
END;
Best Practices for Stored Procedures
- Use Meaningful Names: Prefix your procedures (e.g.,
usp_for User Stored Procedure) to distinguish them from system procedures. - Keep it Focused: A stored procedure should do one thing well. Avoid "God Procedures" that attempt to handle every possible business scenario for a module; they become impossible to test and maintain.
- Handle Errors: Always use
TRY...CATCHblocks. If an operation fails, you want the database to roll back to a clean state rather than leaving data in a corrupted or half-updated condition. - Use Parameters: Never hardcode values into your procedure. Always pass them as arguments to make the procedure reusable.
Callout: The Difference Between Functions and Procedures The most important distinction is that functions are designed to be used inside queries (to return a value or a table), whereas procedures are standalone commands. You cannot call a stored procedure within a
SELECTstatement, but you can call a function. Use functions for calculations and procedures for actions.
Not read yet
4. Comparing the Tools: A Quick Reference
To help you decide which tool is appropriate for your current task, use the following table as a guide.
| Feature | View | User-Defined Function | Stored Procedure |
|---|---|---|---|
| Primary Goal | Simplify complex queries | Perform calculations/transformations | Execute business logic/actions |
| Can use DML (INSERT/UPDATE)? | Yes (with limitations) | No | Yes |
| Accepts Parameters? | No | Yes | Yes |
| Can be used in SELECT? | Yes | Yes (Scalar/TVF) | No |
| Supports Transactions? | No | No | Yes |
5. Advanced Considerations: Performance and Security
As your database usage scales, the way you implement these objects will have a direct impact on how your application performs and how secure your information remains.
Performance Tuning
One of the most common mistakes is the misuse of functions in joins. If you join two tables based on the output of a function, the database engine often cannot use indexes on the columns involved in that function. For example, if you have a Users table and you join it to an Orders table using WHERE YEAR(user_signup_date) = 2023, the database must calculate the year for every row in the Users table. If you have 10 million users, this will be slow. Instead, use a range query: WHERE user_signup_date >= '2023-01-01' AND user_signup_date < '2024-01-01'.
Security and Permissions
Stored procedures are your best friend for security. By using the EXECUTE AS clause, you can allow a user to run a procedure that modifies data, even if that user does not have direct write access to the table. This is known as "ownership chaining." It allows you to enforce strict business rules—for example, you can ensure that inventory can never drop below zero by checking the current stock inside the stored procedure, even if the user has no direct table permissions.
Common Pitfalls to Avoid
- The "Black Box" Problem: If you hide too much logic inside stored procedures, it becomes difficult for other developers to understand what is happening to the data. Always document your procedures thoroughly.
- Ignoring Execution Plans: If a query within a view is slow, use the database engine's "Explain Plan" or "Execution Plan" tool to see where the bottleneck is. It might be a missing index on a join column, which a view cannot fix on its own.
- Over-Engineering: Do not create a function for a simple calculation that will only be used once. Keep your database clean by only adding objects that provide clear, reusable value.
- Hardcoding Constants: Never hardcode business rules like tax rates or currency conversion factors inside procedures or functions. These should ideally reside in a configuration table so they can be updated without changing the code itself.
Not read yet
6. Step-by-Step: Building a Robust Data Transformation Layer
Let’s walk through a real-world scenario. Suppose you are building a reporting system for an e-commerce platform. You need a way to calculate total sales per region, but the data is spread across Orders, Addresses, and Regions.
Step 1: Create a View for Data Normalization
First, create a view that flattens the relationship between orders and regions. This makes the data easier to work with for all future reports.
CREATE VIEW vw_OrderGeography AS
SELECT
o.order_id,
o.total_amount,
a.region_name
FROM Orders o
JOIN Addresses a ON o.address_id = a.address_id;
Step 2: Create a Function for Currency Conversion
Since you have international customers, you need a way to convert the total_amount into the user's local currency.
CREATE FUNCTION dbo.fn_ConvertToLocalCurrency (@Amount DECIMAL(18,2), @Rate DECIMAL(10,4))
RETURNS DECIMAL(18,2)
AS
BEGIN
RETURN @Amount * @Rate;
END;
Step 3: Create a Stored Procedure for Monthly Reporting
Finally, create a stored procedure that generates a summary report for a specific month and region. This procedure will use both the view and the function.
CREATE PROCEDURE usp_GetRegionalReport
@Month INT,
@Year INT,
@RegionName NVARCHAR(50)
AS
BEGIN
SELECT
region_name,
SUM(total_amount) AS total_usd,
SUM(dbo.fn_ConvertToLocalCurrency(total_amount, 0.92)) AS total_eur
FROM vw_OrderGeography
WHERE MONTH(order_date) = @Month
AND YEAR(order_date) = @Year
AND region_name = @RegionName
GROUP BY region_name;
END;
This modular approach is the hallmark of a professional database design. By separating the data access (View), the business calculation (Function), and the reporting logic (Stored Procedure), you have created a system that is easy to update and debug. If the tax rate changes, you only update the function. If the table schema changes, you only update the view.
Not read yet
7. Industry Standards and Maintenance
In a professional environment, managing these database objects requires more than just writing code; it requires a lifecycle approach.
Version Control
Database objects should be treated exactly like application code. Every view, function, and procedure should be stored in a version control system (like Git). Never make changes directly to a production database. Instead, write a migration script, test it in a development or staging environment, and then deploy it to production.
Documentation
Use standard SQL comments within your code to explain why a decision was made, not just what the code does.
- Bad comment:
-- Incrementing the counter - Good comment:
-- Incrementing the retry counter to handle intermittent API failures from the payment gateway.
Testing
Create unit tests for your functions. If you have a complex calculation function, write a script that passes in known inputs and verifies the expected output. If the function returns the wrong value after a database update, your test will catch it immediately.
Monitoring
Most modern database engines provide tools to monitor the performance of stored procedures. If you notice a procedure suddenly taking longer to run, check the execution plan. Often, data distribution changes over time, and an index that worked perfectly for 1,000 rows might be ineffective for 1,000,000 rows.
Not read yet
8. Summary: Key Takeaways
As we conclude this lesson, remember that the goal of using views, functions, and stored procedures is to create a clean, maintainable, and efficient interface between your raw data and your end-users.
- Views are for abstraction: Use them to simplify complex joins and to provide a security layer that limits access to specific columns or rows.
- Functions are for calculation: Use scalar functions for simple, repeatable logic and table-valued functions for parameterized, reusable result sets.
- Stored Procedures are for action: Use them to manage complex transactions, perform data modifications, and encapsulate multi-step business processes.
- Maintain performance: Be wary of using scalar functions in
WHEREclauses, as they can prevent the use of indexes and significantly slow down query execution. - Prioritize modularity: Keep your logic separated. If a procedure is doing too much, break it into smaller, more focused procedures that can be called in sequence.
- Think in sets: SQL is designed to handle sets of data. Whenever possible, avoid row-by-row processing (loops) in your procedures, as it is almost always slower than a set-based
SELECTorUPDATEstatement. - Security is paramount: Use stored procedures to grant access to data. This allows you to enforce business logic and protect sensitive information by controlling exactly how data is read or modified.
By mastering these three tools, you move from being a user of a database to being an architect of data. You are no longer just writing queries; you are building a system that provides reliable, consistent, and fast insights to your organization. Take the time to practice these concepts on your local machine, experiment with the performance differences, and always keep your code clean and well-documented.
Not read yet
Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.
- Workspace Level Access Controls
- Workspace Level Access Controls Quiz5q
- Item Level Access Controls
- Item Level Access Controls Quiz5q
- Row Level Security
- Row Level Security Quiz5q
- Column Level and Object Level Security
- Column Level and Object Level Security Quiz5q
- File Level Access Control
- File Level Access Control Quiz5q
- Sensitivity Labels
- Sensitivity Labels Quiz5q
- Endorsing Items
- Endorsing Items Quiz5q
- Data Loss Prevention Policies
- Data Loss Prevention Policies Quiz5q
- Version Control for Workspaces
- Version Control for Workspaces Quiz5q
- Power BI Desktop Projects
- Power BI Desktop Projects Quiz5q
- Deployment Pipelines
- Deployment Pipelines Quiz5q
- Impact Analysis
- Impact Analysis Quiz5q
- XMLA Endpoint for Semantic Models
- XMLA Endpoint for Semantic Models Quiz5q
- Reusable Assets and Templates
- Reusable Assets and Templates Quiz5q
- Shared Semantic Models
- Shared Semantic Models Quiz5q
- Git Integration Best Practices
- Git Integration Best Practices Quiz5q
- Creating Data Connections
- Creating Data Connections Quiz5q
- OneLake Catalog and Real-Time Hub
- OneLake Catalog and Real-Time Hub Quiz5q
- Data Ingestion Methods
- Data Ingestion Methods Quiz5q
- Choosing Data Stores
- Choosing Data Stores Quiz5q
- OneLake Integration for Eventhouse
- OneLake Integration for Eventhouse Quiz5q
- Lakehouse Architecture
- Lakehouse Architecture Quiz5q
- Warehouse Architecture
- Warehouse Architecture Quiz5q
- Dataflows Gen2
- Dataflows Gen2 Quiz5q
- Views Functions and Stored Procedures
- Views Functions and Stored Procedures Quiz5q
- Enriching Data with New Columns
- Enriching Data with New Columns Quiz5q
- Star Schema for Lakehouse
- Star Schema for Lakehouse Quiz5q
- Star Schema for Warehouse
- Star Schema for Warehouse Quiz5q
- Denormalizing Data
- Denormalizing Data Quiz5q
- Aggregating Data
- Aggregating Data Quiz5q
- Merging and Joining Data
- Merging and Joining Data Quiz5q
- Handling Duplicate Data
- Handling Duplicate Data Quiz5q
- Handling Missing and Null Values
- Handling Missing and Null Values Quiz5q
- Converting Column Data Types
- Converting Column Data Types Quiz5q
- Filtering Data
- Filtering Data Quiz5q
- Data Pipelines in Fabric
- Data Pipelines in Fabric Quiz5q
- Spark Notebooks
- Spark Notebooks Quiz5q
- Delta Tables in Lakehouse
- Delta Tables in Lakehouse Quiz5q
- Data Wrangling Techniques
- Data Wrangling Techniques Quiz5q
- Visual Query Editor
- Visual Query Editor Quiz5q
- Querying with SQL
- Querying with SQL Quiz5q
- Querying with KQL
- Querying with KQL Quiz5q
- Querying with DAX
- Querying with DAX Quiz5q
- Advanced SQL Queries
- Advanced SQL Queries Quiz5q
- Time Intelligence in DAX
- Time Intelligence in DAX Quiz5q
- KQL Query Patterns
- KQL Query Patterns Quiz5q
- Combining Query Languages
- Combining Query Languages Quiz5q
- Choosing Storage Mode
- Choosing Storage Mode Quiz5q
- Star Schema for Semantic Models
- Star Schema for Semantic Models Quiz5q
- Implementing Relationships
- Implementing Relationships Quiz5q
- Bridge Tables and Many-to-Many
- Bridge Tables and Many-to-Many Quiz5q
- DAX Variables and Functions
- DAX Variables and Functions Quiz5q
- DAX Iterator Functions
- DAX Iterator Functions Quiz5q
- Table Filtering and Windowing
- Table Filtering and Windowing Quiz5q
- Calculation Groups
- Calculation Groups Quiz5q
- Dynamic Format Strings
- Dynamic Format Strings Quiz5q
- Field Parameters
- Field Parameters Quiz5q
- Large Semantic Model Storage
- Large Semantic Model Storage Quiz5q
- Composite Models
- Composite Models Quiz5q
- Information Functions in DAX
- Information Functions in DAX Quiz5q
- Hierarchies in Semantic Models
- Hierarchies in Semantic Models Quiz5q
- Role-Playing Dimensions
- Role-Playing Dimensions Quiz5q
- Query Performance Improvements
- Query Performance Improvements Quiz5q
- Report Visual Performance
- Report Visual Performance Quiz5q
- DAX Performance Optimization
- DAX Performance Optimization Quiz5q
- Direct Lake Configuration
- Direct Lake Configuration Quiz5q
- Direct Lake Fallback and Refresh
- Direct Lake Fallback and Refresh Quiz5q
- OneLake vs SQL Endpoints
- OneLake vs SQL Endpoints Quiz5q
- Incremental Refresh
- Incremental Refresh Quiz5q
- Performance Analyzer
- Performance Analyzer Quiz5q
- Aggregations in Semantic Models
- Aggregations in Semantic Models Quiz5q
- Monitoring Semantic Models
- Monitoring Semantic Models Quiz5q
- Query Folding
- Query Folding Quiz5q
- Partitioning Strategies
- Partitioning Strategies Quiz5q
- Troubleshooting Refresh Failures
- Troubleshooting Refresh Failures Quiz5q
Spend your points to unlock exam-style practice questions
Spend points to unlock DP-600 exam-style practice questions.
Practice for DP-600