postgresql
  1. postgresql-primary-key-constraint

Primary Key Constraint - (PostgreSQL Constraints)

In PostgreSQL, constraints are used to enforce rules on the data being inserted into a table. A primary key constraint is a type of constraint that uniquely identifies each record in a table. In this tutorial, we'll discuss the syntax, example, output, explanation, use, important points, and summary of primary key constraints in PostgreSQL.

Syntax

The syntax to create a primary key constraint on a table is as follows:

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

Example

Let's create a table named employees with a primary key constraint on the employee_id column.

CREATE TABLE employees (
  employee_id serial PRIMARY KEY,
  first_name varchar(50),
  last_name varchar(50),
  age integer
);

Explanation

In this example, we created a table named employees with four columns - employee_id, first_name, last_name, and age. The employee_id column was defined as a primary key using the PRIMARY KEY constraint.

The serial data type is used to create an auto-incrementing column. Each time a new row is inserted into the table, the employee_id column will be automatically assigned the next available value.

Use

A primary key constraint is used to uniquely identify each record in a table. This ensures that each record can be uniquely identified and updated or deleted if needed.

Important Points

  • A primary key constraint cannot be NULL.
  • A table can have only one primary key constraint.
  • A primary key constraint can be created on multiple columns.

Summary

In this tutorial, we discussed the syntax, example, output, explanation, use, and important points of primary key constraints in PostgreSQL. With this knowledge, you can now create tables with primary key constraints to uniquely identify each record in a table and enforce data integrity rules.

Published on: