Portable SQL for date and comparison arithmetic

SQL

Table for storing user sessions:

CREATE TABLE sessions (
    user_id INT,
    expires TIMESTAMP
);

To create a session:

INSERT INTO sessions (user_id, expires) VALUES (:user_id,
    CURRENT_TIMESTAMP + INTERVAL '+15 minutes');

To get a session:

SELECT * FROM sessions WHERE user_id = :user_id AND
    CURRENT_TIMESTAMP < expires;

Questions

  • Is this portable SQL?
    Will this work with any database accessible through the PHP PDO extension (excluding SQLite)?

  • Is this correct in different time zones? Through daylight saving time?
    Any mixing problem CURRENT_TIMESTAMP(which includes timezone information) with a column TIMESTAMP(what's wrong)?

+5
source share
3 answers

Date / time values ​​are quite problematic in SQL dialects, in my experience.

  • Oracle DATE, TIMESTAMP, TIMESTAMP WITH TIME ZONE TIMESTAMP WITH LOCAL TIME ZONE.
    • DB2 DATE, TIME TIMESTAMP.
    • SQL Server DATETIME () DATE. SQL Server TIMESTAMP, , .
    • MySQL DATE, DATETIME, TIMESTAMP, TIME YEAR
    • PostgresSQL TIMESTAMP, TIME, , DATE

/ , char/varchar ISO8601

YYYYMMDDTHHMMSS[±HH:MM]

24h/ . , UTC "Z", Zulu (UTC). , "Z" / ISO 8601 .

.

ISO8601

  • /
+3

SQL, ( SQL Server), . , "" "".

, ANSI: INTERVAL '15' MINUTE, ,

+2

SQL Server does not support this. You will need to use the dataadd function. So the answer is not the simplest SQL.

+1
source

All Articles