wasAsked.

What is function , views?

Agiliad Technologies Pvt Ltd · Role not specified · technical

Published

Asked in 2026 · Software Engineering

Community answers

Posted by wasAsked editorial collection

In SQL databases, functions and views are both reusable database objects that simplify queries, but they serve different purposes. Views A view is a saved SELECT query that behaves like a virtual table. It does not store data itself (except indexed or materialized views); every time you query it, the underlying query runs. CREATE VIEW dbo.ActiveCustomerOrders AS SELECT c.Id AS CustomerId, c.Name, o.Id AS OrderId, o.Total, o.OrderDate FROM Customers c JOIN Orders o ON o.CustomerId = c.Id WHERE c.IsActive = 1; SELECT * FROM dbo.ActiveCustomerOrders WHERE OrderDate >= '2026-01-01'; Uses - Simplify complex joins for reports and applications. - Security: expose only certain columns or rows, and grant permissions on the view instead of the base tables. - Abstraction: keep a stable interface while underlying tables change. - Updatable views: simple views over one table can support INSERT, UPDATE and DELETE. - Indexed views (SQL Server) or materialized views (PostgreSQL, Oracle) store results physically to speed up heavy aggregations. Limitation: views do not accept parameters. Functions (user-defined functions) A function accepts parameters and returns a value. - Scalar functions return a single value: CREATE FUNCTION dbo.fn_PriceWithGst (@Price DECIMAL(18,2)) RETURNS DECIMAL(18,2) AS BEGIN RETURN @Price * 1.18; END; SELECT Name, dbo.fn_PriceWithGst(Price) FROM Products; - Table-valued functions return a table — like a parameterised view: CREATE FUNCTION dbo.fn_OrdersForCustomer (@CustomerId INT) RETURNS TABLE AS RETURN SELECT Id, Total, OrderDate FROM Orders WHERE CustomerId = @CustomerId; SELECT * FROM dbo.fn_OrdersForCustomer(42); Function rules - Can be used inside SELECT, WHERE and JOIN (table-valued functions in FROM or with APPLY). - Cannot modify data in permanent tables, cannot use explicit transactions, and cannot call stored procedures. Comparison - Parameters: views no; functions yes. - Returns: views a virtual table; functions a scalar or a table. - Use in queries: both can appear in FROM (table-valued functions); scalar functions appear in expressions. - Performance: inline table-valued functions and views are expanded into the outer query and usually perform well; scalar UDFs called per row can be slow (SQL Server 2019's scalar UDF inlining helps in many cases); multi-statement table-valued functions often have poor estimates. Choose a view for reusable, parameterless query logic or security layers, and an inline table-valued function when you need a parameterised, reusable query.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics