Hi I have query as follows:
SELECT route_id [ROUTE_ID]
FROM route_master(NOLOCK)
WHERE route_ou = 2
AND route_query = @l_s_query
AND lang_id = 1
Here, the " AND route_query = @l_s_query" condition in WHERE clause should be added only when @l_s_query is non empty. I donot want to write IF ELSE condition for @l_s_query. Is there any way to handle in WHERE clause itself directly.Thanks.
Below is the syntax to filter the rows without a null value in a specified column. Syntax: SELECT * FROM <table_name> WHERE <column_name> IS NOT NULL; Example: SELECT * FROM demo_orders WHERE ORDER_DATE IS NOT NULL; --Will output the rows consisting of non null order_date values.
The IS NOT NULL condition is used in SQL to test for a non-NULL value. It returns TRUE if a non-NULL value is found, otherwise it returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.
To exclude the null values from the table we need to use IS NOT NULL operator with the WHERE clause. WHERE Clause: The WHERE clause is used to filter the records. It will extract those records that fulfill the condition.
NULL has no value, and so cannot be compared using the scalar value operators. In other words, no value can ever be equal to (or not equal to) NULL because NULL has no value. Hence, SQL has special IS NULL and IS NOT NULL predicates for dealing with NULL.
You can translate your requirement into :
SELECT route_id [ROUTE_ID]
FROM route_master(NOLOCK)
WHERE route_ou = 2
AND (@l_s_query is null OR route_query = @l_s_query)
AND lang_id = 1
OPTION (RECOMPILE)
The OPTION (RECOMPILE)
is optional but can give better execution plans at the expense of extra compilation time as discussed in the canonical article on the topic Dynamic Search Conditions in T‑SQL
Or with COALESCE()
to avoid the OR
:
WHERE route_ou = 2
AND COALESCE(@l_s_query,route_query) = route_query
AND lang_id = 1
Note: As @jarlh said, if route_query
is nullable, this may cause some issues becuase of null comparison, so you may want to use the first query.
Another option of this is two separate queries using UNION ALL
, one for each condition -
SELECT .. FROM ..
WHERE @l_s_query IS NULL
UNION ALL
SELECT .. FROM ..
WHERE @l_s_query = route_query
On terms of performance,only the last one will use the index, I believe the first one will be the fastest, but it may change depanding on the indexes, sizes of the tables ETC..
Here is a better way to handle: using LEN(ISNULL)... OR
:
AND (LEN(ISNULL(@l_s_query,'')) = 0 OR route_query = @l_s_query)
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