sqlpostgresqlsql-insertwith-statement

Insert sql but all rows have the same id (no unique constraint)


I'm trying to make an insert where the first row is the default item and the other rows are the variants with different language (making a primary key with id and locale) and I was thinking on something like this but it's not working:

with data as (
    select uuid_generate_v4() as uuid
)
insert into content (id, type, locale)
select
(uuid, 'page', 'en-us'),
(uuid, 'page', 'es-mx')
from data

I tried using a CTE to get an UUID and then use that for all the inserts for that I need to use SELECT instead of VALUES, I also need to return results.


Solution

  • You can use a CTE, but a simple subquery does the job. You just can't keep the function uuid_generate_v4() in the SELECT list, or a new UUID is generated for every row.

    INSERT INTO content (id, type, locale)
    SELECT id, 'page', locale
    FROM   uuid_generate_v4() id
        ,  unnest('{en-us, es-mx}'::text[]) locale;
    

    Or even:

    INSERT INTO content (id, type, locale)
    SELECT id, 'page', unnest('{en-us, es-mx}'::text[])
    FROM   uuid_generate_v4() id;
    

    About set-returning functions in the SELECT list:

    I do wonder about your relational design, that would require to store 'page' redundantly ...