📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is the difference between a view, a function and a stored procedure in SQL Server, and when would you use each? Explain scalar, inline table-valued and multi-statement table-valued functions, and why the difference between the last two matters for performance.

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.

Junior Theory Beginner functions query-performance sql-server stored-procedures t-sql views

🎯 Key points

  • A view is a saved SELECT, expanded inline into the calling query; it stores nothing unless it is an indexed view (SCHEMABINDING + unique clustered index materialises it, at a write cost)
  • Inline TVF = a parameterised view: single RETURN SELECT, inlined and optimised with the outer query
  • Multi-statement TVF fills a table variable; the cardinality estimator (CE) uses a fixed guess of 100 rows (CE 120+) or 1 row (legacy CE) unless interleaved execution applies
  • Scalar UDFs ran row by row and blocked parallelism; SQL Server 2019+ scalar UDF inlining helps only when the function qualifies
  • Stored procedures can change data, run multiple statements, manage transactions and return several result sets; functions cannot have side effects
  • Ownership chaining: GRANT SELECT on a view or EXECUTE on a procedure without granting rights on the base tables
  • Use views for reuse and security, inline TVFs for parameterised reuse, procedures for operations and transactions

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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."


Comparison

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

When to use each

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate knows what each object is for and, more importantly, which ones the optimiser can see into.

Green flags

  • Says views are expanded inline and store nothing unless indexed
  • Distinguishes inline from multi-statement TVFs and mentions the fixed row estimate
  • Knows scalar UDFs used to run per row and block parallelism, and mentions 2019 inlining
  • Knows functions cannot change data; procedures can

Red flags

  • Thinks views are cached result sets
  • Treats all functions as equivalent
  • Recommends scalar UDFs in WHERE clauses on large tables without caveats

📚 Learn in depth

1. What "expanded" means

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.

2. Indexed views

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.

3. Scalar UDFs and inlining

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.

4. Inline vs multi-statement TVF

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.

5. Stored procedures

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.

6. Permissions and ownership chaining

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.

Try it yourself

  1. Create a multi-statement TVF and an inline TVF with the same logic. Join each to a large table and compare estimated vs actual rows in the actual plan.
  2. Run 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.
  3. Query a view with a WHERE clause and confirm in the plan that the predicate becomes an index seek on the base table.
  4. Run SET STATISTICS IO, TIME ON and compare a scalar UDF in the SELECT list at compatibility level 140 and 160.

💻 Code

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';

⚠ Common mistakes

  • Mistake: Thinking a view stores data or is "precomputed". Why it is wrong: A normal view is expanded into the query each time; only an indexed view (created 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.
  • Mistake: Writing a multi-statement TVF when a single SELECT would do. Why it is wrong: The cardinality estimator uses a fixed guess (100 rows under CE 120+) and can't push predicates in, so a TVF that returns hundreds of thousands of rows gets nested loops where a hash join was needed. Instead: Write it as an inline TVF (RETURNS TABLE AS RETURN SELECT ...), which gets real estimates from statistics.
  • Mistake: Putting a scalar UDF in the SELECT or WHERE of a big query. Why it is wrong: Unless it is inlined, it runs per row, hides its cost and forces a serial plan. Instead: Check is_inlineable, or rewrite as an inline TVF with CROSS APPLY or a computed column.
  • Mistake: Stacking views on views. Why it is wrong: The expanded tree grows, joins are repeated and the optimiser may time out. Instead: Keep views one level deep, or query base tables directly for hot paths.
  • Mistake: Trying to change data or manage a transaction inside a function. Why it is wrong: Functions must be side-effect free; SQL Server rejects DML on real tables and 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.
  • Mistake: Granting table permissions to the app login just so it can use a view or procedure. Why it is wrong: Ownership chaining already lets a module read tables with the same owner; extra grants widen the blast radius. Instead: Grant SELECT on the view or EXECUTE on the procedure (or schema) only.
  • Mistake: Using 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.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions inline table-valued functions being composable Why: Checks whether they can use TVFs from EF Core so the composition still happens on the server.
    How to answer

    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.

  2. When: Candidate says a normal view stores no data Why: Checks understanding of materialisation, SCHEMABINDING, NOEXPAND and write overhead.
    How to answer

    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).

More in SQL Features

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me