3. SQL Introduction MCA 2023
3. SQL Introduction MCA 2023
SQL 1
SQL(Structured Query Language)
Integrity constraints
SQL 4
Domain Types in SQL
SQL 5
Built-in Data Types in SQL
date: Dates, containing a (4 digit) year, month and date
Example: date ‘2005-7-27’
time: Time of day, in hours, minutes and seconds.
Example: time ‘09:00:30’ time ‘09:00:30.75’
timestamp: date plus time of day
Example: timestamp ‘2005-7-27 09:00:30.75’
interval: period of time.
In Oracle this data type is used as below-
SQL 6
Oracle- SQL Data Types…
1. Character
• Char – fixed length character string that can varies between 1-2000
bytes
• Varchar / Varchar2 – variable length character string, size ranges from
1-4000 bytes.
• Long - variable length character string, maximum size is 2 GB
2. Number : Can store +ve,-ve,zero,fixed point, floating point with 38
precision.
• Number – {p=38,s=0}
• Number(p) - fixed point
• Number(p,s) –floating point
SQL 7
SQL Data Types
3. Date : used to store date and time in the table. DB uses its own format of storing in
fixed length of 7 bytes for century, date, month, year, hour, minutes, seconds. The default
data type is “dd-mon-yy”
4. Interval Year To Month : Stores a period of time using the YEAR and MONTH date
time fields
5. Raw Datatype: used to store byte oriented data like binary data and byte string. Mainly
used when moving data between different systems. Oracle Recommends to store as BLOB
6. Other :
• CLOB – A character large object containing single-byte or multi byte characters.
• BLOB – stores large binary objects such as graphics, video, sounds..
• BFILE – Contains a locator to a large binary file stored outside the database.
SQL 8
Different Types of Commands
DDL commands: -
To create and modify database objects - CREATE, ALTER, DROP
DML commands: -
To manipulate data of a database objects- INSERT, DELETE, UPDATE
DQL command: -
To retrieve the data from a database - SELECT
DCL commands: -
To control the data of a database – GRANT, REVOKE
TCL commands:-
To control and manage transactions – COMMIT, SAVEPOINT,
SQL 9
Create Table Construct
An SQL relation is defined using the create table command:
create table r (A1 D1, A2 D2, ..., An Dn); both are equivalent syntax
Therefore designer has to ensure that data entered by user has to be checked against
SQL 11
TYPE of CONSTSRINTS
Rule/Constraints can be imposed on single column or combination of columns.
– Assume that are two columns in the table say- Date_of_Birth and Date_of_Join.
not null -
primary key (A1, ..., An )
foreign key (Am, ..., An ) references r
Unique
Check
Default
SQL 13
NOT NULL
NULL is special kind of value applicable to any domain(datatype).
SQL 16
FOREIGN KEY
foreign key (Ak1 , Ak2, . . . , Akn ) in r references s: The foreign key in a relation r (child)
specification says that the values of attributes (Ak1 , Ak2, . . . , Akn ) for any tuple in the relation r
must correspond to values of the primary key attributes of some tuple in relation s (parent).
Enrollment can be done to only to those who are student, therefore SID column in Enrollment can have only
values which are present in SID in Student table.
This condition is imposed by defining SID in Enrollment as Foreign key referencing Students
SQL 19
..FOREIGN KEY table-level
Example:
Parent(Master) Table:
CREATE TABLE Items( Item_name varchar2(10), Comp_name varchar2(10),
Price Number(3),
PRIMARY KEY (Item_name,Comp_name) );
Child(Detail) Table
CREATE TABLE Transactions( It_name varchar2(10), Comp_name varchar2(10),
Tr_Date date, Qty Number(3),
FOREIGN KEY(It_name,Comp_name) REFERENCES Items);
SQL 20
..FOREIGN KEY
Properties:
A Foreign key can contain-
Only values present in the corresponding Parent Column.
NULL values, provided Foreign key is not defined with additional NOT NULL
constraints.
Foreign key column can reference to any column (parent column) whose data
type, width is same and Parent column has to be defined with Primary key or
Unique constraint.
A Parent Column has to exist before creation of Child Column with Foreign
key Constraint.
SQL 23
..FOREIGN KEY- UPDATE/DELETE Restrictions
Similarly,
UPDATE EMP SET DEPTNO=‘D5’ WHERE EMPNO=100; is Rejected.
UPDATE EMP SET DEPTNO=‘D3’ WHERE EMPNO=100; is Accepted.
DELETE FROM DEPARTMENT WHERE DNO=‘D1’ is Rejected
To execute above DELETE command, execute in following Order
1st Delete from Child Table(EMP) and then 2nd Delete from Parent(DEPARTMENT)
This Deletion process can be automated by using Clause ON DELETE CASCADE / ON DELETE
SET NULL while creating Child Table
Similarly Altering Structure of DNO or Dropping DNO is Rejected.
SQL 24
..FOREIGN KEY- ON DELETE CASCADE/ON DELETE SET NULL
A foreign key with cascade delete means that if a record in the parent table is deleted, then the
corresponding records in the child table will automatically be deleted. This is called a cascade
delete in Oracle.
Example: Create tables give in slide 18 with ON DELETE CASCADE clause along with
FOREIGN KEY.
Parent(Master) Table:
CREATE TABLE Department ( Dno varchar(2) PRIMARY KEY, Name varchar(10),Budget
Number(9) );
Child(Detail) Table
CREATE TABLE Emp( Empno number(3) PRIMARY KEY, Name varchar(10), Deptno
varchar(2) REFERENCES Department ON DELETE SET NULL );
SQL 26
..FOREIGN KEY- ON DELETE CASCADE/ON DELETE SET NULL
SQL 27
..FOREIGN KEY - Recursive Relationship
Example:
CREATE TABLE EMP(Empno number(3) PRIMARY KEY,
Ename Varchar2(10), MGRNO number(3));
SQL 29
..UNIQUE
In the following table combination of Area_code & Phone_Num is Unique
SQL 30
Some Exercises
• Create the following tables with constraints.
EMP FACULTY
Attribute Datatype size Constraint
Attribute Datatype size Constraint
RegNo Number 3 Primary key Faculty_ID Number 3 Primary Key
Name Varchar 10 Name Varchar 10
References DEPT
Faculty_Advisor F.key referring Faculty with set null
constraint on
Dno Deletion
DEPT
Datatyp
Attribute e size Constraint
DeptID Char 3 Unique
Dname Varchar 10 Unique
HOD Varchar 10
SQL 31
The CHECK clause – Using IN
check (P)
where P is a predicate(condition)
Example: ensure that Type of Courses offered by a Department is any one of MCA,
MTech, BTec,MS.
CREATE TABLE PRODUCT(ProdID varchar2(9) PRIMARY KEY CHECK (ProdID LIKE 'JOI-
Example:
Create a table CANDIDATES(CandtID, Name, Branch) appearing for entrance exam at MIT.
Candidate numbers must be Unique & every candidate number must start with MIT.
User must enter Branch in Capital letters only.
SQL 36
DEFAULT
The DEFAULT constraint is used to provide a default value for a column.
Example:
CREATE TABLE Persons (
ID Number(3) NOT NULL,
LastName varchar(10) NOT NULL,
FirstName varchar(10),
Age Number(2),
City varchar(15) DEFAULT 'Manipal' );
SQL 38
..Example
Note the constraint name and error numbers displayed when data being inserted violates constraint
SQL 39
Naming the Constraints
• If user do not specifies Constraint Name while defining Constraints, System itself gives a
name. System uses auto generate method to give unique constraints names such as –
SYS_C0003461 etc. As constraint names have to be unique. In case of constraint
violation, it is easy to user to track the constraint if user defined constraint name is given.
SQL 41
..Example
Note the constraint name displayed when data being inserted violates constraint
SQL 42
Example
Create following tables with constraint names.
CUSTOMER
Attribute Datatype size Constraint Constraint Name
CustNo Number 3 Primary key Pkey_Cust_Number
Unique , Can't UNQ_Phone;
Phone number 10 be Null Ph_NoNULL
email varchar 20 Unique
City varchar 20 BNG/MUB/CHN Valid_City
Date_Birth Date
ACCOUNT
The DROP TABLE statement allows you to remove or delete a table from the database.
Syntax:
SQL 44
Alter Table Constructs
The ALTER TABLE statement is used to add, modify, or drop/delete columns/constraints in
a table.
The SQL ALTER TABLE statement is also used to rename a table.
Adding Column
Syntax:
SQL 45
..Alter Table Constructs
Modifying Column
Syntax:
Example: Modify column Name to size 25 and Salary to 9,2 in the Emp table.
SQL 46
..Alter Table Constructs
DROP a Column
Syntax:
SQL 47
..Alter Table Constructs
RENAME a Table
Syntax:
SQL 48
..Alter Table Constructs
Adding CHECK Constraint to a column
Syntax:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name CHECK( p ) );
Where p - predicate
Example: Add constraint to Students table to check Mark2 column takes values
only in the range 0 to 100.
SQL 49
..Alter Table Constructs
SQL 50
..Alter Table Constructs
Adding PRIMARY KEY Constraint to a column
Syntax:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name
PRIMARY KEY (column1, column2, ... column_n) ;
Example: Assume that Person(Fname, Lname, Address) table is already created. Add
constraint to Person table to make (FName,LName) column as Primary Key.
ALTER TABLE Person ADD CONSTRAINT F_L_Name_PK
PRIMARY KEY (FName,LName);
SQL 51
..Alter Table Constructs
Adding FOREIGN KEY Constraint to a column
Syntax:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name
FOREIGN KEY (column1, column2, ... column_n)
REFERENCES parent_table (column1, column2, ... column_n);
Example: Assume that Person(Fname, Lname, Address) table is already created with (Fname, LName) as
Primary Key. Also a table Customer(Cust_Id, Cust_FName,Cust_Lname,Credits) is also created already.
Now we want to make (Cust_FName,Cust_Lname) as foreign key referencing Person
SQL 52
..Alter Table Constructs
Removing Constraints
Syntax:
ALTER TABLE table_name
DROP CONSTRAINT constraint_name ;
Example: Assume that Person(Fname, Lname, Address) table is already created with
(Fname,LName) as Primary Key. Also assume a table Customer(Cust_Id,
Cust_FName,Cust_Lname,Credits) is also created already with foreign key constraint on
(Cust_FName,Cust_Lname) referencing (Fname,LName).
Example: Insert a record into Course table having values to Course_id, Dept_Name columns
only. Course(Course_id,title,Dept_Name,Credits)
SQL 58
..INSERT (date value)
SQL 59
Insert into… Select .. From…
• Some time instead of giving data for every tuple in the INSERT INTO command,
we can insert tuples on the basis of the result of a query.
• Using SELECT statement as sub query in the INSERT INTO, we can select
(copy) some set of records from a relation(source) and insert into another
relation(Destination).
• Note that we need to take care of datatype and size compatibility.
STUD Rollno Name Course Dept
MARKS Rno Course Marks Attendance
101 Ajit Algorithms CS
Example: Insert Rollno and course information of students enrolled to MCA department into
MARKS relation.
INSERT INTO MARKS(RNo, Course) SELECT Rollno, Course FROM STUD WHERE Dept=‘MCA’;
SQL 60
..INSERT
Inserting multiple records
Syntax-
INSERT INTO table1(column1,column2,..) SELECT column1,column2,.. FROM table2;
Example: Consider the tables Student(Id, Name, D_name, tot_cred) and Instructor(Id, Name,
Dept_name, Salary). Add all instructors to the student relation with tot_creds set to 0
insert into student
select ID, name, dept_name, 0
from instructor;
OR
SQL 62
..UPDATE
• Example: Consider the table Instructor(Id, Name, Dept_name, Salary). Increase
salaries of instructors whose salary is over $100,000 by 3%, and all others receive a
5% raise
• Write two update statements:
UPDATE instructor
SET salary = salary * 1.03
WHERE salary > 100000;
UPDATE instructor
SET salary = salary * 1.05
WHERE salary <= 100000;
• The order is important
SQL 63
..UPDATE –using CASE
• Same query(previous slide) as before but with case statement
UPDATE instructor
SET salary = CASE
WHEN salary <= 100000 THEN salary * 1.05
ELSE salary * 1.03
END;
Assume the table Emp(Empno, ename, deptno,sal)
UPDATE emp SET sal=CASE
WHEN sal<=3000 THEN sal*1.1
WHEN sal<=5000 THEN sal*1.05
ELSE sal*1
END; SQL 64
DELETE
Syntax:
DELETE FROM table_name WHERE condition;
Example:
• Delete all instructors
delete from instructor
SQL 65
..DELETE
Syntax:
DELETE FROM table_name WHERE condition;
Note- Condition is involving some sub-query
Example:
• Delete all tuples in the instructor relation for those instructors associated
with a department located in the ‘Watson’ building.
Delete from instructor
where dept_name in (select dept_name
from department
where building = ’Watson’);
SQL 66
END
SQL 67
CREATE VIEW emp_view(ENO,NAME,DATE_OF_BIRTH) AS SELECT empno, ename,
dob FROM emp;
SQL 68
Sample Tables
SQL 69