postgresqlcaseprepared-statementselect-intomultiple-insert

PotgresSQL INSERT INTO SELECT CASE problem


I have the the following query and I'd like to insert any number of rows from the sub queries. Of course I'm getting an error SQL Error [21000]: ERROR: more than one row returned by a sub query used as an expression since some of the sub queries return multiple rows

insert into logs (_timestap, _message, _mode, _user_id)
select :_timestamp, :_message, :_mode,
case :_mode

    -- select all users that have the given grade. NOTE that this sub query returns multiple rows
    when 'byGrade' then (select u.id from users u where grade = :_grade)

    -- The user id value is already passed
    when 'byIndividual' then (select :_user_id limit 1)

    -- This sub query also returns multiple rows (all infact) from the users table
    when 'everyone' then (select id from users)
end

PostgreSQL version 10.

How can I solve this?


Solution

  • union all can to help:

    insert into logs (_timestap, _message, _mode, _user_id)
    
    select :_timestamp, :_message, :_mode, id
    from users
    where :_mode = 'byGrade' and grade = :_grade
    
    union all
    
    select :_timestamp, :_message, :_mode, :_user_id
    where :_mode = 'byIndividual'
    
    union all
    
    select :_timestamp, :_message, :_mode, id
    from users
    where :_mode = 'everyone';