Constraints

You can define constraints syntactically in two ways:

  • As part of the definition of an individual column or attribute. This is called inline specification.
  • As part of the table definition. This is called out-of-line specification.

Constraint clauses can appear in the following statements:

SQL Constraints

Constraint Type Description
Primary Key Ensures each record in a table is uniquely identified.
Foreign Key Establishes relationships between tables by linking primary and foreign keys.
Unique Ensures uniqueness of values in specified columns.
Check Defines conditions for data to meet during insert or update operations.
Default Specifies a default value for a column if none is provided during insert.
Not Null Ensures a column cannot contain null values.
Index Optimizes query performance by providing a quick lookup mechanism.

 

source: https://docs.oracle.com/cd/A97630_01/server.920/a96540/clauses3a.htm#1002166

 

 

SQL Constraints and Example Code

Constraint Example Code
Primary Key CREATE TABLE TableName (ID INT PRIMARY KEY, Name VARCHAR(255));
Foreign Key CREATE TABLE Orders (OrderID INT PRIMARY KEY, CustomerID INT, FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID));
Unique CREATE TABLE TableName (Column1 INT UNIQUE, Column2 VARCHAR(255) UNIQUE);
Check CREATE TABLE TableName (Age INT CHECK (Age >= 18));
Default CREATE TABLE TableName (StartDate DATE DEFAULT '2023-01-01');
Not Null CREATE TABLE TableName (ColumnName INT NOT NULL, AnotherColumn VARCHAR(255) NOT NULL);
Index CREATE INDEX idx_ColumnName ON TableName (ColumnName);

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top