SQL date comparision in yyyy/mm/dd - sql

Not being that great at sql, i've reached my limit.
I have a date in the yyyy/mm/dd format and i need to get all records "from a week ago"
I think i need some conversion stuff to be done cause this
d.date_begin >= DATEADD(day,-7, GETDATE())
is not working :), i'm TERRIBLE at convert and data type..

This will work if you want records from 7 days ago up to and including today's records
CAST(d.date_begin AS DATE) >= CAST(DATEADD(day,-7, GETDATE()) AS DATE)

where DATEDIFF(month,Your_date_column,getdate()) < 3

SQL server 2012 onwards, if date_begin is of datatype date
where d.date_begin >= cast(DATEADD(day,-7, GETDATE()) as date)
This will get anything in the last 7 days, regardless of time

You should store date/time values using native formats. Ok, sometimes we cannot. But you can easily convert your values to the correct format:
where cast(replace(d.date_begin, '/', '') as date) >= DATEADD(day, -7, GETDATE())
I should note that SQL Server is pretty good about conversions, so your initial code should not generate any errors -- unless you have unusual internationalization settings.
Or, actually, a better way to do this is to convert the current value to a string:
where d.date_begin >= format(dateadd(day, -7, getdate()), 'yyyy/MM/dd')
This is better because it is "sargable", meaning that SQL Server can use an index on the column if available.

SELECT * FROM tbl_name
WHERE date >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY
AND date < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY

Don't manipulate d.date_begin. Making calculation on a column while comparing can give bad performance. You should manipulate getdate() to get the same format as d.date_begin. In this case it works because the format is yyyy/MM/dd - the comparison will give the same result as if both columns were date columns.
WHERE
d.date_begin >= convert(char(10),DATEADD(day,-7, GETDATE()), 111)

Related

Get date of 3 days ago

I have SQL script that selects everything from current day.
SELECT [ClientID] from [logs] where Date > CONVERT (date, SYSDATETIME())
Date is type of DateTime.
How to get everything within last 3 days? I suppose I need subtract 3 days from function SYSDATETIME() result, but how?
SELECT [ClientID] from [logs] where Date > DATEADD(day, -3, CONVERT (date, SYSDATETIME()))
Use GETDATE() : Yes, it gets date from system!
Returns the current database system timestamp as a datetime value
without the database time zone offset. This value is derived from the
operating system of the computer on which the instance of SQL Server
is running.
Query:
SELECT [ClientID] from [logs] where ( Date > GETDATE() - 3)
More Reference:
GETDATE Detailed Documentation
For mysql use this:
SELECT DATE_ADD(CURRENT_DATE, INTERVAL - 3 DAY);
Use BETWEEN
SELECT ClientID
FROM logs
WHERE Date BETWEEN SYSDATETIME() AND SYSDATETIME() - 3
Using BETWEEN is nice. I also prefer the DATEADD function. But be aware of the fact that the SYSDATETIME function (or I would us GETDATE()) also includes the time which would mean that events before the current time but within the three day period may not be included. You may have to convert both sides to a date instead of datetime.
SELECT [ClientID] from [logs] where Date > DATEADD(day, -3, SYSDATETIME())
In my case:
select * from Table where row > now() - INTERVAL 3 day;
So you can fetch all of 3 days ago!

mssql select GETDATE - all day from 00:00 - 23:59

Running MS SQL Server 2008
I have this query:
select count(*) from dbo.study
where study_datetime >= (GETDATE() -1)
that comes back with all of yesterdays exams written to my study table. How would I make it come back with everything done 'today' up to the current time I asked for it? For example I would everything for today from 00:00:00.000 - current time
my values in the 'study_datetime' column look like: 2014-05-06 10:40:31.000
I can't seem to figure this one out. I have tried replacing the '-1' with a '0' but I get back 0 results.
thanks
unfortunately there is no trunc() like in oracle, but since you have the 2008 version you can use:
select count(*) from dbo.study
where study_datetime >= cast(getDate() As Date)
If I understand well (values from same day), I think you can use DATEDIFF function, using the day as datepart.
select count(*) from dbo.study
where datediff(dd, study_datetime, GETDATE()) = 0
and study_datetime <= GETDATE() -- if you need a check for the "future" (datetime after GETDATE() )
To get everything that strictly happened today, just use:
select count(*) from dbo.study
where study_datetime >= cast(getDate() As Date)
and study_datetime < cast(DATEADD(day,1,getdate()) as Date)
When you're working with continuous data, it's almost always better to switch to using semi-open intervals, to ensure that data falls into one and exactly one interval. Usually, when you want "all day", you don't want to exclude things that occurred during the final minute of the day (at e.g. 23:59:37.223 or even at 23:59:59.993). So you'd normally write your query to be >= midnight at the start of the day and < midnight at the start of the following day (note the different types of comparisons)
This is usually a far better idea than trying to compute the last moment of today and use <= (or BETWEEN) for your comparisons.
select count(*) from dbo.study
where study_datetime between :2014-05-06 00:00:00 and :2014-05-06 23:59:59.
It might help you

