×
>
<

DBMS

DBMS Constraint Key | CrackEase

Key in DBMS

Primary Key

A primary key is a constraint that uniquely identifies each row in a table. It can be a single column or a combination of columns and must contain unique, non-NULL values.

Foreign Key

A foreign key is a column (or set of columns) in one table that references the primary key of another table. It enforces referential integrity by ensuring that values in the child table exist in the parent table.

Primary Key

Creating a primary key

Mark a column (or columns) as the primary key using PRIMARY KEY(column). The primary key guarantees row uniqueness and implicitly applies a NOT NULL rule.

  
CREATE TABLE EMP (
  ID    INT,
  NAME  VARCHAR(20),
  AGE   INT,
  COURSE VARCHAR(10),
  PRIMARY KEY (ID)
);
  

  • When ID is a primary key, its values must be unique for every row.
  • If you try to insert a duplicate value into the primary key column, the DBMS will raise an error.
  • The primary key enforces uniqueness and non-NULL for the chosen column(s).

Example (table with a CHECK)
  
CREATE TABLE STUDENT (
    ID    INT,
    Name  VARCHAR(255),
    Age   INT,
    CHECK (Age >= 18)
);
  
Foreign Key

The FOREIGN KEY constraint ensures that values in the child table match values in the parent table's primary (or unique) key column. This preserves referential integrity.

Example: create parent (customers) table
  
CREATE TABLE CUSTOMERS1 (
   ID     INT,
   NAME   VARCHAR(20),
   COURSE VARCHAR(10),
   PRIMARY KEY (ID)
);
  
Child table with foreign key
  
CREATE TABLE CUSTOMERS2 (
   ID     INT,
   MARKS  INT,
   CUSTOMER_ID INT,
   FOREIGN KEY (CUSTOMER_ID) REFERENCES CUSTOMERS1(ID)
);
  

In the example above, CUSTOMER_ID in CUSTOMERS2 must match an existing ID in CUSTOMERS1, otherwise the insert/update will be rejected.

Footer Content | CrackEase