How to subtract days to a Timestamp in CrateDB SQL query? - cratedb

How can i subtract days to a timestamp in CrateDB SQL query?
Exist something similar to this?
TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 14 DAY)

Don't think there is a built in function but you could do something like this
SELECT DATE_FORMAT(CURRENT_TIMESTAMP - 1000*60*60*24*14) LIMIT 100
in this example (1000 * 60 * 60) * 24 * 14 (24 is to get days and 14 is your number of days)
NB. You can also cast dates into timestamp and perform similar functionality
SELECT ABS(cast('2019-01-1' AS TIMESTAMP) - CURRENT_TIMESTAMP ) / (1000*60*60*24) LIMIT 100
this will get you a number of days between now and 1st of January
So far that's all what they have in their docs

You can subtract INTERVAL from TIMESTAMP, but before any matematichal operation you need to CAST the datatype, you can do it in this way:
SELECT now() - CAST('14 day' AS INTERVAL)
Or the same function of above, but in a contracted way
SELECT now() - '14 day'::INTERVAL;
As a string to be CAST to an INTERVAL you can use a number followed by any of this:
second
minute
hour
day
week
month
quarter
year

Related

Interval Date to days [duplicate]

I have two timestamp columns: arrTime and depTime.
I need to find the number of munites the bus is late.
I tried the following:
SELECT RouteDate, round((arrTime-depTime)*1440,2) time_difference
FROM ...
I get the following error: inconsistent datatype . expected number but got interval day to second
How can i parse the nuber of minutes?
If i simply subtract: SELECT RouteDate, arrTime-depTime)*1440 time_difference
The result is correct but not well formatted:
time_difference
+00000000 00:01:00 0000000
The result of timestamp arithmetic is an INTERVAL datatype. You have an INTERVAL DAY TO SECOND there...
If you want the number of minutes one way would be to use EXTRACT(), for instance:
select extract( minute from interval_difference )
+ extract( hour from interval_difference ) * 60
+ extract( day from interval_difference ) * 60 * 24
from ( select systimestamp - (systimestamp - 1) as interval_difference
from dual )
Alternatively you can use a trick with dates:
select sysdate + (interval_difference * 1440) - sysdate
from (select systimestamp - (systimestamp - 1) as interval_difference
from dual )
The "trick" version works because of the operator order of precedence and the differences between date and timestamp arithmetic.
Initially the operation looks like this:
date + ( interval * number ) - date
As mentioned in the documentation:
Oracle evaluates expressions inside parentheses before evaluating those outside.
So, the first operation performed it to multiply the interval by 1,440. An interval, i.e. a discrete period of time, multiplied by a number is another discrete period of time, see the documentation on datetime and interval arithmetic. So, the result of this operation is an interval, leaving us with:
date + interval - date
The plus operator takes precedence over the minus here. The reason for this could be that an interval minus a date is an invalid operation, but the documentation also implies that this is the case (doesn't come out and say it). So, the first operation performed is date + interval. A date plus an interval is a date. Leaving just
date - date
As per the documentation, this results in an integer representing the number of days. However, you multiplied the original interval by 1,440, so this now represented 1,440 times the amount of days it otherwise would have. You're then left with the number of seconds.
It's worth noting that:
When interval calculations return a datetime value, the result must be an actual datetime value or the database returns an error. For example, the next two statements return errors:
The "trick" method will fail, rarely but it will still fail. As ever it's best to do it properly.
SELECT (arrTime - depTime) * 1440 time_difference
FROM Schedule
WHERE ...
That will get you the time difference in minutes. Of course, you can do any rounding that you might need to to get whole minutes....
Casting to DATE first returns the difference as a number, at least with the version of Oracle I tried.
round((cast(arrTime as date) - cast(depTime as date))*1440)
You could use TO_CHAR then convert back to a number. I have never tested the performance compared to EXTRACT, but the statement works with two dates instead of an interval which fit my needs.
Seconds:
(to_char(arrTime,'J')-to_char(depTime,'J'))*86400+(to_char(arrTime,'SSSSS')-to_char(depTime,'SSSSS'))
Minutes:
round((to_char(arrTime,'J')-to_char(depTime,'J'))*1440+(to_char(arrTime,'SSSSS')-to_char(depTime,'SSSSS'))/60)
J is julian day and SSSSS is seconds in day. Together they give an absolute time in seconds.

presto - getting days interval (not date)

How do I get the days interval for prestodb? I can convert to milliseconds and convert these to number of days but I am looking if there is any shorter way to do this.
Example: I want to see how many days has it been since the first row inserted in a table.
SELECT
to_milliseconds(date(current_date) - min(created)) / (1000*60*60*24) as days_since_first_row
FROM
some_table
What I am hoping to see: (Either 1 of below)
SELECT
to_days(date(current_date) - min(created)) / (1000*60*60*24) as days_since_first_row
,cast(date(current_date) - min(created)) as days) as days_since_first_row2
FROM
some_table
Unfortunately, daylight savings breaks the solution from the accepted answer. DAY(DATE '2020-09-6' - DATE '2020-03-09') and DAY(DATE '2020-09-6' - DATE '2020-03-08') are both equal to 181 due to daylight savings time and DAY acting as a floor function on timestamps.
Instead, use DATE_DIFF:
DATE_DIFF('day', DATE '2020-09-6', DATE '2020-03-09')
Use subtraction to obtain an interval and then use day on the interval to get number of days elapsed.
presto:default> select day(current_date - date '2018-07-01');
_col0
-------
86
The documentation for this is at https://trino.io/docs/current/functions/datetime.html

