0% found this document useful (0 votes)
24 views9 pages

Constraints

SQL constraints are rules that ensure data integrity in relational databases by limiting the types of data that can be inserted, updated, or deleted. Key types of constraints include NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, and DEFAULT, each serving specific purposes for maintaining data quality. Additionally, the document discusses the IDENTITY property for auto-incrementing values and provides an overview of the SELECT statement for retrieving data from databases.

Uploaded by

Saman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views9 pages

Constraints

SQL constraints are rules that ensure data integrity in relational databases by limiting the types of data that can be inserted, updated, or deleted. Key types of constraints include NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, and DEFAULT, each serving specific purposes for maintaining data quality. Additionally, the document discusses the IDENTITY property for auto-incrementing values and provides an overview of the SELECT statement for retrieving data from databases.

Uploaded by

Saman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Constraints

What Are SQL Constraints?


SQL constraints are rules applied to columns or tables in a relational database to limit the type of
data that can be inserted, updated, or deleted. These rules ensure the data is valid, consistent,
and adheres to the business logic or database requirements. Constraints can be enforced during
table creation or later using the ALTER TABLE statement. They play a vital role in maintaining the
quality and integrity of your database.
Types of SQL Constraints
SQL provides several types of constraints to manage different aspects of data integrity. These
constraints are essential for ensuring that data meets the requirements of accuracy, consistency,
and validity. Let’s go through each of them with detailed explanations and examples.
1. NOT NULL Constraint
The NOT NULL constraint ensures that a column cannot contain NULL values. This is particularly
important for columns where a value is essential for identifying records or performing
calculations. If a column is defined as NOT NULL, every row must include a value for that column.
Example:
CREATE TABLE Student
(
ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
ADDRESS varchar(20)
);
Explanation: In the above example, both the ID and NAME columns are defined with the NOT
NULL constraint, meaning every student must have an ID and NAME value.
2. UNIQUE Constraint
The UNIQUE constraint ensures that all values in a column are distinct across all rows in a table.
Unlike the PRIMARY KEY, which requires uniqueness and does not allow NULLs, the UNIQUE
constraint allows NULL values but still enforces uniqueness for non-NULL entries.
Example:
CREATE TABLE Student
(
ID int(6) NOT NULL UNIQUE,
NAME varchar(10),
ADDRESS varchar(20)
);
Explanation: Here, the ID column must have unique values, ensuring that no two students can
share the same ID. We can have more than one UNIQUE constraint in a table.
3. PRIMARY KEY Constraint
A PRIMARY KEY constraint is a combination of the NOT NULL and UNIQUE constraints. It uniquely
identifies each row in a table. A table can only have one PRIMARY KEY, and it cannot accept NULL
values. This is typically used for the column that will serve as the identifier of records.
Example:
CREATE TABLE Student
(
ID int(6) NOT NULL UNIQUE,
NAME varchar(10),
ADDRESS varchar(20),
PRIMARY KEY(ID)
);
Explanation: In this case, the ID column is set as the primary key, ensuring that each student’s ID is
unique and cannot be NULL.
4. FOREIGN KEY Constraint
A FOREIGN KEY constraint links a column in one table to the primary key in another table. This
relationship helps maintain referential integrity by ensuring that the value in the foreign
key column matches a valid record in the referenced table.
Orders Table:
O_ID ORDER_NO C_ID

1 2253 3

2 3325 3

3 4521 2

4 8532 1
Customers Table:
C_ID NAME ADDRESS

1 RAMESH DELHI

2 SURESH NOIDA

