Where statement in my query is supposed to return only today's and yesterday's dates, but is still returning earlier dates - sql

I am looking to only retrieve data from the past 24 hours. The WHERE statement I am using, in theory, should retrieve only from those productiondates. However, I am still having week-old productiondates returned. Any thoughts on how to improve this, or am I doing it wrong? I am using periscope.
select example1,
example2,
example3,
productiondate,
example4,
example5
from final
where exampleX = exampleY or exampleX is null
and productiondate > DATEADD(day,-1, GETDATE())
and example1 <> 'XXX'
and example2 <> 'YYY'
and example2 <> 'ZZZ'
order by 2

Logical operator precedence in SQL can be surprising. You need parentheses around the OR.
where (exampleX = exampleY or exampleX is null)
Alternatively, you could do this:
where coalesce(exampleX, exampleY) = exampleY

Related

Is there any option to replace NVL in where clause for parameter

I have been using NVL in my WHERE clause and it worked well till now.
But in such case where the column has NULL value and parameter was also NULL, it didnt return any query.
select * from Table
where
f_date BETWEEN NVL(:F_DATE_FROM,F_DATE) AND NVL(:F_DATE_TO,F_DATE)
AND op_code = NVL(:CODE, OP_CODE)
AND T_CBC = NVL(:TO_CBC,T_CBC)
order by fiscal_date desc
I updated the query as below, and it returns me all the records as expected. However it takes way too long to execute the query. The original query took 1.5min and the new query takes 7min. Is there any way to fine tune the below query please?
select * from Table
where
f_date BETWEEN NVL(:F_DATE_FROM,F_DATE) AND NVL(:F_DATE_TO,F_DATE)
AND (OP_CODE = :CODE or :CODE is null)
AND (T_CBC = :TO_CBC or :TO_CBC is null)
order by fiscal_date desc
Sure:
WHERE
(f_date >= :F_DATE_FROM OR :F_DATE_FROM IS NULL) AND
(f_date <= :F_DATE_TO OR :F_DATE_TO IS NULL) AND
...
though I'm not sure how much of a performance improvement it'll realize. If your query is about performance specifically, ask a question that includes a query plan

How do I pass a parameter in Report Builder to Firebird database?

I'm looking at doing some report development for one of our Training softwares. I finally got some queries working in FB Maestro, as I'm only familiar with SQL and Oracle.
I have the following query that works and returns results, but when trying to set up a parameter for the display name, the query runs (at least it returns no errors) however the dataset does not return any data. Has anyone worked with these before?
Here's the query:
Select CertStatus, DisplayName, Count(CertStatus) From ( With cte as (Select * From (Select COURSEVERSIONSWITHAGGREGATES.CourseTitle, COURSEVERSIONSWITHAGGREGATES.CourseNumber, "MaxTrainedCompletionDate", "Course_ID", PersonnelView.DISPLAYNAME, COURSEVERSIONSWITHAGGREGATES.RecertificationValue, COURSEVERSIONSWITHAGGREGATES.RECERTIFICATIONUNIT_ID,
CASE
WHEN COURSEVERSIONSWITHAGGREGATES.RECERTIFICATIONUNIT_ID = 3 THEN DATEADD(year, 1*COURSEVERSIONSWITHAGGREGATES.RECERTIFICATIONVALUE, MaxTrainingView."MaxTrainedCompletionDate")
WHEN COURSEVERSIONSWITHAGGREGATES.RECERTIFICATIONUNIT_ID = 2 THEN DATEADD(month, 1*COURSEVERSIONSWITHAGGREGATES.RECERTIFICATIONVALUE, MaxTrainingView."MaxTrainedCompletionDate")
WHEN COURSEVERSIONSWITHAGGREGATES.RECERTIFICATIONUNIT_ID = 1 THEN DATEADD(week, 1*COURSEVERSIONSWITHAGGREGATES.RECERTIFICATIONVALUE, MaxTrainingView."MaxTrainedCompletionDate")
WHEN COURSEVERSIONSWITHAGGREGATES.RECERTIFICATIONUNIT_ID = 0 THEN DATEADD(day, 1*COURSEVERSIONSWITHAGGREGATES.RECERTIFICATIONVALUE, MaxTrainingView."MaxTrainedCompletionDate") END
AS ExpirationDate
From MAXTRAININGVIEW
INNER JOIN PERSONNELVIEW ON (MAXTRAININGVIEW."Personnel_ID" = PERSONNELVIEW.PERSONNELID) INNER JOIN COURSEVERSIONSWITHAGGREGATES ON (MAXTRAININGVIEW."Course_ID" = COURSEVERSIONSWITHAGGREGATES.COURSEID)
WHERE Personnelview.DisplayName = 'Aaron')) Select CourseTitle, CourseNumber, "MaxTrainedCompletionDate", "Course_ID", DisplayName, RecertificationValue, Recertificationunit_ID, ExpirationDate,
CASE WHEN ExpirationDate > current_date Then 'Active' WHEN ExpirationDate < current_date Then 'Expired' END As CertStatus from cte) Group By CertStatus, DisplayName
This returns values with the static value of 'Aaron' in report builder. But trying to use a parameter, it does not throw an error in report builder, however it just does not return any data.
For example this:
WHERE Personnelview.DisplayName = '#DisplayName'))
I've got the parameter based off another data set query, and that seems to work (it gives me the option to select employees)
Here is an example of it passing 'Aaron' (with personal info removed)
Example of passing #FName Parameter:
If you want to pass the parameter in report, other type database might not recognize query like "where [field] in #parameter", so I think you could try to use filter to achieve this goal(create a filter in dataset, and create a parameter, then specify it in filter properties).

