Skip to content
Advertisement

How to use INSERT INTO in database where a condition is the ID has to be unique

Probably confusing title but I’ll explain.

I have this table named Shelf:

    CREATE TABLE Shelf (
  ID int(11) NOT NULL,
  UserID int NOT NULL NOT NULL,
  MovieID int NOT NULL,
  Nome varchar(255) NOT NULL,
  Image varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

And as you can see there is a field named MovieID, it’s value is being incremented from an API and basically everytime I use this query "INSERT INTO Shelf VALUES (null,?,?,?,?)" if I try to add the same movie twice it will do it, and I don’t want it to.

Succintly, I want to make sure that there is a verification in the SQL query that: if the MovieID (for a specific movie) is already stored in my database, I don’t want it to be added again.

Thanks in advance!

Advertisement

Answer

So the error was clear, I just needed to add a UNIQUE value to MovieID which now makes it look like so:

CREATE TABLE Shelf (
  ID int(11) NOT NULL,
  UserID int NOT NULL NOT NULL,
  MovieID int NOT NULL,
  Nome varchar(255) NOT NULL,
  Image varchar(255) NOT NULL,
  UNIQUE (MovieID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement