Skip to content
Advertisement

Sql View with WHERE clause runs slower than a raw query

This runs in a constant time:

However, this one takes about 7 seconds:

Component is a SQL view which consists of the first longer query without WHERE clause.

Why this happens? Does the view retrieve all records and then apply Where clause? Is there a way to speed up the second query? (without applying indexes)

Advertisement

Answer

Why this happens? Does the view retrieve all records and then apply Where clause?

Yes, in this particular case, SQL Server will first execute the original underlying query, and then apply a WHERE filter on top of that intermediate result.

Is there a way to speed up the second query? (without applying indexes)

A SQL view generally performs as well as the underlying query. So, if Barcode is a good way to filter off many records, then adding an index to Barcode is the way to go. Other than this, there is not much you can do to speed up the view.

One option would be to create a materialized view, which is basically just a table whose data is generated by your view’s query. Selecting all records from a materialized view, with no additional restrictions, should have a speed limited only by the time of data transfer.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement