SQL Query Not making Sense to me - sql

I think my where clause is wrong.
My dilemma is, if user don't have a record in tbl_dentalBuyerInsurance that means they are taking all of it.
So if user don't have a record in tbl_dentalBuyerInsurance I want them to come back as a result.
I also want them to come back if they do have a record in tbl_dentalBuyerInsurance and it matches using LIKE or equal.
SELECT
[dbo].[tbl_users].*, [dbo].[tbl_dentalBuyerInsurance].*
FROM
[dbo].[tbl_users]
LEFT OUTER JOIN [dbo].[tbl_dentalBuyerInsurance] ON [dbo].[tbl_dentalBuyerInsurance].buyerId = [dbo].[tbl_users].id
LEFT OUTER JOIN [dbo].[tbl_dentalInsurance] ON [dbo].[tbl_dentalInsurance].id = [dbo].[tbl_dentalBuyerInsurance].dentalInsuranceId
WHERE
(
(
[dbo].[tbl_dentalInsurance].companyName LIKE '%Cigna%'
OR [dbo].[tbl_dentalInsurance].companyName = ''
)
AND(
[dbo].[tbl_dentalBuyerInsurance].ppo = 1
OR [dbo].[tbl_dentalBuyerInsurance].ppo = ''
)
AND(
[dbo].[tbl_dentalBuyerInsurance].hmo = 0
OR [dbo].[tbl_dentalBuyerInsurance].hmo = ''
)
)

Given you're using LEFT JOINS, if there's no matching records on the "right" side of the join, all of those right-side fields will be NULL, not empty strings. You'd have to explicitly check for that with .... OR whatever IS NULL, as NULL cannot ever be equal to anything, including itself.

[dbo].[tbl_dentalInsurance].companyName LIKE '%Cigna%'
OR [dbo].[tbl_dentalInsurance].companyName = ''
that means that you are allowinf empty strings, that's your first mistake, and how said MarcB if you are looking for null values so the query is :
[dbo].[tbl_dentalInsurance].companyName LIKE '%Cigna%'
OR [dbo].[tbl_dentalInsurance].companyName is null
if you are allowing empty string so you have to use len function for validate values with lenght 0
saludos

Related

How to perform Case statement inside a select statement?

I wanted to put 'No record' on the column instead of NULL if the datediff function returns a null value.
SELECT concat(e.firstname ,e.lastname) as Fullname,c.shiftcode as Shift, cast(c.datecheckinout as date) Date,datename(month, c.datecheckinout) as RecordMonth,c.timein , c.timeout,
CAST(
CASE
WHEN (datediff(HOUR,c.timein,c.timeout) IS NULL)
THEN 'No record'
END
), FROM tblCheckInOutDetail c RIGHT JOIN tblEmployee e on e.IdEmployee = c.IdEmployee WHERE e.IdEmployee = 55
So far this code only throws Incorrect syntax near 'CAST', expected 'AS'. but I don't know what data type should I put in the CAST parameter , since if there's a record it will show the datetime .
You need to convert the number value to a string. For this, you can use coalesce():
SELECT concat(e.firstname ,e.lastname) as Fullname,c.shiftcode as Shift, cast(c.datecheckinout as date) Date,datename(month, c.datecheckinout) as RecordMonth,c.timein , c.timeout,
COALESCE(CAST(datediff(HOUR, c.timein, c.timeout) AS VARCHAR(255)), 'No record')
FROM tblEmployee e LEFT JOIN
tblCheckInOutDetail c
ON e.IdEmployee = c.IdEmployee
WHERE e.IdEmployee = 55;
Note: I switched the RIGHT JOIN to a LEFT JOIN. They are equivalent logically. But most people find it much easier to follow the logic of the LEFT JOIN, because the table that defines the rows is the first table being read in the FROM clause.
Strictly answering question (though I don't understand why you need a CASE expression if you have working versions of the query), you can easily translate this to a CASE expression:
ISNULL(CAST(datediff(HOUR,c.timein,c.timeout) as varchar),'No Record')
ISNULL really is just nice, convenient shorthand for CASE WHEN a IS NOT NULL THEN a ELSE b END, so:
CASE WHEN DATEDIFF(HOUR, c.timein, c.timeout) IS NOT NULL
THEN CAST(datediff(HOUR,c.timein,c.timeout) as varchar(11))
ELSE 'No Record' END
As you can see, a downside is that if you really really really want a CASE expression, you have to repeat at least the DATEDIFF to cover both the case where the outer row doesn't exist and the case where the outer row exists but one of the values is NULL.
Also note that you should always specify a length for variable types like varchar, even in cases where you think you're safe with the default.
I don't know if this is the correct option or usage.
but this works for me :
ISNULL(CAST(datediff(HOUR,c.timein,c.timeout) as varchar),'No Record')
But can you guys show me how to do this using case expression?

How to substring non constant strings?

I have the following query:
UPDATE AmmUser.ORDINI_SCANSIONATI
SET NUMERO_ORDINE=replace((substring([Text],PATINDEX('%NR. [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%',[Text]),13)),'NR. ',''),
STATO=1
from AmmUser.ORDINI_SCANSIONATIIndexes
inner join AmmUser.ORDINI_SCANSIONATIDocs
on ORDINI_SCANSIONATIIndexes.DocumentID=ORDINI_SCANSIONATIDocs.DocumentID
inner join AmmUser.ORDINI_SCANSIONATI
on ORDINI_SCANSIONATIDocs.RecordID =ORDINI_SCANSIONATI.DsRecordID
where PageNumber IS NULL AND STATO IS NULL
With this query I try to associate the value of substring to my variable NUMERO_ORDINE when I find the "NR." string in the Text column.
Sometimes I don't have the "NR." string, so this query doesn't work and I get wrong values from substring function.
How can I create the same substring when I don't have the "NR." string into Text? I always need to isolate nine numbers.
One method is to use a CASE expression:
(case when [Text] like '%NR. [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%'
then replace(substring([Text],
PATINDEX('%NR. [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%', [Text]),
13
), 'NR. ', ''
)
end),
STATO = 1
You can also add the pattern to the end of the string when it is being searched:
replace(substring([Text],
PATINDEX('%NR. [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%',
[Text] + 'NR. 000000000'),
13
), 'NR. ', ''
),
STATO = 1
This is a little tricky in this case because the pattern is a little complicated.
I noticed that my code sometime has prefix "NR." and sometime suffix "DEL" (in many cases I have both at the same time). So I used the first solution provided by Gordon with a little customization:
UPDATE AmmUser.ORDINI_SCANSIONATI
SET NUMERO_ORDINE = CASE
WHEN [Text] like '%NR. [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%'
THEN REPLACE(SUBSTRING([Text],PATINDEX('%NR. [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%',[Text]),13),'NR.','')
WHEN [Text] like '%[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] DEL%'
THEN REPLACE(SUBSTRING([Text],PATINDEX('%[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] DEL%',[Text]),9),'DEL','')
ELSE 'ERRATA LETTURA'
END,
STATO=1
FROM AmmUser.ORDINI_SCANSIONATIIndexes
INNER JOIN AmmUser.ORDINI_SCANSIONATIDocs ON ORDINI_SCANSIONATIIndexes.DocumentID=ORDINI_SCANSIONATIDocs.DocumentID
INNER JOIN AmmUser.ORDINI_SCANSIONATI ON ORDINI_SCANSIONATIDocs.RecordID =ORDINI_SCANSIONATI.DsRecordID
WHERE PageNumber IS NULL AND STATO IS NULL

Problem with field not equal to null in case statement

So I have EXISTS in huge query which looks like this:
EXISTS(
SELECT
*
FROM
ExistTable
WHERE
ExTableFieldA = #SomeGuid AND
ExTableFieldB = MainTableFieldB AND
ExTableFieldA <> (
CASE
WHEN MainTableFieldZ = 10 THEN MainTableFieldYYY
ELSE NULL
END
)
)
The problem comes from ELSE part of CASE statement, this ExTableFieldA <> NULL will be always false. I could easily write another parameter #EmptyGuid and make it equal to '00000000-0000-0000-0000-000000000000' and everything will work but is this the best approach ?
Pretty much I want to execute another check into the exist for the small size of the records which return the "main" query.
How about removing the case and just using boolean logic?
WHERE ExTableFieldA = #SomeGuid AND
ExTableFieldB = MainTableFieldB AND
(MainTableFieldZ <> 10 OR ExTableFieldA <> MainTableFieldYYY)
I would also recommend that you qualify the column names by including the table alias.
Note: This does assume that MainTableFieldZ is not NULL. If that is a possibility than that logic can easily be incorporated.
ELSE NULL is implied even if you don't list it, but you could use ISNULL here.
ISNULL(ExTableFieldA,'') <> (
CASE
WHEN MainTableFieldZ = 10 THEN MainTableFieldYYY
ELSE ''
END
)
You may need to use some other value like 9999 instead of ''

CASE expression with NULL value

I'm struggling to understand how to check for a null value in a progress case expression. I want to see if a column exists and use that, if not use the fallback column. For example, William in first name would be over written by Bill in fn.special-char.
I've got the following query:
SELECT
"PUB"."NAME"."LAST-NAME" as LastName,
CASE fn."SPECIAL-CHAR"
WHEN is null THEN "PUB"."NAME"."FIRST-NAME"
ELSE fn."SPECIAL-CHAR"
END as FirstName
FROM "PUB"."NAME"
LEFT OUTER JOIN "PUB"."DAT-DATA" fn on "PUB"."NAME"."NAME-ID" = fn."DAT-SRC-ID" and 11 = fn."FLD-FIELD-ID"
When I run the query I get:
ORBC Progress OpenEdge Wire Protocol driver][OPENEDGE]Syntax error SQL statement at or about "is null then "PUB"."NAME"."FIRST-" (10713)
If I do a select * I see everything. It just doesn't like the null part. I can also change the when is null to when 'bob' and it works.
Is there something different I need to do to use a null value in a progress db query?
The shorthand variation of the case statement (case expression when value then result ...) is a shorthand for a series of equality conditions between the expression and the given values. null, however, is not a value - it's the lack thereof, and must be evaluated explicitly with the is operator, as you tried to do. In order to do this properly, however, you need to use a slightly longer variation of the case syntax - case when condition then result ...:
SELECT
"PUB"."NAME"."LAST-NAME" as LastName,
CASE WHEN fn."SPECIAL-CHAR" IS NULL THEN "PUB"."NAME"."FIRST-NAME"
ELSE fn."SPECIAL-CHAR"
END as FirstName
FROM "PUB"."NAME"
LEFT OUTER JOIN "PUB"."DAT-DATA" fn on "PUB"."NAME"."NAME-ID" = fn."DAT-SRC-ID" and 11 = fn."FLD-FIELD-ID"
Instead of CASE you can use IFNULL function in Progress 4GL.
SELECT
"PUB"."NAME"."LAST-NAME" as LastName,
IFNULL(fn."SPECIAL-CHAR", "PUB"."NAME"."FIRST-NAME") as FirstName
FROM "PUB"."NAME"
LEFT OUTER JOIN "PUB"."DAT-DATA" fn on "PUB"."NAME"."NAME-ID" = fn."DAT-SRC-ID" and 11 = fn."FLD-FIELD-ID"

