Home >Database >Mysql Tutorial >How to write primary key constraints in mysql
The primary key constraint in MySQL is a unique constraint that clearly defines the unique identifier of each row in the table. Primary key constraints can be created by using the PRIMARY KEY keyword or by specifying it when creating the table. The primary key can be a single column or a compound column (composed of multiple columns). It also supports auto-incrementing primary keys, which will automatically generate unique values when inserting new rows. Primary key constraints ensure data integrity and accuracy because each row has a unique value.
Primary key constraints in MySQL
What are primary key constraints?
A primary key constraint is a unique constraint that uniquely identifies each row of data in a table. It enforces that every row in the table has a unique value, ensuring data integrity and accuracy.
How to create a primary key constraint?
In MySQL, use the PRIMARY KEY
keyword to create a primary key constraint. The syntax is as follows:
<code class="sql">CREATE TABLE table_name ( column_name PRIMARY KEY );</code>
Alternatively, you can specify primary key constraints when creating the table:
<code class="sql">CREATE TABLE table_name ( column_name1 INT NOT NULL, column_name2 VARCHAR(255) NOT NULL, PRIMARY KEY (column_name1, column_name2) );</code>
Compound primary key
A composite primary key consists of two or more consists of columns, which together form a unique identifier for the table. The syntax is similar to a single-column primary key:
<code class="sql">CREATE TABLE table_name ( column_name1 INT NOT NULL, column_name2 VARCHAR(255) NOT NULL, PRIMARY KEY (column_name1, column_name2) );</code>
Auto-increment primary key
MySQL supports auto-increment primary key, which will automatically generate a unique value for each new row when inserting a new row. value. To create an auto-incrementing primary key, use the AUTO_INCREMENT
Keyword:
<code class="sql">CREATE TABLE table_name ( id INT NOT NULL AUTO_INCREMENT, column_name1 VARCHAR(255) NOT NULL, PRIMARY KEY (id) );</code>
Notes
NULL
. The above is the detailed content of How to write primary key constraints in mysql. For more information, please follow other related articles on the PHP Chinese website!