Easier way to compare a DATE field to the date value of GETDATE?

I have a field in a table Event.EventDate and it's of the data type DATE rather than DATETIME and then I have a view that has the following WHERE clause:
WHERE e.EventDate >= CAST(CONVERT(VARCHAR(MAX), GETDATE(), 101) AS DATETIME)
As you can see, I'm just trying to get all events >= today's date. The above code works, but it's ugly. I tried this ...
WHERE e.EventDate >= CONVERT(VARCHAR(MAX), GETDATE(), 101)
... and this ...
WHERE e.EventDate >= CONVERT(DATETIME, GETDATE(), 101)
... but those didn't work, they gave me every event > today's date. However, even if the above worked, it's still ugly.
Isn't there a better way?
Try:
WHERE e.EventDate >= cast(getdate() as date)
To cast getdate() into a date time. It's a clean way in SQL Server 2008 and up to strip out the time portion of a datetime type.
Using Shan Plourde's method is certainly cleaner and quicker, but for the more general case when you want to round a datetime to a particular time interval, I use
dateadd(dd,datediff(dd,0,[datetime column]),0)
where dd stands for day, and can be replaced with mm (month), hh (hour), mi (minute), and probably others.
If you want to get fancy and round to, say, 15 minute intervals, you can use
dateadd(mi,
-datepart(mi,[datetime column])%15,
dateadd(mi,datediff(mi,0,[datetime column]),0)
)
where % is the modulo operator. You'll get wacky results for this if you don't use an interval that divides 60 evenly.

Find between with separated date fields (year,month,day)

I have the following dates in my table in separated fields. How can I write a query to show the values between two dates.
For example: values between 2/1/2011 and 2/6/2011:
day month year value
--------------------------------------------------
2 6 2011 120
3 7 2011 130
5 5 2011 100
6 1 2011 50
As others have said, my first suggestion would be to use Date. Or if you need more detailed information than your example, Datetime or Timestamp with Time Zone.
But in case you actually have to work with this data, I think something like this should work, depending on your flavor of SQL:
SELECT value, CONVERT(DATE,CONCAT(CONCAT(CONCAT(CONCAT(day, "-"), month), "-"), year), 105) date FROM table_name where (2/1/2011) <= date and date <= (2/6/2011);
(with Oracle SQL, you can use to_date instead of convert and optionally use the || concatenation operator; with SQL server you have to use the + concatenation operator; with MySQL this should be right)
(2/1/2011) and (2/6/2011) could either be strings that you convert similar to the other convert, or inputted using a PreparedStatement or something like it as dates directly (this would be preferable).
I had the same scenario but with Month column displaying Month name . With slight modification on the given query i was able to fetch the data.
SELECT *
FROM Table_Name AS Tbl_Date
WHERE (Year * 10000 + DATEPART(mm, CAST(Month + Year AS DATETIME)) * 100 + 1
BETWEEN 20111101 AND 20121201)
Hope this will help
To convert to Date for easier comparisons without worrying about dmy or mdy, in a standard fashion:
DATEADD(year, year-1900, DATEADD(month, month-1, DATEADD(day, day-1, 0)))
So, something like this. The safest date format to use is yyyymmdd (especially with SQL Server)
SELECT
value,
DATEADD(year, year-1900, DATEADD(month, month-1, DATEADD(day, day-1, 0))) AS realdate
FROM Mytable_name
WHERE
'20110201' <= DATEADD(year, year-1900, DATEADD(month, month-1, DATEADD(day, day-1, 0)))
and
DATEADD(year, year-1900, DATEADD(month, month-1, DATEADD(day, day-1, 0))) <= '20110206'
if you are using oracle database then you can use TO_DATE and TO_CHAR functions to achive this target...
as follow-
select * from table_name
where to_date(day||month||year,'DDMMYYYY')
between &mindate and &maxdate
min date you can put 2-jan-2011 and max date as 2-jun-2011
I hope it should work for you :)
well i found the answer that i wanted thanks guys
SELECT Tbl_Date.Value,Tbl_Date.Year,Tbl_Date.Month,Tbl_Date.Day from Tbl_Date
where ((Tbl_Date.Year*10000)+(Tbl_Date.Month*100)+Tbl_Date.Day) between 110102 and 110602

Get Records from Current Date in SQLite

In MSSQL using
where DateDiff(Day,CurrentDate,getdate())=0
shows all Records Created from CurrentDate
How to do it in Sqlite ?
WHERE CurrentDate BETWEEN DATE('now') AND DATE('now', '+1 day')
Source:
SQLite Query Language: Date And Time Functions
I'd suggest that using DATEDIFF or any other functions that involve your CurrentDate field will result in a query that cannot take advantage of any indexes you may have on that field.
Much better is to write the WHERE clause as WHERE CurrentDate >= DATEADD(DAY, DATEDIFF(DAY, '2000-01-01', GETDATE(), '2000-01-01')) - or any other rewrite that keeps CurrentDate unmodified in the comparison.
N.B. There may be a much better way of converting a date & time to a date - my approach is based on pre- MSSQL 2008 T-SQL.