0

I have the following sql query that would only insert if it does not already exist in the table

INSERT INTO message_log (message, from_id, to_id, match_id, unix_timestamp, own_account) VALUES('hi', 'tom', 'tom', '55640ec48a2aecab0e3c096c556f5435f4bb054c68930040', 33333, TRUE)
WHERE NOT EXISTS (SELECT 1 FROM message_log WHERE message = 'hi' AND from_id = 'tom' AND to_id = 'tom' AND match_id = '55640ec48a2aecab0e3c096c556f5435f4bb054c68930040' AND unix_timestamp = 33333)

However I get the following error

ERROR:  syntax error at or near "WHERE"
LINE 2: WHERE NOT EXISTS (SELECT 1 FROM message_log where message = ...
        ^

What I am doing wrong?

3
  • 1
    There is no SELECT in the query. Commented Jun 25, 2015 at 16:57
  • That is not something you can do. At least not like that. Can you explain what you are trying to accomplish with that INSERT statement? Commented Jun 25, 2015 at 17:03
  • 1
    @JNevill I want the row to be inserted only if it does not already exist in the table Commented Jun 25, 2015 at 17:04

2 Answers 2

1

Inserting a record in a table only if that record doesn't exist is done with:

 INSERT INTO message_log (message, from_id, to_id, match_id, unix_timestamp, own_account) 
 SELECT 'hi', 'tom', 'tom', '55640ec48a2aecab0e3c096c556f5435f4bb054c68930040', 33333, TRUE
 FROM message_log
 WHERE NOT EXISTS (SELECT 1 FROM message_log WHERE message = 'hi' AND from_id = 'tom' AND to_id = 'tom' AND match_id = '55640ec48a2aecab0e3c096c556f5435f4bb054c68930040' AND unix_timestamp = 33333)

It's a little more verbose, but it should do what you want. Alternatively, you could set a unique primary key on the table, so the database will give you the smack-down if you try to insert a duplicate key. Six of one, half a dozen of the other.

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

Comments

0

The following should do

INSERT INTO message_log (message, from_id, to_id, match_id, unix_timestamp, own_account)
SELECT 'hi', 'tom', 'tom', '55640ec48a2aecab0e3c096c556f5435f4bb054c68930040', 33333, TRUE
WHERE NOT EXISTS (SELECT 1 FROM message_log WHERE message = 'hi' AND from_id = 'tom'
    AND to_id = 'tom' AND match_id = '55640ec48a2aecab0e3c096c556f5435f4bb054c68930040'
    AND unix_timestamp = 33333)

However it lacks styke: self query.

Maybe something like the following might be applicable:

INSERT ...
ON DUPLICATE KEY UPDATE own_account = own_account;

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.