📜  SQL primary-key(1)

📅  最后修改于: 2023-12-03 15:05:17.261000             🧑  作者: Mango

SQL Primary Key

In SQL, a primary key is a column or a group of columns that uniquely identify each row in a table. A primary key constraint ensures that there are no duplicate values in the primary key columns and that each value is not null.

Syntax

The syntax for creating a primary key constraint is as follows:

CREATE TABLE table_name (
    column1 datatype PRIMARY KEY,
    column2 datatype,
    column3 datatype,
    ...
);

A primary key can consist of a single column or a combination of columns. You can also specify the name of the primary key constraint using the following syntax:

CREATE TABLE table_name (
    column1 datatype,
    column2 datatype,
    column3 datatype,
    ...,
    CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ...)
);
Example

Let's create a table and define a primary key constraint:

CREATE TABLE students (
    id INT PRIMARY KEY,
    name VARCHAR(50),
    age INT
);

In this example, the primary key consists of a single column "id", which is an integer and is marked as the primary key. This means that each value in the "id" column must be unique and not null.

We can insert some data into the table:

INSERT INTO students (id, name, age) VALUES
(1, 'John', 22),
(2, 'Mary', 21),
(3, 'Bob', 23);

If we try to insert a duplicate value for the "id" column, we will get an error:

INSERT INTO students (id, name, age) VALUES (3, 'Jane', 20); -- Error: Duplicate entry '3' for key 'PRIMARY'

We can also update the data in the table:

UPDATE students SET name = 'Alice' WHERE id = 1;

And delete data from the table:

DELETE FROM students WHERE id = 2;
Conclusion

In conclusion, a primary key is an essential element of a relational database, as it ensures data integrity and uniqueness. Use it wisely and carefully, and your database will be robust and reliable.