Views, scalar functions, inline and multi-statement table-valued functions and stored procedures in SQL Server: what each is, when to use it, and the performance differences.
A view is a named SELECT that the optimiser expands into your query, so it costs nothing by itself. A function returns a value or a table and can be used inside a query, but it cannot change data. An inline table-valued function is a single RETURN SELECT, so it is inlined like a parameterised view and optimised with the outer query. A multi-statement TVF fills a table variable first, so the optimiser guesses a fixed row count and plans are often poor. Scalar functions historically ran once per row and blocked parallelism (SQL Server 2019+ can inline some). A stored procedure is a batch you call with EXEC: it can insert, update, manage transactions and return several result sets.
The trade-off: functions compose inside queries; procedures do work. Prefer inline TVFs over multi-statement ones.
"A view is just a saved SELECT. When I query a view, SQL Server expands its definition into my query before optimising, so the optimiser sees the underlying tables and can push predicates down. A view stores no data unless I make it an indexed view. I use views to give a stable shape to reporting tools or to grant access to a subset of columns without granting access to the base table.
Functions come in three kinds, and the difference matters. A scalar function returns one value; before SQL Server 2019 it ran once per row, hid its cost from the plan and forced the whole query serial. An inline table-valued function is a single RETURN SELECT, so it behaves like a parameterised view: it's inlined and optimised with the rest of the query. A multi-statement table-valued function declares a table variable, fills it with several statements and returns it, so the optimiser can't see inside and uses a fixed estimate, 100 rows with the newer cardinality estimator. If the real answer is 200,000 rows, I get nested loops where I needed a hash join.
A stored procedure is different: I call it with EXEC, it can insert, update and delete, control transactions, use TRY/CATCH and return several result sets. Functions can't have side effects at all. The mistake I see is wrapping logic in a multi-statement function because it reads nicely, then joining it to a big table. My rule: views for shape and security, inline TVFs when I need parameters, procedures when I'm doing work."
| Object | Returns | Can change data | Used inside SELECT | Optimiser sees inside |
|---|---|---|---|---|
| View | Rows | Only through simple updatable views | Yes | Yes (expanded) |
| Scalar UDF | One value | No | Yes | Only if inlined (2019+) |
| Inline TVF | Rows | No | Yes (FROM/APPLY) |
Yes (inlined) |
| Multi-statement TVF | Table variable | Only its own table variable | Yes | No: fixed estimate |
| Stored procedure | Result sets, output parameters, return code | Yes | No (EXEC only) |
Each statement compiled separately |
| Need | Use |
|---|---|
| Reusable join for reports, or column-level access | View |
| Same filter logic with parameters, composable in queries | Inline TVF |
| A calculation reused in many queries | Inline TVF with CROSS APPLY, or a computed column, rather than a scalar UDF |
| Insert/update logic, transactions, several steps | Stored procedure |
| Logic that truly needs several statements and returns rows | Procedure into a temp table, rather than a multi-statement TVF |
A monthly statement report joined Orders to a multi-statement TVF that returned a customer's discounts. The TVF was estimated at 100 rows but returned about 180,000, so the plan used nested loops and ran for 41 seconds. Rewriting it as an inline TVF with the same logic let the optimiser choose a hash join, and the report dropped to 1.2 seconds with the same indexes.
Checks that the candidate knows what each object is for and, more importantly, which ones the optimiser can see into.
Green flags
Red flags
SQL Server stores a view's definition as text in sys.sql_modules. During binding (algebrisation) the view reference is replaced by its query tree, so this:
SELECT * FROM dbo.vActiveCustomers WHERE Country = 'AU'
|
v (view expansion)
SELECT ... FROM dbo.Customers WHERE IsActive = 1 AND Country = 'AU'
The optimiser then works on the combined tree, so a predicate on the view can use an index on the base table. Nested views (views on views on views) still expand, but the tree becomes large and the optimiser can time out and pick a mediocre plan.
Adding a unique clustered index to a view created WITH SCHEMABINDING materialises it: SQL Server stores the rows and maintains them on every insert, update and delete to the base tables. Enterprise edition (and Azure SQL) can match an indexed view automatically; other editions need WITH (NOEXPAND). Good for pre-aggregated totals, costly on write-heavy tables.
Before SQL Server 2019, a scalar UDF was executed by the interpreter once per row:
Compute Scalar (dbo.fnTax(Amount)) <- called 1,000,000 times, cost hidden
Clustered Index Scan (Orders)
It also made the plan serial. Scalar UDF inlining (database compatibility level 150+) rewrites a qualifying function into relational expressions. It doesn't apply if the function uses things like GETDATE() in some forms, table variables, or loops; check sys.sql_modules.is_inlineable.
Inline TVF: RETURN (SELECT ...) -> inlined like a view
Multi-statement TVF: DECLARE @t TABLE(...); -> runs separately,
INSERT @t ...; RETURN; rows come from a table variable
The multi-statement form gets a fixed cardinality estimate: 1 row under the legacy estimator, 100 under CE 120 and later. Interleaved execution (compatibility level 140+) can pause optimisation, run the TVF and use the real row count, but only for read-only statements and not inside CROSS APPLY correlated calls.
A procedure is compiled on first execution with the parameter values passed (parameter sniffing), and the plan is cached and reused. It can run DML, DDL, transactions, TRY...CATCH, and return multiple result sets plus output parameters and a return code. It cannot be used in a FROM clause.
If a view or procedure and the tables it reads have the same owner, a user granted EXECUTE or SELECT on the module doesn't need rights on the tables. That's how you expose data without granting table access.
SELECT OBJECT_NAME(object_id), is_inlineable FROM sys.sql_modules WHERE is_inlineable IS NOT NULL; to see which scalar UDFs can be inlined.WHERE clause and confirm in the plan that the predicate becomes an index seek on the base table.SET STATISTICS IO, TIME ON and compare a scalar UDF in the SELECT list at compatibility level 140 and 160.Three ways to reuse the same "order totals" logic, and how each behaves.
-- View: expanded into the caller's query
CREATE OR ALTER VIEW dbo.vOrderTotals
AS
SELECT o.OrderId, o.CustomerId, SUM(l.Quantity * l.UnitPrice) AS Total
FROM dbo.Orders o
JOIN dbo.OrderLines l ON l.OrderId = o.OrderId
GROUP BY o.OrderId, o.CustomerId;
GO
-- Inline TVF: a parameterised view, optimised with the outer query
CREATE OR ALTER FUNCTION dbo.fnCustomerOrderTotals (@CustomerId int)
RETURNS TABLE
AS
RETURN
SELECT o.OrderId, SUM(l.Quantity * l.UnitPrice) AS Total
FROM dbo.Orders o
JOIN dbo.OrderLines l ON l.OrderId = o.OrderId
WHERE o.CustomerId = @CustomerId
GROUP BY o.OrderId;
GO
-- Multi-statement TVF: avoid for large results (fixed row estimate)
CREATE OR ALTER FUNCTION dbo.fnCustomerOrderTotals_Slow (@CustomerId int)
RETURNS @r TABLE (OrderId int PRIMARY KEY, Total decimal(19,4))
AS
BEGIN
INSERT @r (OrderId, Total)
SELECT o.OrderId, SUM(l.Quantity * l.UnitPrice)
FROM dbo.Orders o
JOIN dbo.OrderLines l ON l.OrderId = o.OrderId
WHERE o.CustomerId = @CustomerId
GROUP BY o.OrderId;
RETURN;
END;
GO
-- Stored procedure: does work, manages its own transaction
CREATE OR ALTER PROCEDURE dbo.CancelOrder @OrderId int
AS
BEGIN
SET NOCOUNT, XACT_ABORT ON;
BEGIN TRANSACTION;
UPDATE dbo.Orders SET Status = 'Cancelled' WHERE OrderId = @OrderId;
DELETE dbo.Reservations WHERE OrderId = @OrderId;
COMMIT;
END;
GO
-- Using the inline TVF per row with CROSS APPLY
SELECT c.CustomerId, t.OrderId, t.Total
FROM dbo.Customers c
CROSS APPLY dbo.fnCustomerOrderTotals(c.CustomerId) t
WHERE c.Country = 'AU';
WITH SCHEMABINDING with a unique clustered index) stores rows, and every base-table write then maintains it. Instead: Treat views as saved query text; use an indexed view only when read gains outweigh the write cost.RETURNS TABLE AS RETURN SELECT ...), which gets real estimates from statistics.is_inlineable, or rewrite as an inline TVF with CROSS APPLY or a computed column.BEGIN TRAN inside them. Instead: Use a stored procedure for anything that writes, needs TRY...CATCH around several statements, or must commit as a unit.SELECT on the view or EXECUTE on the procedure (or schema) only.SELECT * inside a view. Why it is wrong: The column list is fixed when the view is created; adding a column to the table leaves the view stale until sp_refreshview. Instead: List columns explicitly and consider WITH SCHEMABINDING.The real question behind this one is "do you know what the optimiser can see?" Views and inline TVFs are transparent: they disappear into the outer query. Multi-statement TVFs and non-inlined scalar UDFs are opaque boxes with guessed costs. That single idea explains most of the performance stories you'll hear about functions.
| Option | Fits when | Cost | Avoid when |
|---|---|---|---|
| View | Stable shape for reports, column security | Nested views get hard to tune | Building deep view hierarchies |
| Inline TVF | Parameterised reusable query | None beyond the query itself | Logic needs several statements |
| Multi-statement TVF | Small result, logic needs steps | Bad estimates on large results | Joining to large tables |
| Stored procedure | Writes, transactions, several result sets | Logic lives outside the app's code review | Simple reads you could write in EF Core |
Measure with the actual execution plan: compare estimated and actual rows on the function's operator, and use SET STATISTICS IO, TIME ON. Remember that STATISTICS IO doesn't report reads done inside scalar UDFs, so the query can look cheap when it isn't.
Create an inline table-valued function in SQL Server, add a method on the DbContext that returns IQueryable<T> via FromExpression(() => Fn(arg)), and register it with modelBuilder.HasDbFunction (supported since EF Core 5). EF Core then translates db.Fn(x).Where(...).Include(...) into SELECT ... FROM dbo.Fn(@p0) WHERE .... Inline TVFs are a single SELECT, so the optimiser expands them into the outer query like a parameterised view and uses real statistics. Multi-statement TVFs allow procedural logic (table variables, loops, several statements) when you genuinely need it, but they're opaque to the optimiser: SQL Server 2017+ interleaved execution helps, yet their row estimates are often poor, so they're usually slower when composed with large queries.
An indexed view is a view created WITH SCHEMABINDING that has a unique clustered index, so SQL Server stores its rows and maintains them on every change to the base tables. It suits read-heavy aggregates (daily sales totals) where the base data changes slowly. Every insert, update or delete on a base table also updates the view, which adds write cost and can cause blocking on hot aggregate rows. Enterprise edition and Azure SQL can match it automatically; Standard needs WITH (NOEXPAND).
Last updated 23 Nov 2026.