1

How do we conditionally insert a row with its default values into a table?

For example, we have a table with one column.

CREATE TABLE foo (
    id bigserial PRIMARY KEY
);

And, we want to do something like below:

INSERT INTO foo DEFAULT VALUES
WHERE random() >= 0.5;

But, we get:

ERROR:  syntax error at or near "WHERE"
1
  • 1
    I'm sure you have a reason, but this seems like an odd thing to do. Out of curiosity, what are you hoping to accomplish by doing this? Commented Jul 14, 2017 at 18:53

2 Answers 2

4
INSERT INTO foo
SELECT -- here is empty select, without any columns
WHERE random() >= 0.5;

Demo

PS: There are several "curious" related things in PostgreSQL. For example, select; or even more create table t(); both are valid statements.

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

Comments

0

Conditional insert requires a query and, as you can see from the INSERT documentation, query and DEFAULT VALUES are in a exclusive group.

When explicitly defining what columns should be populated, you need to specify at least one. So something like this is also invalid:

INSERT INTO foo ()
SELECT 1
WHERE random() >= 0.5;

The only way I can think of to achieve the same effect is by explicitly defining the "default" value:

INSERT INTO foo (id)
SELECT nextval('foo_id_seq'::regclass)
WHERE random() > 0.8;

Or by adding another column

CREATE TABLE foo (
    id bigserial PRIMARY KEY,
    ignored SMALLINT
);

INSERT INTO foo (ignored) 
SELECT 1
WHERE random() >= 0.5;

Edit:

Completely missed that you can do empty selects:

INSERT INTO foo
SELECT
WHERE random() >= 0.5;

Comments

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.