0

I have a MySQL query that needs to be converted over to PostgreSQL. As I understand, PostgreSQL has no UTC_TIMESTAMP() or DATE_ADD() functions available. After reading the docs, I'm not entirely certain which date functions solve my needs in this context.

Here's the query:

INSERT INTO snippets (title, content, created, expires)
VALUES(?, ?, UTC_TIMESTAMP(), DATE_ADD(UTC_TIMESTAMP(), INTERVAL ? DAY))

For reference, here is my snippets model:

CREATE TABLE snippets (
    id BIGSERIAL NOT NULL PRIMARY KEY,
    title VARCHAR(100) NOT NULL,
    content TEXT NOT NULL,
    created TIMESTAMP(0) NOT NULL,
    expires TIMESTAMP(0) NOT NULL
);
1
  • 1
    The use of the non-standard serial types is discouraged. It's better to use the standard compliant identity columns with modern Postgres versions Commented Nov 23, 2022 at 8:06

1 Answer 1

1

I've not done much with postgresql either, but maybe something like:

INSERT INTO snippets (title, content, created, expires)
VALUES('test', 'stuff', (now() at time zone 'utc'), (now() at time zone 'utc' + interval '1 day' * 3))

Which gives:

id  title   content created             expires
1   test    stuff   2022-11-23 13:02:13 2022-11-26 13:02:13

Then to restore the parameterized version of the query:

INSERT INTO snippets (title, content, created, expires)
VALUES(?, ?, (now() at time zone 'utc'), (now() at time zone 'utc' + interval '1 day' * ?))

I was not sure how to test the parameterized equivalent, but here's a dbfiddle example with the output from the first query.

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

2 Comments

Either interval '1 day' * ? or make_interval(days => ?)
@a_horse_with_no_name ... thanks I've updated the answer (and the fiddle) with the first part of your suggestion.

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.