Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Performance-wise, what's better: an IF...ELSE clause, or WHERE LIKE clause?

I have a stored procedure that has a optional parameter, @UserID VARCHAR(50). The thing is, there are two ways to work with it:

  1. Give it a default value of NULL, the have an IF...ELSE clause, that performs two different SELECT queries, one with 'WHERE UserID = @UserID' and without the where.
  2. Give it a default value of '%' and then just have the where clause use 'WHERE UserID LIKE @UserID'. In the calling code, the '%' wont be used, so only exact matches will be found.

The question is: Which option is faster? Which option provides better performance as the table grows? Be aware that the UserID column is a foreign key and is not indexed.

EDIT: Something I want to add, based on some answers: The @UserID parameter is not (necessarily) the only optional parameter being passed. In some cases there are as many as 4 or 5 optional parameters.

like image 334
Schmuli Avatar asked Nov 05 '08 21:11

Schmuli


People also ask

Which clause is faster in SQL?

"WHERE" is faster than "HAVING"! Save this answer. Show activity on this post. "Having" is slower if we compare with large amount of data because it works on group of records and "WHERE" works on number of rows..

Does adding WHERE clause improve performance?

A where clause will generally increase the performance of the database. Generally, it is more expensive to return data and filter in the application. The database can optimize the query, using indexes and partitions. The database may be running in parallel, executing the query in parallel.

Which of the following will improve the performance of SQL query?

Popular methods for SQL table optimization and query speed improvement include: Providing a limited range of dates for time series data. Limiting the dataset in a subquery. Avoiding duplicate data.

Is like faster or in in SQL?

1 Answer. Using '=' operator is faster than the LIKE operator in comparing strings because '=' operator compares the entire string but the LIKE keyword compares by each character of the string. We can use LIKE to check a particular pattern like column values starting with 'abc' in this case.


1 Answers

What I typically do is something like

WHERE ( @UserID IS NULL OR UserID = @UserID )

And why isn't it indexed? It's generally good form to index FKs, since you often join on them...

If you're worried about query plan storage, simply do: CREATE PROCEDURE ... WITH RECOMPILE

like image 114
Matt Rogish Avatar answered Sep 18 '22 10:09

Matt Rogish