0

I'm wanting to create a variable based on a query result and then use it in an IF statement. I have this so far:

with variable as (select "Id" from public.tableName where "OtherId" = 24)

if variable notnull then
    insert into public.tableName ("OtherName", "OtherPhoneNumber", "OtherAddress", "Id")
    overriding system values
    values ('foo', '205-123-4567', '123 Sample Ln', variable)
end if

Postgres gives me an error that reads:

SQL Error [42601]: ERROR: syntax error at or near "if"

What am I doing wrong?

****edit: Id is not the primary key, as there is a different primary key named TableNameId****

7
  • I don't get the first CTE. If you expect Id = 24, then wouldn't you also know what the value of Id would be returned from the select? Commented Dec 23, 2019 at 16:38
  • @TimBiegeleisen I guess it's supposed to be an IF EXISTS(…) Commented Dec 23, 2019 at 16:40
  • Unrelated to your question, but: you should really avoid those dreaded quoted identifiers. wiki.postgresql.org/wiki/… Commented Dec 23, 2019 at 17:13
  • Is "Id" the primary or a unique key? If yes, you can simply use insert ... on conflict do nothing instead Commented Dec 23, 2019 at 17:15
  • if Id is not unique then the whole IF doesn't make sense as the "variable" would only be able to contain a single value, not multiple. And to which value should variable be set anyway? The Name? If yes, then it seems rather strange that you want to store "a name" into an integer column. Commented Dec 23, 2019 at 17:23

1 Answer 1

1

If you want to check if a given id exists in one table and insert into another table if there is a match, you can use the insert ... select syntax as follows:

insert into public.tableName2 ("OtherName", "OtherPhoneNumber", "OtherAddress", "Id")
select 'foo', '205-123-4567', '123 Sample Ln', "Id"
from public.tableName1
where "Id" = 24
Sign up to request clarification or add additional context in comments.

2 Comments

I'm wanting this to take place in one table. I want to check for if a certain value exists, then add another value. If not, then don't do anything.
@ColbyWilloughby It works with the same table instead of two separate tables just as well. However, then it looks like your Id column is not unique, which would be rather weird.

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.