Correct date range in SQL - datetime

This has gotten me a little paranoid, but I'm retrieving a set of records that fall within a period of time, say, the period from the january 1, 2011 (starting at midnight) to march 31, 2011 (all records up to 11:59:59 PM)
I'm using the condition
t.logtime between to_date('2011-01-01', 'yyyy-mm-dd') and to_date('2011-03-31')
Note that logtime is a datetime field.
Does this reflect what I want? Or am I actually missing 24 hours less a second?
I could specify the time as well, but I was hoping I this could be done without it.

Yes, you are missing nearly all of the last day. There are various solutions; probablt the simplest is:
t.logtime >= to_date('2011-01-01', 'yyyy-mm-dd')
and t.logtime < to_date('2011-04-01', 'yyyy-mm-dd')
I'd use the ANSI date literal syntax too:
t.logtime >= date '2011-01-01'
and t.logtime < date '2011-04-01'
Another way is:
trunc(t.logtime) between date '2011-01-01' and date '2011-03-31'
but note that that can no longer use an index on logtime (though it can use an index on trunc(logtime)).

Related

Negative dates in sqllite database

I am working locally with an sqllite DB. I have imported some records from teradata where there was a date field in the format of 'YYYY-MM-DD'. When i imported the records the date switched from a date to a number. I know this is a feature of sqllite and that one can access it via date(sqllite_date) when selecting it in a where clause.
My problem is that the dates now appear to be a bit odd. For example the year appears to be negative.
Is there anyway to recover this to the correct format?
Below is an example of converting a number in the database into a date
SELECT date(18386)
# -4662-03-28
SELECT datetime('now')
# 2021-02-11 10:41:52
SELECT date(sqllite_date) FROM mydb
# Returns -4662-03-28
# Should return 2020-05-04
I am very new to this area so apologies if this is a basic question. Thank you very much for your time
In SQLite you can store dates as TEXT, REAL or INTEGER.
It seems that you stored the dates in a column with INTEGER or REAL affinity.
In this case, if you use the function date(), it considers a value like 18386 as a Julian day, meaning the number of days since noon in Greenwich on November 24, 4714 B.C.
This is why date(18386) returns 4662-03-28B.C.
But I suspect that the date values that you have are the number of days since '1970-01-01'.
In this case, 18386 days after '1970-01-01' is '2020-05-04'.
So you can get the dates in the format YYYY-MM-DD if you add the value of your column as days to '1970-01-01':
SELECT date('1970-01-01', datecolumn || ' day') FROM tablename
Or by transforming your date values to seconds and treat them as UNIX time (the number of seconds since '1970-01-01 00:00:00 UTC'):
SELECT date(datecolumn * 24 * 3600, 'unixepoch') FROM tablename
Replace datecolumn with the name of your column.

Teradata - Calculate the previous quarter date start date and end date from current date

I have current_date in Teradata which 18 DEC 2019
I have to calculate the previous quarter start date and end date from the above current_date.
Input = '2019-12-18'
Output Start Date = '2019-07-01'
Output End Date = '2019-09-30'
You should be able to do this using the TRUNC function, something like:
SELECT
TRUNC(ADD_MONTHS(CURRENT_DATE, -3), 'Q') AS Start_Quarter, -- Previous quarter start
TRUNC(CURRENT_DATE, 'Q') - 1 AS End_Quarter -- Current quarter start date - 1 day
Give it a try and let me know. This assumes the mistake in the manual is still considered a "mistake".
Also, depending on what TD version you're using, you may be able to use built-in functions:
SELECT
TD_QUARTER_BEGIN(CURRENT_DATE) AS Start_Quarter,
TD_QUARTER_END(CURRENT_DATE) AS End_Quarter
Reference
TD Manual
Built-in functions

SQlite is not querying output correctly

