H2 database. How to convert date to seconds in sql? - sql

Is there analog og the MySQL's time_to_sec() ?
I heed to perform query like the following on H2 database:
select * from order
join timmingSettings on order.timmingSettings = timmingSettings.id
where (order.time-timmingSettings.timeout) < current_timestamp

No, but it seems quite easy to add function to h2 if needed.
To convert a timestamp to seconds since epoch, compile and add a Java class to h2's classpath containing:
public class TimeFunc
{
public static long getSeconds(java.sql.Timestamp ts)
{
return ts.getTime() / 1000;
}
}
The function in the Java code can then be linked in h2 using CREATE ALIAS:
CREATE ALIAS TIME_SECS FOR "TimeFunc.getSeconds";
SELECT TIME_SECS(CURRENT_TIMESTAMP);
Produces:
TIME_SECS(CURRENT_TIMESTAMP())
1255862217
(1 row, 0 ms)

In lieu of adding a function to H2, you can cast the date to a timsestamp and then use formatdatetime per http://www.h2database.com/html/functions.html. Alternatively, cast to string and use parsedatetime. Examples of both follow:
-- to convert using parsedatetime, done_on stores
select parsedatetime(done_on, 'ssss', 'en', 'Europe/Dublin');
-- for this example, assume done_on stores a timestamp
-- to convert using formatdatetime
select formatdatetime(done_on, 'ssss', 'en', 'Europe/Dublin');
Valid timezones can be found in your /usr/share/zoneinfo directory and language codes are per the list at http://en.wikipedia.org/wiki/ISO_639-1 -- the ISO 639 part 1 standard.

I think this is the most simple code.
select DATEDIFF('second',timestamp '1970-01-01 00:00:00' , CURRENT_TIMESTAMP())

SELECT EXTRACT (EPOCH FROM <value>)
So
select * from order
join timmingSettings on order.timmingSettings = timmingSettings.id
where (extract(epoch from order.time)-extract(epoch from timmingSettings.timeout)) < extract(epoch from current_timestamp)

Related

PostgreSQL - where datetime <= YEAR-MONTH-DAY, ignore time

date column - datetime type.
My query is:
select * from car_db.car_parts where date::text LIKE '2018-07-06%'
How i select where date <= 'YEAR-MONTH-DAY', and ignore time?
I will be grateful...
First, Postgres doesn't offer a datetime type. The type is called timestamp. Also, Postgres has the very convenient function date_trunc(), so you can use that:
select *
from car_db.car_parts
where date_trunc('day', date) = '2018-07-06'::date;
However, this method -- or any method with a functional call or type conversion -- can affect index usage. I strongly recommend:
where date >= '2018-07-06'::date and
date < '2018-07-07'::date
Try the following. Also, you should not name your column as date.
select * from car_db.car_parts where cast("date" as date) < '2018-07-06'

How to convert Timestamp to Date Data Type in Google Bigquery

I am trying to convert Timestamp data type columns to Date datatype using:
bq query -q --destination_table=NEW_DATE_TABLE --replace "SELECT DATE(CURR_DT) AS CURR_DT from TEST.DATE_TABLE"
The new table shows the column as STRING rather than date. Is there a way to convert timestamp to date data type.
Requested Screenshot
If you use Standard SQL, you can do the following:
SELECT * REPLACE(EXTRACT(DATE FROM curr_dt)) AS curr_dt FROM test.date_table
If curr_dt is repeated field, then the solution will look the following:
SELECT * REPLACE(
ARRAY(
SELECT EXTRACT(DATE FROM curr_dt) FROM t.curr_dt
) AS curr_dt)
FROM test.date_table t
Consider below!
Works in both Legacy and Standard SQL
SELECT CAST(DATE(CURR_DT) AS DATE) AS CURR_DT FROM TEST.DATE_TABLE
Added to address comment
Try below - as I mentioned above - it works for both Legacy and Standard
SELECT CAST(DATE(CURR_DT) AS DATE) AS CURR_DT
FROM (SELECT CURRENT_TIMESTAMP() AS CURR_DT)
if you are interested in making your case working with Legacy SQL - provide more details about CURR_DT field
Try this
SELECT TIMESTAMP_SECONDS(CAST(CURR_DT AS INT64)) AS CURR_DT FROM TEST.DATE_TABLE

JPQL & Postgresql - How to perform arithmetic on timestamp field for comparison with CURRENT_TIMESTAMP?

