Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can We Create Index in Table Valued Function

Can we create an index on a column in a table valued functions table in SQL Server 2008?

My function is getting slow results. When I look into the execution plan, it was under the table scan, hence I need to create index on function table column so that put where clause on that.

Any help would be highly appreciated.

Thanks in advance

like image 911
Neeraj Dubey Avatar asked Jul 23 '14 12:07

Neeraj Dubey


People also ask

Can we create indexes on table variables?

Short answer: Yes. A more detailed answer is below. Traditional tables in SQL Server can either have a clustered index or are structured as heaps. Clustered indexes can either be declared as unique to disallow duplicate key values or default to non unique.

Can we CREATE INDEX on function in SQL Server?

SQL Server does not support function-based indexes, but you can use computed columns and indexes on computed columns to increase the performance of queries that use functions in the WHERE clause.

When should you not index a table?

Indexes should not be used on tables containing few records. Tables that have frequent, large batch updates or insert operations. Indexes should not be used on columns that contain a high number of NULL values. Indexes should not be used on the columns that are frequently manipulated.

How do I add an index to an existing table?

ALTER command to add and drop INDEXALTER TABLE tbl_name ADD INDEX index_name (column_list) − This adds an ordinary index in which any value may appear more than once. ALTER TABLE tbl_name ADD FULLTEXT index_name (column_list) − This creates a special FULLTEXT index that is used for text-searching purposes.


1 Answers

If the table valued function is of the inline variety you would create the index on the underlying table columns.

If it is a multi statement TVF in SQL Server 2008 (as tagged) you can only create the indexes associated with primary key or unique constraints.

In SQL Server 2014+ it is possible to declare inline indexes not associated with any constraint.

Example

CREATE FUNCTION F()
RETURNS @X TABLE
(
A INT PRIMARY KEY /*<-- Implicit clustered index*/
)
AS
BEGIN
INSERT INTO @X 
    VALUES(1),(2)
RETURN;
END

GO

SELECT *
FROM F()
WHERE A = 12

enter image description here

The above materializes the entire resultset up front into a table variable first, and creates an implicit index on it.

Generally inline TVFs are preferred to multi statement ones.

like image 114
Martin Smith Avatar answered Sep 20 '22 15:09

Martin Smith