SQL Examples
SQL Examples
• Constraints can be column level or table level. Column level constraints apply to a
column, and table level constraints apply to the whole table.
• The following constraints are commonly used in SQL:
• NOT NULL - Ensures that a column cannot have a NULL value
• UNIQUE - Ensures that all values in a column are different
• PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies
each row in a table
• FOREIGN KEY - Prevents actions that would destroy links between tables
• CHECK - Ensures that the values in a column satisfies a specific condition
• DEFAULT - Sets a default value for a column if no value is specified
• CREATE INDEX - Used to create and retrieve data from the database very quickly
NOT NULL Constraint
• The NOT NULL constraint in a column means that the column cannot store
NULL values. For example,
• Required create table entitled college , making sure that the college id is
not null
• answer
• CREATE TABLE College (
• college_id INT NOT NULL,
• college_code VARCHAR(10) NOT NULL,
• college_name VARCHAR(35)
• );
UNIQUE Constraint
• The UNIQUE constraint in a column means that the column must have
unique value. For example,
• Required create table entitled college , making sure that the college id is
not null and unique
• answer
• CREATE TABLE College (
• college_id INT NOT NULL UNIQUE,
• college_code VARCHAR(20) UNIQUE,
• college_name VARCHAR(50)
• );
PRIMARY KEY Constraint
• The PRIMARY KEY constraint is simply a combination of NOT NULL and
UNIQUE constraints. It means that the column value is used to uniquely
identify the row. For example,
• Required create table entitled college , making sure that the college id is
the primary key
• answer
• CREATE TABLE College (
• college_id INT PRIMARY KEY,
• college_code VARCHAR(20) NOT NULL,
• college_name VARCHAR(50)
• );
FOREIGN KEY Constraint
• The FOREIGN KEY (REFERENCES in some databases) constraint in a
column is used to reference a record that exists in another table. For
example,
• Required create table entitled order , making sure that the order_id
is the primary key and customer id is the foreign key
• answer
• CREATE TABLE Order (
• order_id INT PRIMARY KEY,
• customer_id int REFERENCES Customers(id)
• );
CHECK Constraint
• The CHECK constraint checks the condition before allowing values in a
table. For example,