Use app×
QUIZARD
QUIZARD
JEE MAIN 2026 Crash Course
NEET 2026 Crash Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
10.5k views
in Computer by (25.1k points)

Explain SQL constraints with example.

1 Answer

+1 vote
by (26.0k points)
selected by
 
Best answer

SQL Constraints are rules used to limit the type of data that can be stored into a table, to maintain the accuracy and integrity of the data inside table.
Constraints can be divided into two types,

  • Column level constraints: limits only column data
  • Table level constraints: limits whole table data

Constraints are used to make sure that the integrity of data is maintained in the database. The NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT are the most used constraints that can be applied to a table.

1. NOT NULL Constraint:

NOT NULL constraint restricts a column from having a NULL value. Once *NOT NULL* constraint is applied to a column, you cannot store null value to that column. It enforces a column to contain a proper value.
Example using NOT NULL constraint
CREATE table Student(s_id int NOT NULL, Name varchar(60), Age int);

2. UNIQUE Constraint:

UNIQUE constraint ensures that a field or column will only have unique values. A UNIQUE constraint field will not have duplicate data.
Example using UNIQUE constraint when creating a Table
CREATE table Student(s_id int NOT NULL UNIQUE, Name varchar(60), Age int);

3. Primary Key Constraint:

The primary key constraint uniquely identifies each record in a database. A Primary Key must contain unique value and it must not contain a null value.
Example using PRIMARY KEY constraint
CREATE table Student (s_id int PRIMARY KEY, Name varchar(60) NOT NULL, Age int);

4. Foreign Key Constraint:

FOREIGN KEY is used to relate two tables. A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
Example using FOREIGN KEY constraint at Table Level
CREATE TABLE Orders
(
O-Id int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,
P_Id int FOREIGN KEY REFERENCES Persons(P_Id)

)

5. CHECK Constraint:

CHECK constraint is used to restrict the value of a column between a range. It performs check on the values, before storing them into the database.
Example using CHECK constraint
create table Student(s_id int NOT NULL CHECK(s_id > 0), Name varchar(60) NOT NULL, Age int);

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...