3 DHARMESH GURGAON
As we can see clearly that the field C_ID in Orders table is the primary key in Customers table, i.e.
it uniquely identifies each row in the Customers table. Therefore, it is a Foreign Key in Orders
table.
Example:
CREATE TABLE Orders
(
O_ID int NOT NULL,
ORDER_NO int NOT NULL,
C_ID int,
PRIMARY KEY (O_ID),
FOREIGN KEY (C_ID) REFERENCES Customers(C_ID)
)
Explanation: In this example, the C_ID column in the Orders table is a foreign key that references
the C_ID column in the Customers table. This ensures that only valid customer IDs can be inserted
into the Orders table.
5. CHECK Constraint
The CHECK constraint allows us to specify a condition that data must satisfy before it is inserted
into the table. This can be used to enforce rules, such as ensuring that a column’s value meets
certain criteria (e.g., age must be greater than 18)
Example:
CREATE TABLE Student
(
ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
AGE int NOT NULL CHECK (AGE >= 18)
);
Explanation: In the above table, the CHECK constraint ensures that only students aged 18 or older
can be inserted into the table.
6. DEFAULT Constraint
The DEFAULT constraint provides a default value for a column when no value is specified during
insertion. This is useful for ensuring that certain columns always have a meaningful value, even if
the user does not provide one
Example:
CREATE TABLE Student
(
ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
AGE int DEFAULT 18
);
Explanation: Here, if no value is provided for AGE during an insert, the default value of 18 will be
assigned automatically.
Identity Property
It enables you to store, organize, and manipulate data in a relational format, meaning data is
organized into tables.

IDENTITY to an Existing Column


There are times when we need to modify the structure of our tables. One common requirement is
to add an identity property to an existing column in the SQL Server.
In SQL Server, The identity column uniquely identifies a row. We can have only one identity
column per table. This can be beneficial for creating primary keys or other scenarios where
unique, incremental values are required.
We can use IDENTITY to define a column with auto-increment values. It auto-generates a new
unique number when inserting a new record into the table.
Syntax:
IDENTITY [ (seed , increment) ]
 Seed: The identity column's first value is known as the seed. If we specify a seed, SQL Server
will begin generating identity values starting from this seed. For example, if the seed is 1, the
first identity value will be 1.
 Increment: The increment is the value added to the seed to get the next identity value. if the
increment is 1, each subsequent identity value will be incremented by 1.
Adding IDENTITY to an Existing Column
If the table is created and we want to add IDENTITY to an existing column, it’s not supported.
Suppose we have a table employees created without the IDENTITY property on the id column:
Query:
CREATE TABLE employees
(
id int NOT NULL,
first_name varchar(20),
last_name varchar(30)
);
Now, if we try to modify the existing column id to add the IDENTITY property directly.
Query:
ALTER TABLE employees
ALTER COLUMN id INT IDENTITY(1,1);
Explanation: when we will run this it would result in an error similar to Incorrect syntax near
'IDENTITY'. So, when we define an identity column, it must be done at the time of the column
creation. Once the table is created, we cannot directly alter a column to become an identity
column.
However, there are a few ways around this:
 Drop the column, recreate it with identity on.
 Or create a new table with identity column and drop the old table, then rename the table.
Assuming we have a table products:
Query:
CREATE TABLE products (
product_id INT NOT NULL,
product_name VARCHAR(50),
price DECIMAL(10, 2)
);Drop the column and recreate it:
Now, we want to add an identity column to product_id. Here are the steps
1. Drop the Column and Recreate it
First, drop the column id without IDENTITY.
Query:
//Dropping the existing column
ALTER TABLE products
DROP COLUMN product_id;
Add the new column with IDENTITY.
Query:
ALTER TABLE products
ADD product_id INT IDENTITY(1, 1) NOT NULL;
2. Recreate the Table
Create a new table with the IDENTITY column
CREATE TABLE products_temp
(
product_id INT IDENTITY(1, 1),
product_name VARCHAR(50),
price DECIMAL(10, 2)
);
Move data to the new table using SWITCH
ALTER TABLE products
SWITCH TO products_temp;
or move data using INSERT.
Query:
INSERT INTO products_temp (product_id, product_name, price)
SELECT product_id, product_name, price
FROM products;
Drop the old table.
Query:
DROP TABLE products;
Rename the new table.
Query:
EXEC sp_rename 'products_temp', 'products';
Update the IDENTITY seed if necessary."DBCC CHECKIDENT('products');"
Now, the products table has the product_id column with the IDENTITY property.
After inserting these values in the table.
Query:
INSERT INTO products (product_name, price)
VALUES
('Product A', 19.99),
('Product B', 29.99),
('Product C', 39.99);

