Let's understand Mainframe
Home Tutorials Interview Q&A Quiz Mainframe Memes Contact us About us

Module 8: DB2 Indexes and Constraints


Primary Key

What is a primary key?

  • A primary key is a column (or a group of columns) that uniquely identifies each row in a table.
  • Primary key values must be unique - no two rows can have the same primary key value.
  • A primary key column cannot contain NULL values.
  • A table can have only one primary key, which may consist of a single column or multiple columns. A multi-column primary key is called a composite key.

Defining a primary key

  • Define the primary key in the CREATE TABLE statement, either at column level or table level.
  • You can also add it later with ALTER TABLE, but the key columns must already be declared NOT NULL.
  • DB2 automatically creates a unique index to enforce the primary key.

Example

  • Single-column primary key:-
    CREATE TABLE CUSTOMERS (ID INT NOT NULL, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(25), SALARY DECIMAL(18,2), PRIMARY KEY (ID));
  • Composite primary key:-
    CREATE TABLE CUSTOMERS (ID INT NOT NULL, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(25), SALARY DECIMAL(18,2), PRIMARY KEY (ID, NAME));
  • Add a primary key to an existing table:-
    ALTER TABLE CUSTOMERS ADD PRIMARY KEY (ID);





© copyright mainframebug.com
Privacy Policy
MainframeBug Assistant