I have the following SQL statement, however it is including a date from October
The format from the csv line is 10/2/2017 17:32
Is it because my csv is incorrect?
Please help!
SELECT *
FROM MyTable
WHERE [Completion Status]= 'Incomplete'
AND [Curriculum Name] NOT LIKE '%Phishing Training%'
AND [Date Assigned] < date('now','-30 day')
ORDER BY [Employee Department]
You should probably change the format of the date in your CSV. I don't think SQLite recognizes that format. Once you do that the answer from Olivier should work.
https://www.sqlite.org/lang_datefunc.html
now (as of 17. Jan 2018) minus 30 days is 18. Dec 2017. Since you want [Date Assigned] < this date, i.e. before this date, a date from October is correct.
Did you intend to write
[Date Assigned] >= date('now','-30 day')
i.e. return entries at most 30 days old?
Also, according to the official SQLite documentation, you should store the date as YYYY-MM-DD HH:MM. See: Date And Time Functions.

How to add/subtract date/time components using a calculated interval?

I'd like to get this to work in Teradata:
Updated SQL for better example
select
case
when
current_date between
cast('03-10-2013' as date format 'mm-dd-yyyy') and
cast('11-03-2013' as date format 'mm-dd-yyyy')
then 4
else 5
end Offset,
(current_timestamp + interval Offset hour) GMT
However, I get an error of Expected something like a string or a Unicode character blah blah. It seems that you have to hardcode the interval like this:
select current_timestamp + interval '4' day
Yes, I know I hardcoded it in my first example, but that was only to demonstrate a calculated result.
If you must know, I am having to convert all dates and times in a few tables to GMT, but I have to account for daylight savings time. I am in Eastern, so I need to add 4 hours if the date is within the DST timeframe and add 5 hours otherwise.
I know I can just create separate update statements for each period and just change the value from a 4 to a 5 accordingly, but I want my query to be dynamic and smart.
Here's the solution:
select
case
when
current_date between
cast('03-10-2013' as date format 'mm-dd-yyyy') and
cast('11-03-2013' as date format 'mm-dd-yyyy')
then 4
else 5
end Offset,
(current_timestamp + cast(Offset as interval hour)) GMT
You have to actually cast the case statement's return value as an interval. I didn't even know interval types existed in Teradata. Thanks to this page for helping me along:
http://www.teradataforum.com/l081007a.htm
If I understand correctly, you want to multiply the interval by some number. Believe it or not, that's literally all you need to do:
select current_timestamp as right_now
, right_now + (interval '1' day) as same_time_tomorrow
, right_now + (2 * (interval '1' day)) as same_time_next_day
Intervals have always challenged me for some reason; I don't use them very often. But I've had this little example in my Teradata "cheat sheet" for quite a while.
Two remarks:
You could return an INTERVAL instead of an INT
The recommended way to write a date literal in Teradata is DATE 'YYYY-MM-DD' instead of CAST/FORMAT
select
case
when current_date between DATE '2013-03-10' and DATE '2013-11-03'
then interval '4' hour
else interval '5'hour
end AS Offset,
current_timestamp + Offset AS GMT

SQLite : obtain current week

I'm trying to obtain the current week for date comparison in SQLite.
I have no problem for last month, last year, today, yesterday... but don't find the solution to have the current week.
I tried lot of things like:
SELECT tastings.* FROM tastings
WHERE (DATE(tastings.date) > DATE('now','weekday 1','+ 7 days'))
Can you help me ? Thanks.
This code gives you the week number where the first day of week is monday. It also works well for last and first weeks of the year.
strftime('%W', 'now', 'localtime', 'weekday 0', '-6 days')
I guess you want compare 2 date, Assume you have a table named _testTbl and have 3 column _id INTEGER, _name TEXT, _recordDate TEXT
you want name that record this week
you can use below code:
SELECT * FROM _testTbl
WHERE _recordDate > datetime('now', 'start of day', 'weekday 6', '-7 day')
note that this week start by saturday (sunday 0, monday 1, ..., saturday 7)
this t-sql means:
datetime is a sqlite date and time function.
first parameter is given time: 'now' means the current time.
second parameter take the time to start of day.
third parameter take time to the next weekday number (in this case, saturday).
fourth parameter take time to start of week
What is stored inside the tastings.date column? Note that SQLite does not have “timestamp” type affinity, so probably you store Text (some representation of the date) or integer (julian day, epoch…)
All time and date functions expect a valid time string and convert that time string to another string format. If tastings.date contains a week number then use:
AND cast(tastings.date AS TEXT) = strftime('%W','now')
This helps me to compare the 2 dates using the week of the year.
AND ( strftime('%W', tastings.date) = strftime('%W', 'now') )
Thanks you.

Resources