SQL querying with DATES - not pulling correct data - sql

I'm running a simple query where I am trying to filter by a date, like this...
Select * from tblPurchasedProducts
WHERE PurchasedOn >= '11/04/2016' AND PurchasedOn <= '11/08/2016'
But I am not able to see any results for 11/8/2016. I'm only able to see everything prior to 11/08/2016.
The date is saved in SQL SERVER as smalldatetime. I'm really not sure if this has anything to do with it.
Is the time an issue in this case.
I am required to save the PurchasedOn date with as datetime
EDIT:
#lamak
WHERE PurchasedOn >= '20161104' AND PurchasedOn <= '20161108'

You need to be careful with your conditions. By using <= '11/08/2016' it's using the 00:00:00 time, that's why you are not getting results. Use:
SELECT *
FROM tblPurchasedProducts
WHERE PurchasedOn >= '20161104' AND PurchasedOn < '20161109';

Dates in SQL are formatted YYYY MM DD, so you would write '2016/04/11'
Unless you override it but you will need to specify the date format.
Try:
Select * from tblPurchasedProducts
WHERE PurchasedOn BETWEEN '2016-11-04' AND '2016-11-08'

Related

How to SELECT between two dates in SQL Server

I need to give a select count in a table using the range of two dates, however my dates are in "yyyy-MM-dd" format, and when I execute the select SQL it returns the following error:
Converting a varchar data type to a datetime data type resulted in a value out of range
Here is the query I'm using:
SELECT COUNT(*) AS score
FROM requests
WHERE date_em BETWEEN '2019-04-01' AND '2019-04-30'
Table structure
date_em = DATETIME
Can someone help me?
My preferred method is:
SELECT COUNT(*) AS score
FROM requests
WHERE date_em >= '2019-04-01' AND
date_em < '2019-05-01'
This handles the time component and will make use of an index.
The following also works well in SQL Server:
SELECT COUNT(*) AS score
FROM requests
WHERE CONVERT(date, date_em) BETWEEN '2019-04-01' AND '2019-04-30'
In SQL Server, this will also use an index (if available). However, normally functions on columns preclude the use of an index, so I'm more hesitant about this approach.
have you try this
SELECT COUNT(*) AS score FROM requests WHERE date_em BETWEEN '2019-04-01 00:00' AND '2019-04-30 23:59'
add 00:00 and 23:59 to make it look like a DateTime.

SQL Convert Date from dd.mm.yyyy to dd-mm-yyyy

I want to select data which is set in a specific date range. Unfortunately I get the date in this form:
01.05.2016 and 02.06.2016
In the database, the date are in the form:
2013-06-21
How can I convert the date in my sql query?
SELECT `artikel`.*
FROM `artikel`
WHERE (buchungsdatum >= '01.05.2016') AND (buchungsdatum <= '02.06.2016')
If this is MySQL, you can use STR_TO_DATE:
SELECT `artikel`.*
FROM `artikel`
WHERE
buchungsdatum >= STR_TO_DATE('01.05.2016','%d.%m.%Y')
AND buchungsdatum <= STR_TO_DATE('02.06.2016', '%d.%m.%Y')
Check here for the available date formats.
Try DATE_FORMAT() function of mysql as DATE_FORMAT() function is used to display date/time data in different formats.:
SELECT `artikel`.*
FROM `artikel`
WHERE (DATE_FORMAT(buchungsdatum, "%d.%m.%Y") >= '01.05.2016') AND (DATE_FORMAT(buchungsdatum, "%d.%m.%Y") <= '02.06.2016')
You can try this:
select
SUBSTRING(convert(varchar(10),REPLACE('01.05.2016','.', ''),103),5,4)+ '-'+
SUBSTRING(convert(varchar(10),REPLACE('01.05.2016','.', ''),103),3,2)+'-'+
SUBSTRING(convert(varchar(10),REPLACE('01.05.2016','.', ''),103),1,2)
It formats 01.05.2016 to 2016-05-01
I have to mention that it changes the 01.05.2016 to 01052016 and then it formats it.

SQL Server : Comparing Time

I am trying to compare time in my SQL query. However, when I run the query, I get zero result but I can see that in the table, there are records that should appear.
The query is as such:
SELECT *
FROM dbo.Alarms
WHERE StartDate <= '26/08/2015'
AND StartTime <= CONVERT(varchar(5), GETDATE(), 108)
The StartDate is stored in the database as YYYY-MM-DD and it seems to work fine when I query only with the date.
However, when I add the StartTime is when things don't work. StartTime stores the value in the 24 hour clock format.
What am not doing right?
Thanks
Use a correct datetime format:
SELECT *
FROM dbo.Alarms
WHERE StartDate <= '2015-08-26' AND StartTime <= cast(GETDATE() as date)
Don't compare date/time values as strings. The data types are built into the language. Use them.
I have not explicitly used this scenario but comparing dates can be a problem depending on how the fields are compared.
eg: '28/07/2015' is not less than your startdate as 28 > 26.
You could try comparing dates reformatted into a YYYYMMDD format.
Cheers.

