We use cookies to enhance your experience on the site
CodeWorlds

Column constraints - rules of order

The data type alone is not enough. The Keeper of the Catalog imposes rules on shelves - so that the data stays consistent and trustworthy. We call these rules constraints, and we write them after the type of a column.

PRIMARY KEY - the primary key

It marks the column that uniquely identifies each row. The value must be unique and cannot be empty:

1id INT PRIMARY KEY

It is like a scroll's catalog number - two rows never share the same one.

AUTO_INCREMENT - automatic numbering

Added to the primary key, it makes MySQL assign by itself the next increasing number to every new row (1, 2, 3...):

1id INT AUTO_INCREMENT PRIMARY KEY

You do not have to remember the last number - the Library counts for you. This is the most common way to create an

id
column.

NOT NULL - a required field

It forces the column to never be empty:

1nazwa VARCHAR(100) NOT NULL

A category without a name makes no sense - so we require it. A column without NOT NULL may stay empty (NULL).

Order matters

In a column definition we always write: the name, the type, and then the constraints - one after another, separated by a space:

1id INT AUTO_INCREMENT PRIMARY KEY,
2nazwa VARCHAR(100) NOT NULL

This is a pattern you will repeat in almost every table.

Go to CodeWorlds