Check null or empty data from three columns in SQL Server - sql

I have a table with three columns and I want to check Null or Empty data from the columns either its is Imp or Main or Comp.
I am using the following query:
SELECT Imp,Main,Comp
FROM Items_tbl
WHERE Contributor = 37
AND NULLIF(Imp, '') IS NULL
AND NULLIF(Main, '') IS NULL
AND NULLIF(Comp, '') IS NULL;

So if you want to COUNT the rows you could just do the following:
SELECT COUNT(*)
FROM Items_tbl
WHERE Contributor=37
AND NULLIF(Imp, '') IS NULL
AND NULLIF(Main, '') IS NULL
AND NULLIF(Comp, '') IS NULL;
Or if you only need one of those columns to be NULL:
SELECT COUNT(*)
FROM Items_tbl
WHERE Contributor=37
AND (NULLIF(Imp, '') IS NULL
OR NULLIF(Main, '') IS NULL
OR NULLIF(Comp, '') IS NULL
);

Based on your comment regarding needing a count...
SELECT Count(*)
FROM Items_tbl
WHERE Contributor=37 and ISNULL(Imp, '') = ''
and ISNULL(Main, '') = ''
and ISNULL(Comp, '') = '' ;

Well I am not sure if I have understood the question correctly, but if you want all the rows where the 3 columns is either NULL/empty, you could try this :
SELECT ID, Contributor,
Imp,
Main,
Comp
FROM Items_tbl
WHERE Contributor = 37
AND (Imp IS NULL OR Imp = '')
AND (Main IS NULL OR Main = '')
AND (Comp IS NULL OR Comp = '')
You can see this here ->SQL fiddle
Note that for this query either all the 3 columns in question should either be all NULL or all empty.
In case, you want all the rows where even one of the aforementioned columns is NULL/empty, you could use a `UNION' to get this as follows :
SELECT ID, Contributor,
Imp,
Main,
Comp
FROM Items_tbl
WHERE Contributor = 37
AND (Imp IS NULL OR Imp = '')
AND (Main IS NULL OR Main = '')
AND (Comp IS NULL OR Comp = '')
UNION
SELECT ID, Contributor,
Imp,
Main,
Comp
FROM Items_tbl
WHERE Contributor = 37
AND (Imp IS NULL)
OR (Main IS NULL)
OR (Comp IS NULL)
See this here -> SQL fiddle
Hope this helps!!!

Try this.
Edit:
SELECT Imp,Main,Comp
FROM Items_tbl
WHERE Contributor=37 AND COALESCE(NULLIF(ISNULL(Imp,''),''),NULLIF(ISNULL(Main,''),''),NULLIF(ISNULL(Comp,''),'')) is NULL

Related

Snowflake -When value doesn't exist make sure its NULL and not empty

I have the following fb.org_story that returns some rows empty, I want to change that so instead of empty it shows NULL (without creating a file format)
select
fb.org_story as pvt_story
from prod.facebook fb
NULLIF is a little short than use a full IFF or CASE statement
SELECT
NULLIF(fb.org_story,'') AS pvt_story
FROM prod.facebook AS fb
But if the string has whitespace around it you might need to TRIM that also, thus I would be inclined to use:
SELECT
NULLIF(TRIM(fb.org_story),'') AS pvt_story
FROM prod.facebook AS fb
So, if you have NULLs and what them displayed as the text NULL we need to convert to TEXT then COALESCE,NVL,IFNULL the desired output
SELECT
fb.org_story AS pvt_story
,fb.org_story::text AS as_text
,NVL(fb.org_story::text, 'NULL') as null_says_null_a
,COALESCE(fb.org_story::text, 'NULL') as null_says_null_b
,IFNULL(fb.org_story::text, 'NULL') as null_says_null_c
,IFF(fb.org_story IS NULL, 'NULL', fb.org_story::text ) as null_says_null_d
FROM VALUES (123), (null) AS fb(org_story)
PVT_STORY
AS_TEXT
NULL_SAYS_NULL_A
NULL_SAYS_NULL_B
NULL_SAYS_NULL_C
NULL_SAYS_NULL_D
123
123
123
123
123
123
NULL
NULL
NULL
NULL
you can use coalesce() as well
select coalesce(fb.org_story,'') AS pvt_story
FROM prod.facebook AS fb
Try One of these if you have Spaces in the data:
-- If you want to return `NULL` values
SELECT NULLIF(TRIM(' '), '') + 1 AS "Test 1"; -- Returns NULL
SELECT NULLIF(TRIM(NULL), '') + 2 AS "Test 2"; -- Returns NULL
SELECT NULLIF(TRIM(''), '') + 3 AS "Test 3"; -- Returns NULL
-- If you want to return calculated values even if the field is null.
SELECT NVL(NULLIF(TRIM(' '), ''), 0) + 4 AS "Test 4"; -- Returns 4
SELECT NVL(NULLIF(TRIM(NULL), ''), 0) + 5 AS "Test 5"; -- Returns 5
SELECT NVL(NULLIF(TRIM(''), ''), 0) + 6 AS "Test 6"; -- Returns 6
Example Usage:
SELECT NULLIF(TRIM(fb.org_story), '') + 7 AS "pvt_story"
FROM prod.facebook AS fb; -- Returns NULL
SELECT NVL(NULLIF(TRIM(fb.org_story), ''), 0) + 8 AS "pvt_story"
FROM prod.facebook AS fb; -- Returns 8

Select only the top 1 value from a column in a table that I'm joining?

So below is the query, how can I store only the top 1 "agencyID" into DCA.AgencyID? I know that the way the query below is structured now it would select all the "agencyID" values and not just the top 1.
SELECT AP.ID
,DCA.AgencyID as agencyID --How to store select top 1?
,replace(LTRIM(RTRIM(AP.UserNameWebsite)), '\', '') AS username
,replace(LTRIM(RTRIM(AP.FirstName)), '\', '') + N' ' + replace(LTRIM(RTRIM(AP.LastName)), '\', '') AS fullName
,LTRIM(RTRIM(AP.EmailAddress)) AS email
,LTRIM(RTRIM(AP.Phone1)) AS phone1
,LTRIM(RTRIM(AP.Phone2)) AS phone2
,LTRIM(RTRIM(AP.GreenSolution)) AS greenSolution
,CASE
WHEN UserType = 'AM'
THEN 1
ELSE 0
END AS producer
FROM DEV01_DataExchange.[DuckCreek].[fpmAgentsProfile] AP
Inner Join [DUCKCREEK_DEV].[DEV01_DuckCreek_Consolidated].[dbo].Agency DCA
on AP.AgencyID = DCA.Reference
WHERE TransType = 'A' AND DC_LastModifiedDate IS NULL AND DCA.Reference is NOT NULL
Your question is a bit vague, but the answer is cross apply:
FROM DEV01_DataExchange.[DuckCreek].[fpmAgentsProfile] AP CROSS APPLY
(SELECT TOP (1) DCA.*
FROM [DUCKCREEK_DEV].[DEV01_DuckCreek_Consolidated].[dbo].Agency DCA
WHERE AP.AgencyID = DCA.Reference
) DCA
WHERE TransType = 'A' AND DC_LastModifiedDate IS NULL AND DCA.Reference is NOT NULL;
Normally an ORDER BY clause would be used. Perhaps ORDER BY DCA.AgencyID DESC? However, if there is a column called AgencyID, I'm surprised it is not being used for the alignment to AP.
Also, some of the WHERE conditions might belong in the subquery.
You can use a Cross Apply instead of the Join:
SELECT AP.ID
,DCA.AgencyID as agencyID
,replace(LTRIM(RTRIM(AP.UserNameWebsite)), '\', '') AS username
,replace(LTRIM(RTRIM(AP.FirstName)), '\', '') + N' ' + replace(LTRIM(RTRIM(AP.LastName)), '\', '') AS fullName
,LTRIM(RTRIM(AP.EmailAddress)) AS email
,LTRIM(RTRIM(AP.Phone1)) AS phone1
,LTRIM(RTRIM(AP.Phone2)) AS phone2
,LTRIM(RTRIM(AP.GreenSolution)) AS greenSolution
,CASE
WHEN UserType = 'AM'
THEN 1
ELSE 0
END AS producer
FROM DEV01_DataExchange.[DuckCreek].[fpmAgentsProfile] AP
Cross Apply
(
Select top 1 AG.*
From [DUCKCREEK_DEV].[DEV01_DuckCreek_Consolidated].[dbo].Agency AG
where AG.Reference = AP.AgencyID
) DCA
WHERE TransType = 'A' AND DC_LastModifiedDate IS NULL AND DCA.Reference is NOT NULL

Update AND select in one statement (with 1 WHERE clause)

How can I simplify the following SQL statement to 1 WHERE clause:
SELECT *
FROM tabA
WHERE (colCar IS NULL OR colCar = '')
OR (colBike IS NULL OR colBike = '')
OR (colTrain IS NULL OR colTrain = '')
UPDATE tabA
SET Distance = 999
WHERE (colCar IS NULL OR colCar = '') OR
(colBike IS NULL OR colBike = '') OR
(colTrain IS NULL OR colTrain = '')
This statement makes no sense, but it is working fine.
I just want avoid to use the WHERE clause twice.
Some ideas?
Thanks in advance!
Mike
SQL Server
SELECT *
FROM tabA
WHERE (colCar IS NULL OR colCar = '')
OR (colBike IS NULL OR colBike = '')
OR (colTrain IS NULL OR colTrain = '')
UPDATE tabA
SET Distance = 999
WHERE (colCar IS NULL OR colCar = '')
OR (colBike IS NULL OR colBike = '')
OR (colTrain IS NULL OR colTrain = '')
Code is working fine
You can use OUTPUT clause to return updated rows:
UPDATE tabA
SET Distance = 999
OUTPUT deleted.colCar
, inserted.colCar
, deleted.colBike
, inserted.Distance
WHERE (colCar IS NULL OR colCar = '') OR
(colBike IS NULL OR colBike = '') OR
(colTrain IS NULL OR colTrain = '')

Replace current table with coalesce statement

I have a table like named innerjoined:
This current table has fields that are empty. And I have a code that removes rows with a blank value.
`SELECT productcode, Brand, product, size FROM innerjoined WHERE
COALESCE(productcode, '') <> '' AND
COALESCE(Brand, '') <> '' AND
COALESCE(product, '') <> '' AND
COALESCE(size, '') <> ''`
So it ends up just like this:
My question is:
How do I update the current table without creating a new one based on this formula?
I have tried the following:
`update innerjoined(SELECT productcode, Brand, product, size FROM innerjoined WHERE
COALESCE(productcode, '') <> '' AND
COALESCE(Brand, '') <> '' AND
COALESCE(product, '') <> '' AND
COALESCE(size, '') <> '')`
First, I just do not understand why you are not using:
SELECT productcode, Brand, product, size
FROM innerjoined
WHERE productcode <> '' AND
Brand <> '' AND
product <> '' AND
size <> '';
It is simpler and does the same thing.
Second, you appear to want delete:
delete i from innerjoined i
where productcode = '' or productcode is null or
brand = '' or brand is null or
product = '' or product is null or
size = '' or size is null;
Here is a db<>fiddle illustrating that all of this code works, with both empty strings and NULLs.

Concatenate first name, last name and middle name with comma

I want to concatenate 3 columns in SQL server as below:
MAX(LTRIM(RTRIM((ISNULL(LastName,'') +
', ' +
ISNULL(FirstName,'') +
', ' +
ISNULL(MiddleName,''))))) AS FullName
I have used value of this column in SELECT clause as:
MAX(FullName) AS FullName,
I would like to handle NULL values, in case all 3 last name, middle name and first name are BLANK or NULL. The query used above will show " , , " in case all 3 columns are NULL or BLANK. But I want to show "N/A" in such case.
Thanks in advance.
You could use a CASE expression:
SELECT MAX(CASE WHEN ISNULL(FirstName, '') = '' AND
ISNULL(MiddleName, '') = '' AND
ISNULL(LastName, '') = ''
THEN 'N/A'
ELSE LTRIM(RTRIM((ISNULL(LastName,'') + ', ' +
ISNULL(FirstName,'') + ', ' +
ISNULL(MiddleName,''))))
END) AS FullName
FROM yourTable
...
Check with COALESCE and then CASE Statement:
Declare #FirstName VARCHAR(50)='',#MiddleName VARCHAR(50),#LastName VARCHAR(50)
SELECT
CASE WHEN ISNULL(COALESCE(#FirstName,#MiddleName,#LastName),'')<>''
THEN ISNULL(#FirstName,'')+',' +ISNULL(#MiddleName,'')+','+ISNULL(#LastName,'')
ELSE 'N/A' END AS FullName
Use Concat like below this will do implicit conversion. So no need to use ISNULL.
select isnull(MAX(LTRIM(RTRIM((concat(LastName,
', ' ,
FirstName,
', ' ,
MiddleName,''))))) ,'n/a')AS FullName from table
The below method may seem quite complicated, but it does make adding or removing columns much simpler, and for all its perceived complexity it isn't actually doing that much under the hood, so doesn't add much overhead.
The first step is to unpivot each of your columns to rows with a common column name, so you would turn
FirstName MiddleName LastName
------------------------------------
A NULL C
Into
Name
------
A
NULL
C
Using CROSS APPLY along with the table value constructor VALUES
SELECT x.Name
FROM (VALUES ('A', NULL,'C')) AS t (FirstName, MiddleName, LastName)
CROSS APPLY (VALUES (1, t.FirstName), (2, t.MiddleName), (3, t.LastName)) x (SortOrder, Name)
ORDER BY x.SortOrder
Then you can remove NULLs and blanks with WHERE ISNULL(Name, '') <> '', then you only have valid data to concatenate together which you can do using SQL Server's XML Extensions. So you end up with a full query like:
WITH TestData AS
( SELECT *
FROM (VALUES ('A'), (NULL)) AS f (FirstName)
CROSS JOIN (VALUES ('B'), (NULL)) AS m (MiddleName)
CROSS JOIN (VALUES ('C'), (NULL)) AS l (LastName)
)
SELECT t.*,
NamesConcat = ISNULL(STUFF(NamesConcat.value('.', 'NVARCHAR(MAX)'), 1, 2, ''), 'N/A')
FROM TestData AS t
CROSS APPLY
( SELECT ', ' + x.Name
FROM (VALUES
(1, t.FirstName),
(2, t.MiddleName),
(3, t.LastName)
) x (SortOrder, Name)
WHERE ISNULL(x.Name, '') <> '' -- NOT BLANK OR NULL
ORDER BY x.SortOrder
FOR XML PATH(''), TYPE
) x (NamesConcat);
Result
FirstName MiddleName LastName NamesConcat
-------------------------------------------------
A B C A, B, C
A NULL C A, C
A B NULL A, B
A NULL NULL A
NULL B C B, C
NULL NULL C C
NULL B NULL B
NULL NULL NULL N/A
select Isnull(FirstName,' ') +' '+ ','+ Isnull(MiddleName,' ')+' '+ ' ,'+ Isnull(Lastname,' ') as Name from personaldata
select FirstName +' '+','+ MiddleName +' '+',' + Lastname as Name from personaldata
Note: The Second query will work fine if all value present and if anyone is null then it will return null for Name, to avoid such kind of concern please use the first query.