ANSI standard of UNIX_TIMESTAMP() - sql

UNIX_TIMESTAMP() isn't an ANSI standard keyword but an addition to the MySQL syntax. However, since I'm supporting multiple DB's, is there an ANSI standard way to write UNIX_TIMESTAMP();
Thanks

As far as I know, no.
Every database handles this differently.
For example, in Oracle, you have to manually generate the timestamp with something like:
SELECT (sysdateColumn - to_date('01-JAN-1970','DD-MON-YYYY')) * (86400) AS alias FROM tableName;
In MSSSQL:
SELECT DATEADD(s, yourDateColumn, '19700101') AS alias FROM tableName
In PGSQL:
SELECT date_part('epoch', timestampColumn) AS alias FROM tableName
Edit: as AlexKuznetsov pointed out, there are two totally different usages of MySQL's UNIX_TIMESTAMP() function. I assumed the latter, UNIX_TIMESTAMP(date) (for native format to epoch conversion) for the above answer.

You failed to define UNIX_TIMESTAMP
If the following is true:
UNIX_TIMESTAMP(date) returns the value of the argument as seconds since '1970-01-01 00:00:00'
then use DATEDIFF function

Related

Typecasting datetime differences

We use firebird as a local testing database and most of our clients use SQL Server or Oracle.
This works in MS SQL Server, but not in Firebird. (haven't tested it n Oracle yet)
CONVERT(char(8),MAX(p.end_Time)-MIN (p.start_Time),8) as duration
is there a way to acoomplish this same thing for (Firebird, Oracle, and MS Sql Server)?
thanks
For Firebird you need to use DATEDIFF to obtain a difference between two timestamps (datetimes). This BTW is similar to the SQL Server DATEDIFF. If you then want to cast it to char, you can use CAST, eg CAST(DATEDIFF(DAY, MAX(p.end_Time), MIN(p.start_Time)) AS CHAR(8)) should do the trick (or you can simply do CAST(MAX(p.end_Time) - MIN (p.start_Time) AS CHAR(8)) as timestamps are subtractable.
I just noticed though that the option you specify in your CONVERT will convert to hh:mi:ss. There is no such option in Firebird. If you need to convert specifically to hh:mi:ss, you might want to look at UDF libraries like FreeAdhocUDF (specifically F_SECONDS2PERIOD) or rFunc UDF. If all else fails, you could write your own UDF.
there is no CONVERT on firebird.
Use CAST:
select cast(MAX(p.end_Time) as varchar(50)) and so on...
On Oracle (Oracle 8i, Oracle 9i, Oracle 10g, Oracle 11g), you can use to_char function:
select to_char( value, [ format_mask ], [ nls_language ] ) ....
Example:
SELECT TO_CHAR ( SYSDATE - TO_DATE ( '18-10-2012', 'dd-mm-yyyy' ), '9,999.99' ) as duration FROM DUAL;
Here is the link for Oracle/PLSQL: To_Char Function

HSQL Get Date and Time from TIMESTAMP

I have a HSQLDB table with some informations and where a timestamp is stored
I want to select informations from specific time periods like every information of october between 0am and 5pm.
I didn't found any function like mysql'ones DATE(myfield) OR TIME(myfield) which would be perfect for what i want.
SELECT * FROM myTable
WHERE DATE(myField) BETWEEN '2012-10-01' AND '2012-10-30'
AND TIME(myField) BETWEEN '00:00:00' AND '17:00:00'
The only things i found are to use the functions YEAR(), DAYOFMONTH(), DAYOFYEAR(), HOUR() ANd MINUTE() but I was wondering if there aren't any other simpler solutions.
There is no need for such specialised functions as HSQLDB supports the general CAST expression for this purpose
CAST(myField AS DATE)
CAST(myField AS TIME)
HSQLDB also supports automatic cast from DATE to TIMESTAMP. Therefore an optimised query that can use an index on the myField column should look like this:
SELECT * FROM myTable
WHERE myField BETWEEN DATE'2012-10-01' AND DATE'2012-10-30'
AND CAST(myField AS TIME) BETWEEN TIME'00:00:00' AND TIME'17:00:00'

Errors while trying to cast/convert VARCHAR to DATETIME in ANSI SQL

I have a column in a table where timestamps have been stored in VARCHAR format, but I need to compare these against a column of DATETIME values from another table to find time intervals, so I want to either cast or convert the VARCHAR timestamps to DATETIME. However, both casting and converting are giving me problems.
The format of the VARCHAR timestamp looks like this: "29/07/2012 01:53:36 +12".
Using the query:
SELECT CAST(event_timestamp AS datetime) FROM the_table
produces ERROR: date/time field value out of range: "29/07/2012 01:53:36 +12".
Using the query:
SELECT CONVERT(datetime, event_timestamp, 131) from the_table;
produces
ERROR: syntax error at or near ","
LINE 1: select CONVERT(datetime, event_timestamp, 131) from the_tab...
^ (note: this is pointing at the first comma).
The error with CONVERT actually happens even if you use a generic function such as getdate() for the data source. This db uses ANSI SQL-92 (or so I'm told). Could anyone please help me out with this?
This seems really painful, but the following should work:
select dateadd(hh, cast(right(tv, 3) as int),
CONVERT(datetime, left(tv, 10), 103)+CONVERT(datetime, substring(tv, 12, 8), 108)
)
from (select '29/07/2012 01:53:36 +12' as tv) t
I've never added datetime's before, but this just worked on SQL Server 2008.
Why can't SQL Server just support a flexible notation built around yyyy, mm, mmm, dd and so on?
The actual database is Aster Data, which is based on Postgres (as are most recent database engines). In this database, you would use to_timestamp(). See the documentation here http://www.postgresql.org/docs/8.2/static/functions-formatting.html. The call would be something like:
to_timestamp(val, 'MM/DD/YYYY HH:MI:SS tz') -- not sure if this gets the +12
There are no ANSI functions for date conversion, so each database does its own. Even string functions vary among databases (substr? substring? charindex? instr? location?), so there is no ANSI way to do this.
You are using the wrong syntax, try:
CONVERT(varchar(X), datetimeValue, 131)
Where X is the total number of characters desired.
You will then be able to search for a match with datetimeValue and event_timestamp, assuming each value share the same structure. This will allow you to match string against string.
If I'm not mistaken the standard (ANSI SQL) CAST operator always expect time/date/timstamp literals in ISO format ('YYYY-MM-DD')
But according to the manual for Teradata V12 (can't test it), the format of the CAST operator is
CAST(character_expression AS TIMESTAMP timestamp_data_attribute)
with date_data_attribute being a character value plus an optional FORMAT specifier.
So in your case this would probably be:
cast(event_timestamp AS TIMESTAMP FORMAT 'MM/DD/YYYY HH:MI:SS Z');
I'm not entirely sure about the format definition though. You'll probably need to adjust that
Btw: CONVERT isn't a standard SQL function. It's SQL Server specific.

Question: how to use the current time in a where clause

there was a question coming up to my mind. Is there any possibility to use the current timestamp instead of a selected date in the Where Clause?
SELECT this, that
FROM here
WHERE start>='2010-07-01'
I thought it would be sth. like: start='now()' or curdate() or curtime().
Anything I found was that they're used in the Select Clause, but I need it in Where.
Any help is much appreciated.
Flora
SELECT this, that
FROM here
WHERE start >= NOW()
You can use any of the following three functions as per your requirements:
SELECT NOW(),CURDATE(),CURTIME()
The output of this query is -
NOW() | CURDATE() | CURTIME()
---------------------+----------------+----------
2008-11-11 12:45:34 | 2008-11-11 | 12:45:34
Edited:
you can use these functions in Where clause as instructed.
Sure you can:
WHERE start >= CURDATE()
You can use any expression in the WHERE clause, using any inbuilt Date-and-Time function.
I'd use
WHERE start >= current_timestamp
Just because this should work in every DBMS. Don't know about NOW() though, maybe that's a standard function?
Update: well now I know NOW() does not work at least in Oracle, so I'd definitely go with current_timestamp, current_date etc, because these are in the standard. I've done a couple of DBMS migrations (DB2 -> MySQL, MySQL -> Oracle etc) and I'm glad we used the standards -compliant SQL where ever possible, which made the migrations relatively painless.
You shouldn't to quote a function name
Use function names like this:
SELECT this, that FROM here WHERE
start >= NOW();
SELECT this, that FROM here WHERE
start >= CURRENT_DATE();
... WHERE v_date=CURRENT_DATE()

Mysql strip time component from datetime

I need to do a date comparison in Mysql without taking into account the time component i.e. i need to convert '2008-11-05 14:30:00' to '2008-11-05'
Currently i am doing this:
SELECT from_days(to_days(my_date))
Is there a proper way of doing this?
Yes, use the date function:
SELECT date(my_date)
select date(somedate) is the most common.
If you need to accommodate other formats, you can use:
SELECT DATE_FORMAT(your_date, '%Y-%m-%d');
In PostgreSQL you use the TRUNC() function, but I'm not seeing it for MySQL. From my brief Googling, it looks like you'll need to cast your DATETIME value to be just DATE.
date_col = CAST(NOW() AS DATE)
See http://dev.mysql.com/doc/refman/5.0/en/date-and-time-types.html
Just a simple way of doing it date("d F Y",strtotime($row['date'])) where $row['date'] comes from your query
You could use ToShortDateString();