Between Operator Big Query Standard SQL

Using Standard SQL in BQ - as part of a task I want to search for records created between 2pm the previous day & 2pm on current day
I have found
SELECT DATETIME_SUB(DATETIME_TRUNC(CURRENT_DATETIME(), DAY), INTERVAL 10 hour) Gives me 2PM yesterday
SELECT DATETIME_ADD(DATETIME_TRUNC(CURRENT_DATETIME(), DAY), INTERVAL 14 hour)
Gives me 2pm today
So, i assumed i could use this in my query
Select * from
TableA
where CreatedDate Between
DATETIME_SUB(DATETIME_TRUNC(CURRENT_DATETIME(), DAY), INTERVAL 10 hour) and DATETIME_ADD(DATETIME_TRUNC(CURRENT_DATETIME(), DAY), INTERVAL 14 hour)
However I get the following
No matching signature for operator BETWEEN for argument types:
TIMESTAMP, DATETIME, DATETIME. Supported signature: (ANY) BETWEEN
(ANY) AND (ANY)
Where am i going wrong?
Your issue is that CreatedDate is TIMESTAMP and you need to convert into a DATETIME
It could be like:
where DATETIME(CreatedDate) Between ...
But you could easily write your own statements for TIMESTAMP
SELECT timestamp_sub(timestamp_trunc(current_timestamp() ,
DAY),interval 10 hour)

Average Timestamp oracle with milliseconds

Hello everyOne I need to get the AVERAGE of difference of two dates (timestamp)
I tried this
select AVG((sva.endTime - sva.startTime)) as seconds from SVATable sva;
but I got an error
93/5000
ORA-00932: Inconsistent data types; expected: NUMBER; got: INTERVAL DAY TO SECOND
You may use EXTRACT to get AVG seconds.
SELECT AVG (EXTRACT (SECOND FROM (sva.endTime - sva.startTime)))
AS avg_seconds
FROM SVATable sva;
This is an insidious problem in Oracle. Your calculation would work with the date data type, but it does not work with timestamps.
One solution is to extract the days, hours, minutes, and seconds from the interval. Another is to use date arithmetic. You can get fractions of a day by using:
select (date '2000-01-01' + (sva.endTime - sva.startTime)) - date '2000-01-01'
You can use the average and convert to seconds:
select avg( (date '2000-01-01' + (sva.endTime - sva.startTime)) - date '2000-01-01') * (60*60*24)

Query to fetch records only form previous half hour with time stamp in unix epoch format

I want SQL query to fetch/select records which are taken only from previous half an hour only. For example if my scheduler ran at 2 pm, and then again in 2:30, during the 2:30 run it should only pick rows from between 2pm and 2:30pm and not earlier, using the column created_timestamp which stores the time as unix epoch format eg:
|created_timestamp|
|1497355750350 |
|1497506182344 |
We can do arithmetic with Oracle dates. Subtracting one date from another gives the interval as a fractional number. Multiplying by 86400 gives us the number of seconds. So this is the current unix expoch:
(sysdate - date '1970-01-01') * 86400
This means your query will be something like
select * from your_table
where created_timestamp >= (:last_run_time - date '1970-01-01') * 86400
The trick is that your scheduler needs to pass in the time of the previous run - last_run_time - to pick up all the records which have been added since then.
You can do Flashback query
SELECT * FROM TABLE
AS OF TIMESTAMP (SYSTIMESTAMP - INTERVAL '30' MINUTE);