Where clause in sql - sql

My sql query is as follows
IF #StatusId = 10
BEGIN
SELECT
*
FROM
Risk AS R
INNER JOIN Statuses AS St ON R.Status_Id=St.Status_Id
WHERE
R.MitigationOwner = COALESCE(#MitigationOwner,R.MitigationOwner)
AND R.RiskFactor = COALESCE(#RiskFactor,R.RiskFactor)
AND R.RiskArea = COALESCE(#RiskArea,R.RiskArea)
AND R.AddedWhen BETWEEN
COALESCE(CONVERT(DATETIME, #StartDate+'00:00:00',120),R.AddedWhen) AND
COALESCE(CONVERT(DATETIME,#EndDate+'23:59:59',120),R.AddedWhen)
END
When I pass only status Id and all other variables are null, then records with NULL MitigationOwner or ModifiedDate are not displayed..
What is wrong in this query?

Use the form:
...
(R.MitigationOwner = #MitigationOwner OR #MitigationOwner IS NULL)
...
This is optimised in SQL Server. COALESCE isn't.
Edit: This does the same as Paul Williams' answer but his answer allows explicit "NULL = NULL" matches. m ylogic is simpler because NULL never equals NULL.

I believe that by ModifiedDate you meant R.AddedWhen
try this:
SELECT
*
FROM
Risk AS R
INNER JOIN Statuses AS St ON R.Status_Id=St.Status_Id
WHERE
(R.MitigationOwner = COALESCE(#MitigationOwner,R.MitigationOwner) OR R.MitigationOwner IS NULL)
AND R.RiskFactor = COALESCE(#RiskFactor,R.RiskFactor)
AND R.RiskArea = COALESCE(#RiskArea,R.RiskArea)
AND (R.AddedWhen BETWEEN
COALESCE(CONVERT(DATETIME, #StartDate+'00:00:00',120),R.AddedWhen) AND
COALESCE(CONVERT(DATETIME,#EndDate+'23:59:59',120),R.AddedWhen) OR R.AddedWhen IS NULL)

If R.MitigationOwner can be null, then your comparison clause:
WHERE
R.MitigationOwner = COALESCE(#MitigationOwner,R.MitigationOwner)
Must be rewritten to handle NULL values:
WHERE
((R.MitigationOwner IS NULL AND #MitigationOwner IS NULL)
OR (R.MitigationOwner = #MitigationOwner))
See this article on Wikipedia about NULL.

Related

SQL checking equality inside a case statement inside where clause?

Here is the code:
WHERE 1=1
AND TU.Auction_I IN (41, 42)
AND #StatePickupID = CASE
WHEN #StatePickupID IS NOT NULL
THEN (UP.TransportStateID = #StatePickupID)
END
AND #StateDropoffID = CASE
WHEN #StateDropoffID IS NOT NULL
THEN (UD.TransportStateID = #StateDropoffID)
END
So I only want to return records where UP.TransportStateID is equal to StatePickupID if it is not null, same thing for DropoffID. But I get a syntax error message where the equals sign is and I cannot find any other way to check for equality online. Any help or advice would be much appreciated.
I only want to return records where UP.TransportStateID is equal to StatePickupID if it is not null
This would translate as the following predicate:
#StatePickupID IS NULL OR #StatePickupID = UP.TransportStateID
When the parameter is not null, the predicate filters on TransportStateID; when the parameter is null, the filter is a no-op.
In your where clause, for both parameters :
WHERE 1 = 1
AND TU.Auction_I IN (41, 42)
AND ( #StatePickupID IS NULL OR #StatePickupID = UP.TransportStateID )
AND ( #StateDropoffID IS NULL OR #StateDropoffID = UD.TransportStateID )

"Subquery returns more than 1 row" when use select to set value of parameter

I have an issue when I try to set the value of a variable with a subquery.
This is my SQL code:
SELECT #V_SOURCE = (SELECT ITEM_SOURCE
FROM TABLE1
WHERE OPP_CODE = #V_OPP_CODE
AND PDGROUPNO = #V_PRD_GROUP_NO
AND DELETE_FLAG IS NULL
AND CONTRACTOR = #V_CONTRACTOR
AND OPP_ITEM_NO = #_OPP_ITEM_NO)
When I run this code with an assumed variable that is used in WHERE condition, it returns only 1 row and 1 col that is correct but if I run this code with store procedure it will return the error:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <=, >, >= or when the subquery is used as an expression
The sub-query can return multiple rows.
Even if it shouldn't, that won't do.
But you can change it to this.
SELECT #V_SOURCE = ITEM_SOURCE
FROM TABLE1
WHERE OPP_CODE = #V_OPP_CODE
AND PDGROUPNO = #V_PRD_GROUP_NO
AND DELETE_FLAG IS NULL
AND CONTRACTOR = #V_CONTRACTOR
AND OPP_ITEM_NO = #_OPP_ITEM_NO
GROUP BY ITEM_SOURCE;
It'll assign the last value of the resultset to the variable.
Which is fine, since you expect only one anyway.
Another way is to pick only the top 1
SET #V_SOURCE = (
SELECT TOP 1 ITEM_SOURCE
FROM TABLE1
WHERE OPP_CODE = #V_OPP_CODE
AND PDGROUPNO = #V_PRD_GROUP_NO
AND DELETE_FLAG IS NULL
AND CONTRACTOR = #V_CONTRACTOR
AND OPP_ITEM_NO = #_OPP_ITEM_NO
);
I find an issue in my query because of I query data to use for this query some CONTRACTOR is NULL then it makes an error when using this query
SELECT #V_SOURCE = (SELECT ITEM_SOURCE
FROM TABLE1
WHERE OPP_CODE = #V_OPP_CODE
AND PDGROUPNO = #V_PRD_GROUP_NO
AND DELETE_FLAG IS NULL
AND CONTRACTOR = #V_CONTRACTOR
AND OPP_ITEM_NO = #_OPP_ITEM_NO)
When I filter data that CONTRACTOR is NULL out, I don't get any error now.

SQL: field = other_field returns false even if they are identical (NULL values)

I have a difficulty because when comparing two fields in a subquery, although the fields are identical i.e. they both have NULL values, the comparison returns a FALSE result
Therfore NULL = NULL is returning FALSE
Now I know that NULLs are supposed to be compared with the IS operator, however when I compare two fields how am I supposed to know they contain a null? I need to compare two fields for identical data both if the values are NULL or not.
Consider this SQL:
SELECT
*
FROM
fts.fts_customers_data_50360001
WHERE
fts.fts_customers_data_50360001.record_type = 15
AND
fts.fts_customers_data_50360001.mid = 103650360001
AND NOT EXISTS
(
SELECT
fts.temp_fees_50360001.record_type
FROM
fts.temp_fees_50360001
WHERE
fts.temp_fees_50360001.record_type = fts.fts_customers_data_50360001.record_type
AND
fts.temp_fees_50360001.merch_id = fts.fts_customers_data_50360001.mid
AND
fts.temp_fees_50360001.fee_curr = fts.fts_customers_data_50360001.currency
AND
fts.temp_fees_50360001.card_scheme = fts.fts_customers_data_50360001.card_scheme
AND
fts.temp_fees_50360001.tran_type = fts.fts_customers_data_50360001.fee_type
AND
fts.temp_fees_50360001.area = fts.fts_customers_data_50360001.region
AND
fts.temp_fees_50360001.srvc_type = fts.fts_customers_data_50360001.card_type
);
In the query above,
fts.temp_fees_50360001.card_scheme = fts.fts_customers_data_50360001.card_scheme
both have NULL values inside but the comparison returns false .. too bad
ANY IDEAS WOULD BE MUCH APPRECIATED
As the others have pointed out, NULL cannot be compared with NULL.
In Postgres you can shorten your expressions by using the operator IS DISTINCT FROM which is a null-safe replacement for <>. In your case you'd need to use IS NOT DISTINCT FROM to compare for equality (looks a bit the wrong way round but unfortunately there is no corresponding IS EQUAL TO defined in the SQL standard).
From the manual:
Ordinary comparison operators yield null (signifying "unknown"), not true or false, when either input is null. For example, 7 = NULL yields null, as does 7 <> NULL. When this behavior is not suitable, use the IS [ NOT ] DISTINCT FROM constructs:
So, instead of
(fts.temp_fees_50360001.record_type = fts.fts_customers_data_50360001.record_type
OR (fts.temp_fees_50360001.record_type IS NULL
AND fts.fts_customers_data_50360001.record_type IS NULL)
)
you can use:
(fts.temp_fees_50360001.record_type IS NOT DISTINCT FROM fts.fts_customers_data_50360001.record_type)
to handle NULL values automatically. The condition looks a bit strange if you want to compare for equality but it still is quite short.
First of all, use aliases for your tables, your query will be MUCH more readable:
select *
from fts.fts_customers_data_50360001 as d
where
d.record_type = 15 and
d.mid = 103650360001 and
not exists
(
select *
from fts.temp_fees_50360001 as f
where
f.record_type = d.record_type and
f.merch_id = d.mid and
f.fee_curr = d.currency and
f.card_scheme = d.card_scheme and
f.tran_type = d.fee_type and
f.area = d.region and
f.srvc_type = d.card_type
)
As for your question, there's several ways to do this, for example, you can use syntax like this:
...
(
f.card_scheme is null and d.card_scheme is null or
f.card_scheme = d.card_scheme
)
...
Or use coalesce with some value that couldn't be stored in your column:
...
coalesce(f.card_scheme, -1) = coalesce(d.card_scheme, -1)
...
Recently I also like using exists with intersect for this type of comparisons:
...
exists (select f.card_scheme, f.tran_type intersect select d.card_scheme, d.tran_type)
...
Just a side note - you have to be careful when writing queries like this and check query plans to be sure your indexes are used.
In SQL, null is never equal to null. The only way to get a true result for a comparison with null is via the special tests:
IS NULL
IS NOT NULL
In your case, you must cater specifically for the "two nulls" case being considered equal:
AND (fts.temp_fees_50360001.card_scheme = fts.fts_customers_data_50360001.card_scheme
OR (fts.temp_fees_50360001.card_scheme IS NULL
AND fts.fts_customers_data_50360001.card_scheme IS NULL)
)
There's no getting around dealing with it (although there are a few variations).
The following inner SELECT works (but I give no guarantee regarding performance):
SELECT
fts.temp_fees_50360001.record_type
FROM
fts.temp_fees_50360001
WHERE
(fts.temp_fees_50360001.record_type = fts.fts_customers_data_50360001.record_type
OR (fts.temp_fees_50360001.record_type IS NULL AND fts.fts_customers_data_50360001.record_type IS NULL))
AND
(fts.temp_fees_50360001.merch_id = fts.fts_customers_data_50360001.mid
OR (fts.temp_fees_50360001.merch_id IS NULL AND fts.fts_customers_data_50360001.mid IS NULL))
AND
(fts.temp_fees_50360001.fee_curr = fts.fts_customers_data_50360001.currency
OR (fts.temp_fees_50360001.fee_curr IS NULL AND fts.fts_customers_data_50360001.currency IS NULL))
AND
(fts.temp_fees_50360001.card_scheme = fts.fts_customers_data_50360001.card_scheme
OR (fts.temp_fees_50360001.card_scheme IS NULL AND fts.fts_customers_data_50360001.card_scheme IS NULL))
AND
(fts.temp_fees_50360001.tran_type = fts.fts_customers_data_50360001.fee_type
OR (fts.temp_fees_50360001.tran_type IS NULL AND fts.fts_customers_data_50360001.fee_type IS NULL))
AND
(fts.temp_fees_50360001.area = fts.fts_customers_data_50360001.region
OR (fts.temp_fees_50360001.area IS NULL AND fts.fts_customers_data_50360001.region IS NULL))
AND
(fts.temp_fees_50360001.srvc_type = fts.fts_customers_data_50360001.card_type
OR (fts.temp_fees_50360001.srvc_type IS NULL AND fts.fts_customers_data_50360001.card_type))

Incorrect Where Statement

Any reason why the below statement doesn't return any results? If I leave out the where I get all the records and can clearly see that VarcharFields don't match in a number of cases which are the ones I'm trying to find. I've tried swapping ACC and CON in the where and also using <> instead of !=.
SELECT Con.VarcharField, ACC.VarcharField
FROM
dbo.Contact AS CON
INNER JOIN Account as ACC ON ACC.AccountId = CON.ContactID
WHERE ACC.VarcharField != CON.VarcharField
UPDATE
The problem is down to null values in the table. Any way around NULL comparisons?
You can check if either side is NULL and other is not.
SELECT Con.VarcharField, ACC.VarcharField
FROM
dbo.Contact AS CON
INNER JOIN Account as ACC ON ACC.AccountId = CON.ContactID
WHERE (ACC.VarcharField IS NULL AND CON.VarcharField IS NOT NULL)
OR (ACC.VarcharField IS NOT NULL AND CON.VarcharField IS NULL)
OR ACC.VarcharField != CON.VarcharField
SQLFiddle DEMO
For comparisons with string fields that might be NULL, I prefer the IsNull() function. Careful. Depends on what your definition of "no value" is, and whether they should match or not match.
WHERE IsNULL(ACC.VarcharField, '') != IsNull(CON.VarcharField, '')

TSQL Case in where statement if parameter is null

I have a SP that gives me a lot of hard times.
The sp gets a two parameters #madeByUserId and #reportedByUserId.
I want to have something like:
select * from table
where MadeByUserId = #madeByUserId (if(#reportedByUserID != null) and ReportedByUserID = #reportedByUserID)
Basically I want to make a case in the where clause to include another filter condition based of the null/not null state of the #reportedByUserId
Is that possible?
Thanks a lot,
Radu
Try:
select * from table
where MadeByUserId = #madeByUserId
AND (#reportedByUserID IS null OR ReportedByUserID = #reportedByUserID)
You could use COALESCE.
SELECT *
FROM Table
WHERE MadeByUserId = #madeByUserId
AND ReportedByUserID = COALESCE(#reportedByUserID, ReportedByUserID)
This translates to
if #reportedByUserID is `NOT NULL` then
compare ReportedByUserID with #reportedByUserID
else
compare ReportedByUserID with ReportedByUserID
From MSDN
COALESCE
Returns the first nonnull expression
among its arguments.
Add an if statement
IF (#reportedByUserId IS NOT NULL)
SELECT *
FROM table t
WHERE t.MadeByUserId = madeByUserId etc
I think this will give you what you're after.
IF (#reportedByUser IS NULL)
select * from table
where MadeByUserId = #madeByUserId
ELSE
select * from table
where MadeByUserId = #madeByUserId and ReportedByUserID = #reportedByUserID)