I have a table "User" in two environments. One is using an Oracle DB and the other Postgresql. What I would like to do is retrieve all the records created in the last 4 hours. The "User" table has a field "beCreatime" which stores the timestamp of when the record was created.
I've implemented this successfully on the Oracle-based environment using the following:
SELECT u.id, u.userName, u.beCreatime FROM User u WHERE u.beCreatime + 4/24 > CURRENT_DATE
However, when using the same query on the Postgres environment, I receive the following error:
Internal Exception: org.postgresql.util.PSQLException: ERROR: operator does not exist: timestamp without time zone + integer
Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.
Position: 100
Error Code: 0
Call: SELECT Id AS a1, UserName AS a2, be_creatime AS a3 FROM BeamUser WHERE ((be_creatime + (? / ?)) > CURRENT_TIMESTAMP) LIMIT ? OFFSET ? bind => [4 parameters bound] Query: ReportQuery(referenceClass=UserEntity sql="SELECT Id AS a1, UserName AS a2, be_creatime AS a3 FROM BeamUser WHERE ((be_creatime + (? / ?))
CURRENT_TIMESTAMP) LIMIT ? OFFSET ?")
It seems like Postgres just doesn't like the addition of the timestamp (u.beCreatime) and 4/24. Is there a way to do something similar to this in a Postgres environment?
You need to use an interval:
WHERE u.beCreatime + interval '4' hour > CURRENT_DATE
But you cannot pass the '4' as a paramter, you need to do something like this in a PreparedStatement:
WHERE u.beCreatime + (interval '1' hour) * ? > CURRENT_DATE
Are you sure you want to compare that value with current_date? Becaues current_date does not contain any time information in Postgres (as it does in Oracle due to the lack of a "real" DATE data type)
If you want to get the Oracle behaviour you have to use current_timestamp because unlike Oracle, a DATE in Postgres does not contain a time part (that includes current_date)

How to perform operations on dates in queries?

I'd like to add 100 days to a field in a query:
SELECT DATE_ADD("date" + INTERVAL '100' DAY) FROM "history";
or whatever… but it doesn't work with the default HSQLDB frontend…
Any workaround ?
You don't need the date_add(), just add the interval to the column:
SELECT "date" + INTERVAL '100' DAY
FROM "history";
The default HSQLDB version in OpenOffic and LO is 1.8. It does not supports this function.
HSQLDB version 2.x supports several functions and expressions for date / time arithmetic.
If the column is named "date", this form is also supported. Note there is no underscore in the function name:
SELECT DATEADD('day',100, "date") FROM "history";

How to get one day ahead of a given date?

Suppose I have a date 2010-07-29. Now I would like to check the result of one day ahead. how to do that
For example,
SELECT *
from table
where date = date("2010-07-29")
How to do one day before without changing the string "2010-07-29"?
I searched and get some suggestion from web and I tried
SELECT *
from table
where date = (date("2010-07-29") - 1 Day)
but failed.
MySQL
SELECT *
FROM TABLE t
WHERE t.date BETWEEN DATE_SUB('2010-07-29', INTERVAL 1 DAY)
AND '2010-07-29'
Change DATE_SUB to DATE_ADD if you want to add a day (and reverse the BETWEEN parameters).
SQL Server
SELECT *
FROM TABLE t
WHERE t.date BETWEEN DATEADD(dd, -1, '2010-07-29')
AND '2010-07-29'
Oracle
SELECT *
FROM TABLE t
WHERE t.date BETWEEN TO_DATE('2010-07-29', 'YYYY-MM-DD') - 1
AND TO_DATE('2010-07-29', 'YYYY-MM-DD')
I used BETWEEN because the date column is likely DATETIME (on MySQL & SQL Server, vs DATE on Oracle), which includes the time portion so equals means the value has to equal exactly. These queries give you the span of a day.
If you're using Oracle, you can use the + and - operators to add a number of days to a date.
http://psoug.org/reference/date_func.html
Example:
SELECT SYSDATE + 1 FROM dual;
Will yield tomorrow's date.
If you're not using Oracle, please tell use what you ARE using so we can give better answers. This sort of thing depends on the database you are using. It will NOT be the same across different databases.
Depends of the DateTime Functions available on the RDBMS
For Mysql you can try:
mysql> SELECT DATE_ADD('1997-12-31',
-> INTERVAL 1 DAY);
mysql> SELECT DATE_SUB('1998-01-02', INTERVAL 31 DAY);
-> '1997-12-02'
If youre using MSSQL, you're looking for DateAdd() I'm a little fuzzy on the syntax, but its something like:
Select * //not really, call out your columns
From [table]
Where date = DateAdd(dd, -1, "2010-07-29",)
Edit: This syntax should be correct: it has been updated in response to a comment.
I may have the specific parameters in the wrong order, but that should get you there.
In PL SQL : select sysdate+1 from dual;