Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default value of one column to another column in INSERT Statement

I have a table, call it t1, with three integer columns c1, c2, c3. c1 has a default value of:

not null default nextval

For the INSERT statements I am currently doing, I want c2 to have the same value as will be assigned to c1. This is not the case for most of my inserts so it does not make sense to define c2 to have a default value or to have a trigger on update. Currently I am doing two statements:

INSERT INTO t1 (c3) VALUES (val3);
UPDATE t1 SET c2 = c1 WHERE //Get correct row
like image 316
brendan Avatar asked Dec 27 '22 05:12

brendan


1 Answers

There is no guarantee in which order elements of a set will be processed. There is also no need to make two function calls. Use a sub-select or a CTE:

INSERT INTO t (c1, c2, c3)
SELECT x.s, x.s, val3
FROM  (SELECT nextval('c1_seq') AS s) x;

Or with a CTE:

WITH   x(s) AS (SELECT nextval('c1_seq'))
INSERT INTO t (c1, c2, c3)
SELECT x.s, x.s, val3
FROM   x;
like image 152
Erwin Brandstetter Avatar answered Apr 13 '23 10:04

Erwin Brandstetter