Better way of writing this SQL WHERE Clause - sql

I have something similar to the following WHERE clause in my SQL statement:
AND (ipdp.UserID!=dbo.fn_userid(ipdp.ItemID) OR dbo.fn_userid(ipdp.ItemID) IS NULL)
However, I don't like how dbo.fn_userid function is being ran twice. How can I improve this line of code so that it only has to be ran once?
ipdp.UserID is always a Non-NULL Integer value
dbo.fn_userid can return a NULL or an Integer value
Cheers.

Try:
AND ipdp.UserID != ISNULL(dbo.fn_userid(ipdp.ItemID), -1)

Related

Conditional WHERE clause with operator in statement [duplicate]

This question already has answers here:
Conditional WHERE statement SQL Server
(4 answers)
Closed 4 years ago.
I have a stored procedure that I'm trying to do a conditional WHERE clause on. I believe the solution is easy but for some reason it's escaping me.
What I'm trying to achieve is: if a ID (#pbid in this case) is passed to the stored procedure I only want to return a single record matching that parameter otherwise I'd like to return all results in the table.
Here is the what I have come up with and it's obviously not going to work because I'm trying to do an equals evaluation at PBID (PBID =) and I'm looking to conditionally make that
where pb.PBID =
CASE WHEN #pbid is not null THEN
#pbid --just return results with this ID
ELSE
is not null --return all results
END
If it was C# or something I'd write it like:
if(intPBID > 0) --parameter set, only return results with that param
{
pb.PBID = intPBID
}
else
{
pb.PBID > 0 --return everything
}
I hope this isn't too confusing and I'd appreciate any feedback.
Thanks
I'm not sure about performance implications, but I typically end up doing something like:
SELECT *
FROM table
WHERE (#pbid IS NULL OR pb.PBID = #pbid)

Is there a way to make NULL behave like 0 (zero) or like an empty string in SQL?

Assume a sqlite database with an integer column.
Now, it tends to happen that the integer field contains NULL values (=unset) as well.
I would like to interpret NULL values as zero (0) when doing queries on that field.
Is there a way to tell sqlite that I like NULL handled like 0 in this case, especially when I do comparisons using a SELECT statement?
Since I construct the queries dynamically in C-like code, I like to be able to write something like this:
query = "SELECT * FROM tbl WHERE intField=" + IntToStr(anIntValue)
Currently, I work around this with code as follow, which I like to avoid:
if (anIntValue == 0) {
query = "SELECT * FROM tbl WHERE intField IS NULL OR intField=0"
} else {
query = "SELECT * FROM tbl WHERE intField=" + IntToStr(anIntValue)
}
Maybe there's an operator I can use in the query that converts NULLs to other values I specify?
Of course, another way would be to make sure one never ends up with NULL values in that field, but one might want to be able to tell when the value hasn't been set at all yet, so I like to be able to keep the NULL values in the database.
In Standard SQL this is called COALESCE:
COALESCE(col, 0)
Why using a proprietary extension like IFNULL/NVL if there's a Standard which is supported by every DBMS?
please, try ifnull function, see doc at http://www.sqlite.org/lang_corefunc.html#ifnull
You can use IFNULL
or
CASE WHEN fieldname IS NULL THEN 0 ELSE fieldname END
This works the same as isnull(fieldname, 0)
You can read more here
Although you could use null coalesce functionality of your RDBMS, a universal approach exists that lets you treat NULLs as zeros in a condition, like this:
String val = IntToStr(anIntValue)
"SELECT * FROM tbl WHERE intField=" + val + " OR (0="+ val+" AND intField IS NULL)"

Select with NVL2 Not working Oracle

I am selecting values from the database using Functions. I have three different functions in which if the first does not return anything I check for the second and third functions for values using NVL2. The problem is when I execute independent functions they return values but not in the NVL2 function My query is:
select NVL2(CRBP.FPDATE(LAM.ACID),
CRBP.FPDATE1(LAM.ACID),
CRBP.ODSANCDATE(GAM.ACID)) from
tbaadm.lam, TBAADM.GAM
where gam.acid = lam.acid
and gam.acid = 'VM12990'
This does not return any value.
But when I execute :
select CRBP.FPDATE (LAM.ACID) from tbaadm.lam where lam.acid = 'VM12990';
This Already returns a value. Shouldn't this be the value returned by my first query considering that it is the first in the check. What is the Problem with My first Query??
If CRBP.FPDATE returns a value the query should return the value returned by the function CRBP.FPDATE1 and if CRBP.FPDATE returns NULL then the query should return CRBP.ODSANCDATE's vlaue.
Does CRBP.FPDATE1 return anything?
NVL2(a,b,c) is a "if a is null then a else b" type function. so the value of a is never returned.
it sounds like you want COALESCE which will return the first not null value from the set of parameters

SQL: Select (null = null);

This question is out of a databases exam i was looking at, so it might be nothing one can ever use in a real situation...
What output does the following valid SQL statement produce? Explain your answer!
SELECT (NULL = NULL);
I can easily produce the output of the statement, which is
school=> select (null = null);
?column?
----------
(1 row)
in psql 8.4.11, but how and why this is the answer i don't know... I would have guessed it tries to evaluate the expression inside the brackets and comes up with true/false but apparently it doesn't.
Any hints on why it behaves like it does?
Thanks
NULL stands for "Unknown Value". It is not known whether a value is true or false or anything else.
So, when comparing two unknown values, what would the answer be? Is UnknownA equal to UnknownB?
Answer? Unknown...
Here is an example for SQL Server:
IF (NULL = NULL)
PRINT 'Equals'
IF (NULL != NULL)
PRINT 'Not Equals'
IF (NULL IS NULL)
PRINT 'IS'
IF (NULL IS NOT NULL)
PRINT 'IS NOT'
The only thing that gets printed: IS
I suppose, the expected answer is NULL. That's what MySQL does. That's what PostgreSQL returns as well, actually. Probably, your SQL client just doesn't show the single row where the only returned value is a NULL.
MS SQL server doesn't have a boolean type, though, so it cannot just select a result of boolean expression. So the result in MS SQL is an error.
The point of the question is to check your understanding of NULL logic in SQL. Instead of =, you should use the IS operator when comparing to NULL (unless the ANSI_NULLS option is set to true in MySQL).

What does this SQL Query mean?

I have the following SQL query:
select AuditStatusId
from dbo.ABC_AuditStatus
where coalesce(AuditFrequency, 0) <> 0
I'm struggling a bit to understand it. It looks pretty simple, and I know what the coalesce operator does (more or less), but dont' seem to get the MEANING.
Without knowing anymore information except the query above, what do you think it means?
select AuditStatusId
from dbo.ABC_AuditStatus
where AuditFrequency <> 0 and AuditFrequency is not null
Note that the use of Coalesce means that it will not be possible to use an index properly to satisfy this query.
COALESCE is the ANSI standard function to deal with NULL values, by returning the first non-NULL value based on the comma delimited list. This:
WHERE COALESCE(AuditFrequency, 0) != 0
..means that if the AuditFrequency column is NULL, convert the value to be zero instead. Otherwise, the AuditFrequency value is returned.
Since the comparison is to not return rows where the AuditFrequency column value is zero, rows where AuditFrequency is NULL will also be ignored by the query.
It looks like it's designed to detect a null AuditFrequency as zero and thus hide those rows.
From what I can see, it checks for fields that aren't 0 or null.
I think it is more accurately described by this:
select AuditStatusId
from dbo.ABC_AuditStatus
where (AuditFrequency IS NOT NULL AND AuditFrequency != 0) OR 0 != 0
I'll admit the last part will never do anything and maybe i'm just being pedantic but to me this more accurately describes your query.
The idea is that it is desireable to express a single search condition using a single expression but it's merely style, a question of taste:
One expression:
WHERE age = COALESCE(#parameter_value, age);
Two expressions:
WHERE (
age = #parameter_value
OR
#parameter_value IS NULL
);
Here's another example:
One expression:
WHERE age BETWEEN 18 AND 65;
Two expressions
WHERE (
age >= 18
AND
age <= 65
);
Personally, I have a strong personal perference for single expressions and find them easier to read... if I am familiar with the pattern used ;) Whether they perform differently is another matter...