1

I am writing my queries in 'standard' / 'generic' SQL so that it runs on any database (MySQL, Postgre etc).

I'd like to use DATE_ADD() of MySQL. In Postgre, it would be done with something like '2001-01-01'::timestamp + '1 year'::interval;.

Is there a more 'general' way of writing it so that it runs on both MySQL and Postgre (or others) ?

2
  • 4
    Trying to write standard SQL is usually a mistake. Take a look at the databases available, see which features you need, then be brave and just choose a database that meets your needs and code against that. Use the features that database has effectively. "Generic SQL" typically means slow, unmaintainable SQL that only works on the two databases you tested it on. Commented Jul 11, 2010 at 17:22
  • 1
    To add to Mark's comment, if you need to support different database vendors - either look to an ORM (trading coding simplicity for performance) or use SQL customized to each database vendor (better performance, more work). Commented Jul 11, 2010 at 17:35

2 Answers 2

2

In MySQL you don't need DATE_ADD, it has almost the same syntax as PostgreSQL:

MySQL: SELECT CAST('2001-01-01' AS date) + INTERVAL 1 year;

PostgreSQL: SELECT CAST('2001-01-01' AS date) + INTERVAL '1 year';

Sign up to request clarification or add additional context in comments.

Comments

1

No, there are not SQL standard functions for date addition.

Depending on how you're building your app (using a database abstraction layer and/or interface layer), you could probably handle it in a generic way there, and still have the database doing the math, not your code.

1 Comment

The operations timestamp + interval, timestamp - interval, timestamp - timestamp and date - date are specified in the SQL standard

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.