SELECT * FROM products;


Output:
product_id product_name price

1 Product A 19.99

2 Product B 29.99

3 Product C 39.99
Explanation: The product_id values are automatically generated and incremented due to the
identity property, starting from the specified seed value of 1 and incrementing by 1 for each new
record.

Data Manipulation
Understanding the SELECT Command Format
The SELECT Clause
SELECT Statement in SQL
The SELECT statement in SQL is used to fetch or retrieve data from a database. It allows users to
access the data and retrieve specific data based on specific conditions.
We can fetch either the entire table or according to some specified rules. The data returned is
stored in a result table. With the SELECT clause of a SELECT command statement, we specify the
columns that we want to be displayed in the query result and, optionally, which column headings
we prefer to see above the result table.
The SELECT clause is the first clause and is one of the last clauses of the select statement that the
database server evaluates. The reason for this is that before we can determine what to include in
the final result set, we need to know all of the possible columns that could be included in the final
result set.
Syntax:
The syntax for the SELECT statement is:
SELECT column1,column2…. FROM table_name ;
SELECT Statement Example
Let’s look at some examples of the SQL SELECT statement, to understand it better.
Let’s create a table which will be used in examples:
CREATE TABLE:
CREATE TABLE Customer(
CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(50),
LastName VARCHAR(50),
Country VARCHAR(50),
Age int(2),
Phone int(10)
);
-- Insert some sample data into the Customers table
INSERT INTO Customer (CustomerID, CustomerName, LastName, Country, Age, Phone)
VALUES (1, 'Shubham', 'Thakur', 'India','23','xxxxxxxxxx'),
(2, 'Aman ', 'Chopra', 'Australia','21','xxxxxxxxxx'),
(3, 'Naveen', 'Tulasi', 'Sri lanka','24','xxxxxxxxxx'),
(4, 'Aditya', 'Arpan', 'Austria','21','xxxxxxxxxx'),
(5, 'Nishant. Salchichas S.A.', 'Jain', 'Spain','22','xxxxxxxxxx');
Output:

Example 1: Retrieve Data using SELECT Query


In this example, we will fetch CustomerName, LastName from the table Customer:
Query:
SELECT CustomerName, LastName FROM Customer;
Output:

Example 2: Fetch All Table using SELECT Statement


In this example, we will fetch all the fields from the table Customer:
Query:
SELECT * FROM Customer;
Output:
Example 3: SELECT Statement with WHERE Clause
Suppose we want to see table values with specific conditions then WHERE Clause is used with
select statement.
Query:
SELECT CustomerName FROM Customer where Age = '21';
Output:

Example 4: SQL SELECT Statement with GROUP BY Clause


In this example, we will use SELECT statement with GROUP BY Clause
Query:
SELECT COUNT (item), Customer_id FROM Orders GROUP BY order_id;
Output:

Example 5: SELECT Statement with HAVING Clause


Consider the following database for HAVING Clause:
Query:
SELECT Department, sum(Salary) as Salary
FROM employee
GROUP BY department
HAVING SUM(Salary) >= 50000;
Output:
Example 6: SELECT Statement with ORDER BY clause in SQL
In this example, we will use SELECT Statement with ORDER BY clause
Query:
SELECT * FROM Customer ORDER BY Age DESC;
Output:

Important Points with SQL SELECT Statement


 It is used to access records from one or more database tables and views.
 The SELECT statement retrieves selected data based on specified conditions.
 The result of a SELECT statement is stored in a result set or result table.
 The SELECT statement can be used to access specific columns or all columns from a table.
 It can be combined with clauses like WHERE, GROUP BY, HAVING, and ORDER BY for more
refined data retrieval.
 The SELECT statement is versatile and allows users to fetch data based on various criteria
efficiently.

You might also like