In the past I've noted terrible performance when querying a varbinary(max) column. Understandable, but it also seems to happen when checking if it's null or not, and I was hoping the engine would instead take some shortcuts.
select top 100 * from Files where Content is null
I would suspect that it's slow because it's
This question seems to disagree with my premise of slowness here, but I seem to have performance problems with binary fields time and time again.
One possible solution I thought of is to make a computed column that is indexed:
alter table Files
add ContentLength as ISNULL(DATALENGTH(Content),0) persisted
CREATE NONCLUSTERED INDEX [IX_Files_ContentLength] ON [dbo].[Files]
(
[ContentLength] ASC
)
select top 100 * from Files where ContentLength = 0
Is that a valid strategy? What other ways are there to efficiently query when binary fields are involved?
Definition and Usage. The ISNULL() function returns a specified value if the expression is NULL. If the expression is NOT NULL, this function returns the expression.
We use IS NULL to identify NULL values in a table. For example, if we want to identify records in the employee table with NULL values in the Salary column, we can use IS NULL in where clause.
The VARBINARY data type holds variable-length binary data. Use this type when the data is expected to vary in size. The maximum size for VARBINARY is 8,000 bytes.
I think it's slow because the varbinary column is not (and can't be) indexed. Therefore, your approach to use a computed (and indexed) column is valid.
However, I would use ISNULL(DATALENGTH(Content), -1)
instead, so that you can distinguish between length 0 and NULL. Or just use DATALENGTH(Content)
. I mean, Microsoft SQL Server is not Oracle where an empty string is the same as NULL.
We had a similar problem when looking for rows where a varbinary value was not null. For us the solution was to update the statistics for the database:
exec sp_updatestats
After doing this the queries ran much faster.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With