birgersp
birgersp

Reputation: 4956

How can I insert a row with an id, where the id is not already taken?

So I'm in the slow process of becoming comfortable with databases.

(Example) I have two tables, customers and purchases. Created like this:

create table Customers (customerId int, firstname varchar(255), surname varchar(255))

create table Purchases (customerId int, productName varchar(255))

Let's say that some application wants to register a new customer. The new customer needs an id that does not already exist in the table.

If I execute this query: insert into Customers values (1, 'Mark', 'Zuckerberg'), there may already exist a different customer with this id.

How can the application obtain an value for customerId that does not already exist in the table? Is there something flawed with the design of this database? Should I be using some other method for tying purchases to customers?

Upvotes: 0

Views: 78

Answers (1)

birgersp
birgersp

Reputation: 4956

Solved using integer primary key autoincrement as type for customerId.

create table Customers (
    customerId integer primary key autoincrement,
    firstname varchar(255),
    surname varchar(255)
);

Upvotes: 1

Related Questions