SQL - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

SQL Primary Key

SQL Primary Key

shape Description

By defining a column with SQL Primary Key constraint then that primary key constraint won't acknowledge invalid and copy values. And a table can contain only one primary key. Primary key = Unique + Not null Unique constraints can acknowledge null values where as primary key won't acknowledge null and copy values.And for detailed explanation about unique and Not null constraint will there in the following link: Unique Constraint NOT NULL Constraint.

shape Conceptual figure

Primary key - Which is unique and not null. Create table statement - Which is used to create a table in the database. Alter table statement - Which is used to alter a table in the database.

shape Syntax

create table <table_name> (<column_name1>data type(size)constraint constraint name constraint type, <column_name2>data type(size),constraint(column_name1); Table_name =>Any accurate table. Column_name =>The operation that can be performed in the column of a table. constraint_type =>constraint type will specify the type of constraint, that going to be executed in the database.

shape Examples

By viewing the below example, the concept of primary key constraint can be easily understood. [c] sql> create table product(prod_id int not null auto_increment,prod_name varchar(255)not null,primary key(prod_id)); Query OK, 0 rows affected (0.52 sec) sql> insert into product (prod_name) values ('mobile'); Query OK, 1 row affected (0.05 sec) sql> insert into product (prod_name) values ('laptop'); Query OK, 1 row affected (0.09 sec) sql> insert into product (prod_name) values ('system'); Query OK, 1 row affected (0.09 sec) sql> select * from product; +---------+-----------+ | prod_id | prod_name | +---------+-----------+ | 1 | mobile | | 2 | laptop | | 3 | system | +---------+-----------+ 3 rows in set (0.00 sec)[/c] In the above example, the column prod_id is given not null auto increment constraint and at the same time in another column prod_id is given primary key constraint. In such case, no need to insert each and every value, just by writing the prod_name, the prod_id values are displayed automatically.

Summary

shape Key Points

  • SQL Primary Key Constraint - Primary key constraint won't accept invalid and copied values