4

I have a table more or less looking like

Name | Lastname | ID | Date 

Is there a way to prevent the database from running the insert function if a person which such Name, Lastname and ID already exists without running additional queries searching for him?

John Woo
  • 258,903
  • 69
  • 498
  • 492
user2228063
  • 221
  • 1
  • 2
  • 8

1 Answers1

13

add a UNIQUE constraint on the columns,

ALTER TABLE TableName ADD CONSTRAINT tb_uq UNIQUE (ID, LastName)

once it has been implemented, if you try to insert a value which ID and LastName already existed, it will throw an exception. example

INSERT INTO tableName (ID, LASTNAME) VALUES (1, 'hello') // ok
INSERT INTO tableName (ID, LASTNAME) VALUES (2, 'hello') // ok
INSERT INTO tableName (ID, LASTNAME) VALUES (1, 'hello') // failed
John Woo
  • 258,903
  • 69
  • 498
  • 492