Oracle constraints are rules defined on columns or sets
of columns in a table to enforce data integrity and ensure that the data stored in the database satisfies certain conditions. Constraints help maintain the accuracy, consistency, and reliability of the data. Here are some common types of constraints in Oracle along with examples:
NOT NULL Constraint:
Ensures that a column cannot contain a null value.
Example: sql Copy code CREATE TABLE employees ( employee_id NUMBER PRIMARY KEY, first_name VARCHAR2(50) NOT NULL, last_name VARCHAR2(50) NOT NULL, email VARCHAR2(100) UNIQUE NOT NULL, hire_date DATE NOT NULL ); UNIQUE Constraint:
uniquely in a table. Example: sql Copy code CREATE TABLE departments ( department_id NUMBER PRIMARY KEY, department_name VARCHAR2(100), location_id NUMBER ); FOREIGN KEY Constraint:
Maintains referential integrity by enforcing a link
between the data in two tables. Example: sql Copy code CREATE TABLE employees ( employee_id NUMBER PRIMARY KEY, first_name VARCHAR2(50), last_name VARCHAR2(50), department_id NUMBER, FOREIGN KEY (department_id) REFERENCES departments(department_id) ); CHECK Constraint:
Ensures that all values in a column satisfy a specific
condition. Example: sql Copy code CREATE TABLE orders ( order_id NUMBER PRIMARY KEY, order_date DATE, order_amount NUMBER, status VARCHAR2(20), CHECK (status IN ('Pending', 'Processing', 'Completed', 'Cancelled')) ); These constraints help in maintaining data integrity and consistency within the Oracle database by preventing the insertion of invalid or inconsistent data.