optional parameter checking in where clauses

I have a bunch of report parameters and as a result my criteria checking first checks if parameter value is null and if not compares it with a column value .
(#dateStart IS NULL OR #dateStart <= BELGE.AccDate)
AND (#dateEnd IS NULL OR #dateEnd >= BELGE.AccDate)
AND (#CompanyId IS NULL OR #CompanyId = hrktlr.CompanyId)
AND ((#onKayitlarDahil = 1 and hrktlr.StatusCode in ('M', 'O'))
OR (#onKayitlarDahil = 0 AND hrktlr.StatusCode = 'M'))
AND (#BizPartnerId IS NULL or CK.BizPartnerId = #BizPartnerId)
AND (#BizPartnerKodStart is null or #BizPartnerKodStart = '' or #BizPartnerKodStart <= CK.BizPartnerKod)
AND (#BizPartnerKodEnd is null or #BizPartnerKodEnd = '' or #BizPartnerKodEnd >= CK.BizPartnerKod)
AND (#BizPartnerType is null or #BizPartnerType=CK.BizPartnerType)
this is great for a maintainable sql query, but the problem is that Sql Query Optimizer prepares itself for the worst case I guess, and index usage is bad. For example when I pass in BizPartnerId and thus avoid BizPartnerId is null check, query runs a 100 times faster.
So if I keep going with this approach are there any pointers that you can recommend for Query Planner to help increase query performance.
Any viable alternatives to optional parameter checking?
To stop sql server form saving a sub optimal query plan you can use the option WITH RECOMPILE. The query plan will be recalculated each time you run the query.

Alternative to relying on execution order of conditions in SQL 'where' clause

In languages such as JavaScript you can have 2 conditional statements and "protect" the second one with the first one. For instance:
if( scarryObject != null && scarryObject.scarryMethod() ) { ... }
// if scarryObject is null scarryMethod will not be called
I thought I would achieve the same in SQL like so:
where int_date > 19500101
and month(CONVERT(smalldatetime, ... int_date))
The problem here is that if int_date is some "bad" value like -1, 0, 1 the conversion will fail and the sp will stop with an error. I thought the first check int_date > 19500101 would get evaluated first and if false the second condition would be skipped.
It seems like it does not work like this... or? Is there any other way of doing this?
Thanks!
Your query is syntactically not correct, as the clausemonth(CONVERT.... is not a condition.
Let's assume you want to compare with a certain number, a possible way of expressing what you want would be
SELECT *
FROM myTable
WHERE case
when int_date > 19500101
then -1
else month(CONVERT(smalldatetime, ... int_date))
end = #YourMonth
You would 'protect' the evaluation of the 'month' and not the condition.
You could try splitting the query into two. Here is the concept:
SELECT *
FROM (
SELECT *
FROM myTable
WHERE int_date > 19500101
) t
WHERE month(CONVERT(smalldatetime, ... t.int_date))

No Result Returned From SQL Query

I am running the following query, but no rows are returned even though a record exists that should match the query.
SELECT
*
FROM
tblsignup
WHERE
usr_email='amir#gmail.com'
AND
(status=1 or status=2)
You should try by simplifying the query (yeah...even if it's so simple)
try this
Select * from tblsignup
then
Select * from tblsignup where
usr_email = 'amir#gmail.com'
then
Select * from tblsignup where
usr_email='amir#gmail.com' and
status > 0
//I know you won't use > 0 at the end, but we want to eliminate the most cause of error we simplify by > 0 only to be easier to read
Tell us from where you start getting 0 line, this could lead us to the problem, I know I already had a problem like that with a field named "date", because date is already used by MySQL, funny MySQL still let me use that fieldname tho.
Try this:
select * from `tblsignup` where `usr_email`='amir#gmail.com' and (`status`=1 or `status`=2)
I have a feeling "status" might be reserved for something special. It might be worth a shot changing it to `status`.
Try wrapping brackets around the status column name:
SELECT *
FROM tblsignup
WHERE usr_email = 'amir#gmail.com'
AND ([status] = 1
OR [status] = 2);
EDIT
After reading your comment, why not use:
SELECT *
FROM tblsignup
WHERE usr_email = 'amir#gmail.com'
AND [status] > 0;
May it be that your column or table has case sensitive collation and the address is typed different ('Amir...')? As your query is correct SQL. You can find that with:
EXEC sp_help DatabaseName