Keys and constraints
Now that we have our main tables defined, let's try to think about how the data inside would look. Each row inside a table would describe an object, which may be either a book or a customer. What would happen if our application has a bug and allows us to create books or customers with the same data? How will the database differentiate them? In theory, we will assign IDs to customers in order to avoid these scenarios, but how do we enforce that the ID not be repeated?
MySQL has a mechanism that allows you to enforce certain restrictions on your data. Other than attributes such as NOT NULL
or UNSIGNED
that you already saw, you can tell MySQL that certain fields are more special than others and instruct it to add some behavior to them. These mechanisms are called keys, and there are four types: primary key, unique key, foreign key, and index. Let's take a closer look at them.
Primary keys
Primary keys are fields that identify a unique row from a table. There cannot be two...