0

I've tried multiple variations of this code and it keeps giving me the SQL state: 42601 error. I've looked at the docs and tried using their examples which sometimes work, but do not do what I want.

IF (SELECT guildid FROM Servers <> 1) THEN
  INSERT INTO Servers (guildid) VALUES (1)
END IF;

My Servers table is simple. I just have a single row called guildid. I do not want a CASE statement because that only outputs messages.

2
  • CASE expressions (not "statements") don't "output messages". Commented Dec 13, 2017 at 12:57
  • You probably have a column called guildid. Rows don't have names. Commented Dec 13, 2017 at 12:59

2 Answers 2

1

If you don't have to worry about race conditions (which the if approach suggests), then:

INSERT INTO Servers (guildid)
   SELECT guildid
   FROM (VALUES (1)) v(guildid)
   WHERE NOT EXISTS (SELECT 1 FROM Servers s WHERE s.guildid = v.guildid);

To protect the table, I would suggest adding a unique index on it. In fact, just declare guildid to be the primary key. In that case, your original insert will simply fail, if you attempt to insert a duplicate value.

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

4 Comments

How would I be able to insert a different value into a separate row every time the value doesn’t exist? (so that would be two values in two different rows)
@SethDeegan . . . New questions should be asked as questions, not in comments.
Could you explain how the FROM (VALUES (1)) v(guildid)? I know that after a FROM, there should be the column name. This looks like a placeholder system but I can’t find any documentation on it. Could you please explain the query and provide a documentation source?
v is a table alias. guildid names the column in the table: postgresql.org/docs/9.6/static/sql-values.html.
1

If you have a unique constraint on that column, you can use on conflict do nothing:

INSERT INTO Servers (guildid) VALUES (1)
ON CONFLICT DO NOTHING;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.