I'm trying to do a wildcard retrieve if a defined variable is blank. But I can't figure out the correct syntax.
SELECT ...
FROM ...
WHERE customers = CASE
WHEN ISNULL(#customerID, '') = '' THEN LIKE '%'
ELSE #customerID
END
It is as simple as this:
WHERE customers = NULLIF(#customerID, '') OR NULLIF(#customerID, '') IS NULL
The expression NULLIF(x, '') will convert '' to null. Then we take advantage of how null comparison works:
If #customerID is not null then first condition will be true only for exact match
If #customerID is null then first condition will be false (nothing equals null) but second condition will be true for all rows
DB<>Fiddle
You can just simply put it like this
SELECT...
FROM...
WHERE customers = ISNULL(#customerID,'') OR (ISNULL(#customerID,'') = '')
This should work because if the first condition was met, it will select the specific customer id. Otherwise, if the customer id is null,it will select all data because of this condition below:
(ISNULL(#customerID,'') = ''
If NULL, '' = '' will be true.
Related
This question already has answers here:
CASE in WHERE, SQL Server
(5 answers)
Closed 4 years ago.
I'm creating a query (to eventually be used in a stored procedure) with multiple variations on what criteria is entered in a form. Sometimes there can be an entry, sometimes not. Sometimes the data field has a value, sometimes it's NULL.
The fields in my form are NAME, SSN, and DRLICENSE.
DECLARE #name VARCHAR(30);
DECLARE #ssn VARCHAR(10);
DECLARE #drlic VARCHAR(10);
--(if for example, someone enters data in two of the fields like this...)
SET #name = 'SMITH'
SET #drlic = 'D'
(In stored procedure)
SET #name = #name + '%'
SET #ssn = #ssn + '%'
SET #drlic = #drlic + '%'
SELECT
NAME,
SSN,
DRLICENSE
FROM
TABLE
WHERE
NAME LIKE CASE WHEN LEN(#name) > 1 THEN #name ELSE NAME END
AND SSN LIKE CASE WHEN len(#ssn) > 1 THEN #ssn ELSE SSN END
AND DRLICENSE LIKE CASE WHEN LEN(#drlic) > 1 THEN #drlic ELSE DRLICENSE END
The idea behind my case statement is to check the variable for usage and perform a like if the name, ssn, or drlicense are partial entries.
My question is: how do I account for the case of NULL in the table column (i.e. SSN LIKE SSN does not work when SSN is NULL because SSN IS NULL needs to be there).
This isn't going to perform well, especially since you are using LIKE but parentheses are important here
where ((#name is null or name like '%' + #name + '%') or ( name is null))
and ((#ssn is null or ssn like '%' + #ssn + '%') or (ssn is null))
and ((#drlic is null or DRLICENSE like '%' + #drlic + '%') or (DRLICENSE is null))
This will return the NULL values in those columns regardless if a parameter is passed in or not. If you don't want the NULL then just remove the or ( name is null)) section from each line. I wasn't certain from your post.
if length(#foo) <= 1
set #foo = NULL
if length(#bar) <= 1
set #bar = NULL
...
WHERE (#foo is NULL or t.foo = #foo)
AND (#bar is NULL or t.bar like #bar)
OPTION (RECOMPILE)
This should do it:
WHERE (#name IS NULL OR name LIKE #name + '%')
AND (#ssn IS NULL OR ssn LIKE #ssn + '%')
AND (#drlic IS NULL OR drlicense LIKE #drlic + '%')
Note that if, for example, user searched for name = foo then it will return rows that match foo% and not rows that have NULL name.
You can inline adding the wild card to the parameter value and add your null checks inline as well. There is no need for a CASE statement either. For each of the parameter/column values the result returns true if the parameter is null or if the column value is null or if the column value starts with the passed in parameter value.
Where statement:
WHERE (Name IS NULL OR #name IS NULL OR Name LIKE #name + '%')
AND (SSN IS NULL OR #ssn IS NULL OR SSN LIKE #ssn + '%')
AND (DRLICENSE IS NULL OR #drlic IS NULL OR DRLICENSE LIKE #drlic + '%')
The key here is to not do any filtering if the incoming value to use is null or if the column value is null which I assume you do not want filtered on if it is null.
You could use ISNULL() it's very useful in cases like yours.
SELECT
NAME,
SSN,
DRLICENSE
FROM
TABLE
WHERE
ISNULL(NAME,0) LIKE ISNULL(ISNULL(#name, NAME),0)
AND ISNULL(SSN,0) LIKE ISNULL(ISNULL(#ssn, SSN),0)
AND ISNULL(DRLICENSE,0) LIKE ISNULL(ISNULL(#drlic, DRLICENSE),0)
This method will replace the NULL values with the column value if the column value is NULL then both will be set to 0 (which will be 0=0, which will always be true).
If I understand correctly, you want a NULL-safe equality. That is, you want NULL to match NULL and values to match values. So:
where (name = #name or (name is null and #name is null)) and
(ssn = #ssn or (ssn is null and #ssn is null)) and
(drlicense = #drlicense or (drlicense is null and #drlicense is null))
or, an intriguing variant:
where (select count(*)
from (select distinct *
from (values (name, 'name'), (#name, 'name'), (ssn, 'ssn'), (#ssn, 'ssn'), (drlicense, 'drlicense'), (#drlicense, 'drlicense')
v(val, which)
) x
) = 3
This is using group by semantics to combine NULL values.
Or, if you want some obfuscation:
where nullif(name, #name) is null and nullif(#name, name) is null and
nullif(ssn, #ssn) is null and nullif(#ssn, ssn) is null and
nullif(drlicense, #drlicense) is null and nullif(#drlicense, drlicense) is null
I want to search for non null values from the 'currentsheet' which works fine but some fields are actually blank rather than null. How can I find blank fields using postgreSQL as the below has not worked and still displays blank values under the 'currentsheet' field.
SELECT *
FROM PUBLIC._http_requests
WHERE (_http_requests.currentsheet IS NOT NULL OR _http_requests.currentsheet <> '')
AND _http_requests.session_id IS NOT NULL
AND _http_requests.http_referer IS NOT NULL
You need to use AND to check _http_requests.currentsheet. If it was NULL, then it would always be true for the <> '' check and vice versa.
As a way simpler example, you can use select statements without a table to help debug this sort of thing (from psql or whatever SQL query tool you like):
select ('' is not null or '' <> '') as empty_result,
(null is not null or null <> '') as null_result;
empty_result | null_result
--------------+-------------
t |
If the string is '', you get true. If the string is null, you get null (this is because comparisons with null are SQL oddities -- select null = null; results in null). Let's see what happens when we replace or with and:
select ('' is not null and '' <> '') as empty_result,
(null is not null and null <> '') as null_result;
empty_result | null_result
--------------+-------------
f | f
Neat! With X is not null and X <> '', we get false when X is either '' or null.
So the way to phrase the select statement to do what you actually want is:
SELECT *
FROM PUBLIC._http_requests
WHERE _http_requests.currentsheet IS NOT NULL
AND _http_requests.currentsheet <> ''
AND _http_requests.session_id IS NOT NULL
AND _http_requests.http_referer IS NOT NULL;
I think you just need AND _http_requests.currentsheet <> ''. The AND is important there so that we exclude both.
I'm trying to write his in sql:
SET `Field` = (
If `Field` is empty then "b",
if `Field` is not empty, concat(`Field`,"_b"))
Meaning, if Field had value a it would change to a_b, if it was empty, it would change to b
Is there an sql synthax that creates this if..else statement properly?
IF(Field = "" or Field IS NULL,'b',concat(Field,'_b'))
You can use a CASE statement.
Example:
SELECT
CASE
WHEN myField IS NULL THEN 'b'
WHEN myField = '' THEN 'b'
ELSE myField + '_b'
END
FROM myTable
You need to use the CASE keyword.
Something like
UPDATE tbl
SET field =
CASE
WHEN field = ''
THEN 'b'
ELSE field + '_b'
END
You can use Cases but you can shorten it like this:
set Field = isnull(field, '')
+ case when isnull(field, '') = '' then '' else '_' end
+ 'b'
I am trying to write a SQL Select statement to return records based on a user input through a front end.
I want to write the Select statement like this:
SELECT somefields
FROM sometable
WHERE CASE variable
WHEN 'blank' THEN field IS NULL
ELSE field = field
END
Basically I either want to filter a column to find NULL values or ignore the filter and return all values depending on the value of the variable. I know that the results of the CASE statement is not executable but how can I do this?
When variable is 'blank', the following query will give you rows where field is NULL. When variable is anything else, it will give you all rows:
SELECT somefields
FROM sometable
WHERE
(variable = 'blank' AND field IS NULL)
OR (variable <> 'blank')
You can use NULLIF() (link is for SQL Server, but NULLIF() should be standard):
SELECT somefields
FROM sometable
WHERE field = NULLIF(variable, 'blank')
The following snippet should behave as follows:
when #variable is null, return all rows
when #variable = 'blank', return all rows where field is null or field = 'blank'
otherwise, return rows where #variable equals field
Code snippet:
WHERE 1 = CASE
WHEN #variable is null then 1
WHEN #variable = 'blank' and field is null then 1
WHEN #variable = field then 1
END
SELECT somefields
FROM sometable
WHERE ((variable IS NULL OR variable = 0) OR (variable = field))
WHERE Criteria is apply when variable have value
For Example:
DECLARE #CityName VARCHAR(50)
SET #CityName = NULL
SELECT CityName
FROM City
WHERE ((#CityName IS NULL ) OR (#CityName = CityName ))
When City is null then tables return all rows
I think I get what you're after. Something like this maybe?
SELECT field1,
field2,
CASE variable
WHEN 'blank' THEN NULL
ELSE field3
END as field3
FROM sometable
Think I understand what you mean....for example....
SELECT
House, Postcode
from
SomeTable
where
(House=isnull(#House,House) or (House is null and #House is null))
and
(Postcode=isnull(#Postcode,Postcode) or (Postcode is null and #Postcode is null))
First bit of the conditional where is to use the variable, when present (the isnull bit is to ignore the variable if it's null)
Second bit of the conditional where is in case your evaluative field is null also as effectively fields don't = null they are 'is null'.
Confused? Good. Works on what I'm doing though!
Here is my solution based on #Andomar answer above aimed at anyone testing an input varchar value, you need to test the parameter in the right order as per the example below:
FIELD1 = CASE
WHEN #inputParameter = '' THEN FIELD1
WHEN #inputParameter <> FIELD1 THEN NULL -- if input is some text but does not match
WHEN #inputParameter IS NULL THEN FIELD1
WHEN #inputParameter != '' AND FIELD1 = #inputParameter THEN FIELD1
END
Hope this helps someone.
Execute where clause depending on the column value
Hi, so here's my problem.
I need to have a query with a where clause bu the condition is depending on the value of a certain field.
Heres the structure:
ID NAME CUSTOMERTYPE STUDENTNO
basically here;s the lofic:
SELECT * FROM TRANSACTTABLE WHERE ID <> ''AND(NAME <> ''
--CASE WHEN CUSTOMERTYPE='STUDENT' THEN EXCEUTE THIS QUERY:
AND STUDENTNO <> '')
--ELSE WHEN CUSTOMERTYPE <> 'STUDENT' THEN EXECUTE JUST THIS:
)
PLEASE HELP. THANKS
Your query is showing some strange design - ID and CUSTOMERTYPE of type 'string', are you sure that it should be done this way?
SELECT *
FROM TRANSACTTABLE
WHERE ID <> '' AND
NAME <> '' AND
(CUSTOMERTYPE <> 'STUDENT' OR STUDENTNO <> '')
In MySQL you can use the IF function like this
SELECT * FROM TRANSACTTABLE
WHERE ID <> '' AND IF(CUSTOMERTYPE='STUDENT',STUDENTNO <> '',1=1)