Oracle no results, small query

I am having trouble with some sql. When I run the following query:
Select * from teleapp;
I get TONS of results. Resulst which include a column (called cashwithappyn) that has TONS of empty or null data cells. (They look empty and don't say null)
The column info is:
ColumnName ID Null? Data Type Histogram Num Distinct Num Nulls Density
CASHWITHAPPYN 54 Y VARCHAR2(1 Byte) Frequency 2 56895 0
When I try to run the following query:
Select * from teleapp where cashwithappyn = null;
or
Select * from teleapp where cashwithappyn = '';
or
Select * from teleapp where cashwithappyn not like '';
or
Select * from teleapp where cashwithappyn not in ('Y','N');
or ANY type of combination, I cannot seem to get all of the rows with nothing in cashwithappyn.
Any ideas? Please help, this is the last part of a project that I was assigned to do and I just need to figure this out.
Thanks.
Maybe the column contains blanks. In that case you can do
WHERE TRIM(CASHWITHAPYYN) IS NULL
TRIM removes all blanks before and after and if nothing is left anymore the value becomes NULL
e.g.
TRIM(' ') IS NULL -- one blank removed = true
TRIM(NULL) IS NULL -- true
Also NULL cannot be compared with = NULL but must be phrased IS NULL. NULL is not a value as such and that is why the comparison never works.
You need to use IS NULL
Select * from teleapp where cashwithappyn is null;
Logical test expressions (=, Not In, Like etc) with null result in a false so all of the following result in false
1 = NULL
1 <> NULL
NULL = NULL
NULL <> NULL
NULL NOT IN ('a','b')
NULL Not Like NULL
Additionally in oracle the zero length string is null so NOT LIKE '' will never return any rows
You'll need to use either is null, is not null or Coalesce
A co-worker and I did a bunch of research, here's what we came up with that will work. Any ideas why this works but not the others?
Select * from teleapp where nvl(cashwithappyn,'U') = 'U';