0% found this document useful (0 votes)
0 views62 pages

Lecture2 SQL ConstraintII

The document provides an overview of SQL constraints, including NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, and DEFAULT. It explains the use of auto-increment for unique record identification and demonstrates how to create tables, insert records, and manage constraints in SQL. Additionally, it covers examples of altering tables and inserting data while adhering to defined constraints.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views62 pages

Lecture2 SQL ConstraintII

The document provides an overview of SQL constraints, including NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, and DEFAULT. It explains the use of auto-increment for unique record identification and demonstrates how to create tables, insert records, and manage constraints in SQL. Additionally, it covers examples of altering tables and inserting data while adhering to defined constraints.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Database Management System

Md. Manowarul Islam


Lecturer
Dept. of CSE
Jagannath University.
SQL Constraints

◼ Constraints are used to limit the type of data that


can go into a table.
◼ Constraints can be specified
❑ when a table is created
❑ with the CREATE TABLE statement
◼ Constraints can be specified after the table is
created
❑ with the ALTER TABLE statement

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Auto increment

◼ Auto-increment allows a unique number to be


generated automatically when a new record
is inserted into a table.
◼ Typically, you use the AUTO_INCREMENT
attribute for the primary key column of the
table.

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Example

◼ Create a table
CREATE TABLE animals (
id INT NOT NULL AUTO_INCREMENT,
name CHAR(30) NOT NULL,
PRIMARY KEY (id)
);

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Insert rows

◼ To insert a new record we will NOT have to


specify a value for the “id" column
insert into animals (name)
VALUES('Cat'),('Whale')

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Insert rows

◼ To insert a new record we will NOT have to


specify a value for the “id" column
insert into animals (name)
VALUES('Dog')

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Show the result

◼ Select * from animals

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Show the result
INSERT INTO animals (id,name)
VALUES(NULL,'squirrel');
Select * from animals

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Alter statement

◼ You can reset the auto-increment value by using


the ALTER TABLE statement.
◼ The syntax of the ALTER TABLE statement to
reset the auto increment value is as follows:
◼ ALTER TABLE table_name
AUTO_INCREMENT = value;

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Set a value

ALTER TABLE animals AUTO_INCREMENT = 1000

insert into animals (name) VALUES('Cow')

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


SQL Constraints

◼ We will focus on the following constraints:


❑ NOT NULL
❑ UNIQUE
❑ PRIMARY KEY
❑ FOREIGN KEY
❑ CHECK
❑ DEFAULT

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


SQL Constraints

◼ The CHECK Constraint enables a condition to


check the value being entered into a record.
◼ If the condition evaluates to false, the record
violates the constraint and isn't entered the
table.

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


SQL CHECK Constraint
CREATE TABLE Persons
(
P_Id int NOT NULL CHECK (P_Id>0),
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Let’s create a table
CREATE TABLE Employee (
EmpID INT(11) NOT NULL PRIMARY KEY,
Name VARCHAR(30) NOT NULL, Column level

AGE INT NOT NULL CHECK (AGE >= 18)


);

CREATE TABLE Employee1(


EmpID INT(11) NOT NULL PRIMARY KEY,
Name VARCHAR(30) NOT NULL,
AGE INT NOT NULL,
Table level
Address VARCHAR(30) NOT NULL,
CHECK (AGE >= 18)
);

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Let us do some exercise
◼ Create a table called customer

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Insert item
insert into employee values
(1000, 'Manowar', 19)

insert into employee values


(1010, 'Liton', 20)

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Insert item age<18
insert into employee values
(1002, 'Milton', 15)

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Alter table

ALTER TABLE Employee MODIFY AGE


INT NOT NULL CHECK (AGE >= 18 );

ALTER TABLE Employee


ADD CONSTRAINT myCheckConstraint CHECK(AGE >= 18);

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


select COLUMN_NAME, CONSTRAINT_NAME, REFERENCED_COLUMN_NAME,
REFERENCED_TABLE_NAME
from information_schema.KEY_COLUMN_USAGE
where TABLE_NAME = 'employee'

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


CMD (Method-1)
+R
C:\Users\Islam>cd c:
C:\Users\Islam

C:\Users\Islam>cd ..

C:\Users>cd .. Welcome to the MariaDB monitor. Commands end with ; or \g.


Your MariaDB connection id is 439
C:\>cd xampp Server version: 10.4.11-MariaDB mariadb.org binary distribution

C:\xampp>cd mysql Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

C:\xampp\mysql>cd bin Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

C:\xampp\mysql\bin>mysql.exe -u root -p MariaDB [(none)]>


Enter password:

Show create table employee

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


CMD (Method-2)
Setting environment for using XAMPP for Windows.
Lab-2@DESKTOP-UGV9ION c:\xampp

# cd mysql
Lab-2@DESKTOP-UGV9ION c:\xampp\mysql

# cd bin
Lab-2@DESKTOP-UGV9ION c:\xampp\mysql\bin

# mysql.exe -u root -p
Enter password:

Welcome to the MariaDB monitor. Commands end with ; or \g.


Your MariaDB connection id is 439
Server version: 10.4.11-MariaDB mariadb.org binary distribution

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]>

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


