1

Can someone tell me why this doesn't work?

select * 
from keyword_groups_list 
where group_id = (insert into keyword_groups_list(group_name, keyword_tool_id) 
                  values('title', 86574551) returning group_id);

I get an error in PostgreSQL:

ERROR: Syntax error at or near "into"
LINE 1: ...from keyword_groups_list where group_id = (insert into keywo...

4
  • 2
    What are you trying to achieve here? Commented Sep 7, 2018 at 18:16
  • 1
    you can't use an insert for returning a value to compare .. explain better your goal .. Commented Sep 7, 2018 at 18:16
  • first I am inserting a row in Postgres and after insertion, I am returning group_id of that inserted row. This group id will be used to insert into another table. But I am getting this error Commented Sep 7, 2018 at 18:20
  • Removed my comment @a_horse_with_no_name I was way off base on that one. Your CTE is beautiful, BTW and I'm totally going to steal that at some point in the future. Commented Sep 7, 2018 at 18:22

2 Answers 2

5

I don't see why you would need the select at all. Just use returning * to get all columns of the newly inserted rows:

insert into keyword_groups_list(group_name, keyword_tool_id) 
values ('title', 86574551) 
returning *;

Having said that, you can however do this with a CTE, if you really need a select:

with new_groups as (
    insert into keyword_groups_list(group_name, keyword_tool_id) 
    values ('title', 86574551) 
    returning group_id
)
select * 
from keyword_groups_list 
where group_id in (select group_id from new_groups);

But I can't think of any reason to prefer that over the simple returning *;

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

2 Comments

That INSERT CTE is a nice trick. I'm going to remember that one!
while running this sql statements, it returned empty row.
0

You can access that value if you put it into a CTE

See this SQL fiddle

with t as (
    insert into mytable (id, val) values(1,'abc') returning id
)
select * from anotherTable where id in (select id from t)

The Postgres INSERT documentation has another CTE example like this too. Search for "Returning"

Or just simplify to

insert into mytable (id, val) values(1,'abc') returning *

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.