Constraints define conditions about a database that must remain true. They are used to ensure data integrity. Commonly used constraints are primary key constraints, foreign key constraints, and unique constraints. Constraints are also used to enforce non-null column values.
A constraint is typically defined as part of the table definition as is created using something similar to the following syntax:
CREATE TABLE ORDERS (
ORDER_ID NUMBER(7) NOT NULL,
PRODUCT_ID NUMBER(7) NOT NULL,
PRODUCT_NAME VARCHAR2(100) NOT NULL,
CONSTRAINT ORDER_ID_PK
PRIMARY KEY(ORDER_ID),
CONSTRAINT PRODUCTS_PRODUCT_ID_FK
FOREIGN KEY(PRODUCT_ID)
REFERENCES PRODUCTS(PRODUCT_ID)
)
The preceding table definition creates two constraints: one for the primary key on the ORDER_ID column; and one for the PRODUCT_ID column foreign key.
Constraints can also be created on a table using the ALTER TABLE syntax, as follows:
ALTER TABLE ORDERS
ADD CONSTRAINT PRODUCTS_PRODUCT_ID_FK
FOREIGN KEY(PRODUCT_ID)
REFERENCES PRODUCTS(PRODUCT_ID)
Filed under: Oracle, pl/sql, Programming, SQL | Tagged: constraints, database, Oracle | 1 Comment »