0

I have three columns in my table: id, email, and OAuthEmail. When a user, ([email protected]) signs up with an email I'd like to create a new record if the email is not in the table. If the user previously signed up with OAuthEmail (if OAuthEmail = [email protected]), I'd like to add [email protected] to the email column. I have tried the following -

INSERT INTO users ("email") 
  VALUES ([email protected]) 
ON CONFLICT (user."OAuthEmail" = [email protected]) 
  DO UPDATE SET (users.email = [email protected])
WHERE users."OAuthEmail" = [email protected];

I am getting a syntax error at "=" on the line - ON CONFLICT (users.email = user."OAuthEmail").

2
  • So which column should contain unique values: email or OAuthEmail? A few records of sample data and desired results would help clarifying your question. Commented Aug 18, 2020 at 21:14
  • Email and Oauth email can be the same values. If a user signs up with an email, then signs up again with a value that is the same OAuthEmail, then the OauthEmail should be added to the column instead of creating a new record. Commented Aug 18, 2020 at 21:54

1 Answer 1

1

You have syntax problems

  1. The email address has to be enclosed in quotes
  2. The ON CONFLICT should specify the conflict column or the name of the constraint
  3. There should be no WHERE clause
  4. If you are going to set the email to the value that it already has, then change it to DO NOTHING

I hope you do have a UNIQUE constraint on the email column.

Also, You should not use mixed-case identifiers. That will give you headaches down the road.

with do_update as (
  update users
     set email = "OAuthEmail"
    from invars
   where "OAuthEmail" = '[email protected]'
     and email is null
)
insert into users (email)
select new_email 
  from invars
on conflict (email) do nothing;
Sign up to request clarification or add additional context in comments.

3 Comments

If OAuthEmail is found, I'd like to add the email to the email field.
@user3291025 I have modified the query to do what you ask. I am sorry that I did not read it through completely. This approach requires a UNIQUE constraint on the email column.
@GMB When caffeine is gone, switch to bourbon. :-)

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.