CMD
MariaDB [(none)]> show databases;
+--------------------+
| Database |
+--------------------+
| bcctest |
| information_schema |
| mysql |
| performance_schema |
| phpmyadmin |
| test |
+--------------------+
6 rows in set (0.001 sec)

MariaDB [(none)]> use bcctest;


Database changed
MariaDB [bcctest]>

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


As enum
create table tb1(
city varchar(250) NOT NULL CHECK (city IN ('Rangpur','Dhaka','Rajshahi'))
)

insert into tb1 values('DHAKA')

insert into tb1 values('rajshahi')

insert into tb1 values('rajshahi')

Select * from tb1;

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


As enum
insert into tb1 values('Dinajpur')

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


As enum
create table gender(
gen varchar(20) NOT NULL check (gen='M' OR gen='F')
);

insert into gender values('m'); 

insert into gender values(‘M'); 

insert into gender values(‘R'); X

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


SQL Constraints

◼ We will focus on the following constraints:


❑ NOT NULL
❑ UNIQUE
❑ PRIMARY KEY
❑ FOREIGN KEY
❑ CHECK
❑ DEFAULT

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Default value
◼ Why use the MySQL DEFAULT value?
❑ For most of the data types, MySQL provides ‘NULL’ as
a DEFAULT value.
❑ For predefined standards or business rules, we can
use DEFAULT values instead of manually specifying
the field every time.
❑ Inserting DATETIME value in a DATE column to
identify when the record inserted in a table.

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Default value
◼ Implicit: MySQL automatically sets a default
value if not provided.
◼ Explicit: We can explicitly set a DEFAULT
value when creating or altering a table.

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Example

◼ Create the following table


create table users(
userID int NOT NULL,
SALARY DECIMAL (18, 2) DEFAULT 5000.00,
country varchar(255) DEFAULT 'BANGLADESH'
)

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Example

◼ Describe the table

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Example

◼ Describe the table


❑ insert into users (userID)values(100)

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Example

◼ Describe the table


ALTER TABLE users
Alter JoinDate DATETIME DEFAULT CURRENT_TIMESTAMP()

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Example

◼ Adding a column and set default value


ALTER TABLE users
ADD JoinDate DATETIME DEFAULT CURRENT_TIMESTAMP()

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Example

◼ Adding values

insert into users (userID)values(101)

insert into users (userID)values(101)

insert into users (userID)values(102)

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Example

◼ Add a new column name city


ALTER TABLE users
ADD city varchar(100) NOT NULL

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Example

◼ Add a default value


ALTER TABLE users
ALTER City SET DEFAULT 'Dhaka'

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Example

◼ Insert
insert into users (userID)values(104)

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Dropping a default value

◼ Drop

ALTER TABLE users


ALTER city DROP DEFAULT;

insert into users (userID)values(105)

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Show all information

Select * from users

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


FOREIGN KEY

◼ A foreign key is a column or group of columns in a table


that links to a column or group of columns in another
table.
◼ A Foreign Key is a column or a combination of columns
whose values match a Primary Key in a different table.
◼ Establishes a relationship between a primary key or a
unique key in the same table or a different table
◼ A foreign key value must match an existing value in the
parent table or be NULL.

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Example
The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.

The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Let us do some exercise
◼ Create a table called customer
CREATE TABLE customer (
CustomerID INT(11) NOT NULL PRIMARY KEY,
Name VARCHAR(30) NOT NULL,
City VARCHAR(30)
);

CREATE TABLE orders(


OrderID int NOT NULL PRIMARY KEY,
productName varchar (100) NOT NULL,
orderCustomerID int NOT NULL,
FOREIGN KEY (orderCustomerID) REFERENCES
customer(CustomerID)
)
CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.
Let us do some exercise
◼ Create a table called customer

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Showing constraint

◼ show index from orders

select COLUMN_NAME, CONSTRAINT_NAME, REFERENCED_COLUMN_NAME,


REFERENCED_TABLE_NAME
from information_schema.KEY_COLUMN_USAGE
where TABLE_NAME = 'orders'

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Insert the data into customer table
insert into customer
value(1001,'Manowar','Dhaka')

insert into customer


value(1002,‘Anowar','Dhaka')

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Insert the data into order table

insert into orders values (1, 'Mobile', 1001)

insert into orders values (2, 'FAN', 1001)

insert into orders values (3, 'FAN', 1002)

insert into orders values (4, 'Light', 1002)

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Look the data

customer

orders

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Look the data
Parent table does not
contain CustomerID
1003

customer

insert into orders values (5, 'FAN', 1003)

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Deleting row from parent table

DELETE FROM customer


WHERE CustomerID = 1001;

Child table has


dependency

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Deleting row from parent table

DELETE FROM orders


WHERE OrderID = 1;

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Updating row from parent table

UPDATE customer
SET CustomerID=1000
WHERE CustomerID = 1001;
Child table has
dependency

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


How to update/delete

◼ CASCADE:
❑ If a row from the parent table is deleted or
updated,
◼ the values of the matching rows in the child table
automatically deleted or updated.

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Example

◼ Create two tables as follows:


CREATE TABLE categories(
categoryId INT AUTO_INCREMENT PRIMARY KEY,
categoryName VARCHAR(100) NOT NULL
)

CREATE TABLE products(


productId INT AUTO_INCREMENT PRIMARY KEY,
productName varchar(100) not null,
categoryId INT NOT NULL,
FOREIGN KEY(categoryId) REFERENCES categories(categoryId)
ON UPDATE CASCADE
ON DELETE CASCADE
)

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Describe the tables

categories

products

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Insert into categories

categories

INSERT into categories (categoryID, categoryName)


values (1,'Phone')

INSERT into categories (categoryID, categoryName)


values (2,'TV')
INSERT into categories (categoryID, categoryName)
values (3,'Printer')
CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.
Show the data

Insert into products


INSERT into products values (100,'Samsung J7', 1)

INSERT into products values (101,‘iPhone 8', 1)

INSERT into products values (102,'Nokia-1100', 1)


CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.
Show the data

Insert into products


INSERT into products values (200,'Walton X', 2)

INSERT into products values (201,'LG-14', 2)

INSERT into products values (203,'National', 2)


CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.
Show the data

Insert into products


INSERT into products values (300, 'HP', 3)

INSERT into products values (301, 'Canon', 3)

INSERT into products values (302,'Epson', 3)


CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.
Show the data

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Show the data

Update the categorieID

UPDATE categories
SET categoryId=1000
WHERE categoryId = 1

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Show the data
Cascading works properly

Delete phone

DELETE FROM categories


WHERE categoryId=1000;

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.


Thanks a lot

CSE-2203 Md. Manowarul Islam, Dept. of CSE, Jagannath University, Dhaka-1100.

You might also like