filter DateTime field with now as reference in WHERE clause

I am trying to build a vb.net application with a where clause to filter data using a DateTime field.
My table contains 5 fields and more than 10000 rows. I wanna use a DateTime field to find all the rows older than 7 years from now.
But this script will be re-used many times. So I don't wanna use this kind of where clause cause I don't wanna need to modify the where clause every time I wanna run the application :
select * from myTable WHERE myDateTimeField < '2006-09-07 00:00:00.000'
I'd like to find a way to write a where clause like this :
select * from myTable WHERE myDateTimeField "is older than 7 years from NOW"
I don't use VB.net very often (as you can see), so this thing is really bugging me
Just make use of DateTime:
Dim dateTime As DateTime
dateTime = DateTime.Now.AddYears(-7);
When you're building your SQL string just call ToString on your date (you can obviously format it however you need):
dateTime.ToString("MM/dd/yyyy");
SELECT * FROM myTable WHERE myDateTimeField < DATEADD(YEAR, -7, GETDATE())
That is if the data in the myDateTimeField is in the same local time zone of the sql server.
If your data is in UTC (which it often should be), then use:
SELECT * FROM myTable WHERE myDateTimeField < DATEADD(YEAR, -7, GETUTCDATE())
i think better would be provided you have SQL Server
strQuery = "select * from myTable WHERE myDateTimeField
<= DATEADD(YEAR, -7, GETDATE())"
What you are looking for is a DSL for datetime. Check out this blog post to get some ideas.
http://leecampbell.blogspot.com/2008/11/how-c-30-helps-you-with-creating-dsl.html
Good Luck
P.S.
If you need help translating it into vb.net just submit a comment.

Sybase date comparison - Correct format?

I'm pretty new to Sybase and am writing a query to return results after a specified date, and also before a specified date. MM/DD/YYYY format
At the moment im doing..
SELECT *
From aTable
WHERE afterDate >= 08/07/2013
AND beforeDate <= 08/08/2013
I'm getting records back, but as I'm a Sybase newbie, I want to be sure Sybase is interpreting these dates correctly..
Their online doc is pretty bad for basic explanations on things like this!
Anyone able to confirm if what I have works, or does it need some formatting round the dates?
You'll need to convert the dates into DATETIME and tell sybase what the format is to be sure.
According to this documentation the code for MM/DD/YYYY is 101, so something like this:
SELECT *
FROM aTable
WHERE afterDate >= CONVERT(DATETIME,'08/07/2013',101)
AND beforeDate <= CONVERT(DATETIME,'08/08/2013',101)
You can see the difference by running the following select statements:
SELECT CONVERT(DATETIME,'08/07/2013',101) --MM/DD/YYYY (2013-08-07 00:00:00.000)
SELECT CONVERT(DATETIME,'08/07/2013',103) --DD/MM/YYYY (2013-07-08 00:00:00.000)
For any date-time field in sybase, instead of going through the convert function, there is a more direct approach.
SELECT *
From aTable
WHERE afterDate >= '2013-08-07'
AND beforeDate <= '2013-08-08'
The date has to be in the form 'YYYY-MM-DD'
If you want to add a time, it can be included along with the date. The date and the time have to be separated by a T.
Any date time field can be directly used using the format 'YYYY-MM-DDTHH:MM:SS'
Using the functions is too lengthy. Noone needs a bazooka to shoot a squirrel! :)
CAST( '2000-10-31' AS DATE )
will convert from text to date format....
I am assuming that your two fields (afterDate and beforeDate) are in Date format.
Your example would be:
SELECT *
From aTable
WHERE afterDate >= CAST( '08/07/2013' AS DATE )
AND beforeDate <= CAST( '08/08/2013' AS DATE )
Also, usually (but not always) a date range is on the SAME field. As I said, that is not true all the time and you may have a good reason for that.
The best approach is to use the ANSI standard which does not require any conversion: yyyymmdd (you can also include hh:mm:ss) for instance:
DateField1 >= "20150101" and DateFile1 <= "20150102"
You should decide which Input-Strings the user is going to use as parameter and then convert them and concatenate them like you want, unless it is Datetime it is not important which initial format it had, you can use it in a between-condition.
E. g. the user is from Europe and uses "DD.MM.YY" and "hh:mm" as an input parameter, I would convert and concatenate like this:
WHERE dateCol between convert(DATETIME,
convert(char(11),
convert(DATETIME, '01.06.14', 4), 16) || ' ' || '00:00', 8)
AND convert(DATETIME,
convert(char(11),
convert(DATETIME, '01.07.14', 4), 16) || ' ' || '16:00', 8)