0% found this document useful (0 votes)
19 views138 pages

System Design (DBMS)

Uploaded by

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

System Design (DBMS)

Uploaded by

lakshay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 138

System Design (DBMS)

Ashish Rastogi
Introduction

Database languages are used for read, update and store


data in a database. There are several such languages that
can be used for this purpose; one of them is SQL
(Structured Query Language).
• SQL is abbreviation for Structured Query Language
• A Database Language that communicates with
Relational Database
• Can be divided into more specific language
• DDL
• DML
• DCL
• TCL
DDL

• DDL is abbreviation for Data Definition Language


• Used to define the database structure or schema
• CREATE - to create objects in the database
• ALTER - alters the structure of the database
• DROP - delete objects from the database
• TRUNCATE - remove all records from a table
• RENAME - rename an object
DML

• DML is abbreviation for Data Manipulation Language


• Used to manipulate data within schema objects
• SELECT - retrieve data from the a database
• INSERT - insert data into a table
• UPDATE - updates existing data within a table
• DELETE - deletes all records from a table, the space for
the records remain
DCL

• DCL is abbreviation for Data Control Language


• Used to define roles and permissions to access
database
• GRANT - gives user's access privileges to database
• REVOKE - withdraw access privileges given with the
GRANT command
TCL

• TCL is abbreviation for Transactional Control


Language
• Used to manage the changes made by DML statements
• COMMIT - save work done
ROLLBACK - restore database to original since the last
COMMIT
Working with Tables
OUT LINE

SQL
SQLConstraint
ConstraintMeaning
Meaning

Write
WriteConstraint
Constraint

Constraint
ConstraintType
Type
 Cons tr a i nt Me a ni ng :-

 Constraints can be specified when a table is


created (with the CREATE TABLE
statement) or after the table is created (with
the ALTER TABLE statement)

 Constraints are used to limit the


type of data that can go into a
table.
 Constraint Write:-

Constrai Constraint[ Constraint


nt ]name Type
m p le me n t at ion Way
 Constraint I

You can define constraints syntactically in


two ways:
1. As part of the definition of an individual column or attribute.
This is called inline specification.

2. As part of the table definition. This


is called out-of-line specification.
 Constraint Type:-

Not Null .1
Unique Key .2
Primary Key .3
Foreign Key .4
Check Key .5
Default Key .6
Co ns tr a i nt Ty pe : -

Not Null

 constraint enforces a column to NOT accept


NULL values. constraint enforces a column to
NOT accept NULL values.
 This means that you cannot insert a
new record, or update a record without
adding a value to this field.
 Expression of Not Null we use short cut NN
Co ns tr a i nt Ty pe : -

-: Not Null Example .1

Create Table Language


(
Language_Name varchar2(30),
Language_Id number(15) Constraint
Constraint_Language_language_name_NN
Not Null
);
Co ns tr a i nt Ty pe : -

Unique Key .2

The UNIQUE constraint uniquely


identifies each record in a
database table.
Co ns tr a i nt Ty pe : -

Example 2. Unique Key

Create Table Person


(
Person_Id number(15)
Constraint Person_person_id_UN Unique
Person_name varchar2(40),
Person_BD Date
);
Co ns tr a i nt Ty pe : -

Example 2. Unique Key

Create Table Person


(
Person_Id number(15),
Person_name varchar2(40),
Person_BD Date
Constraint Person_person_id_UN Unique
(Person_Id)
);
Co ns tr a i nt Ty pe : -

Primary Key .3

 Primary keys must contain unique values

 A primary key column cannot contain


NULL values.
 Each table should have a primary key,
and each table can have only ONE
primary key
Co ns tr a i nt Ty pe : -

Primary Key Example .3

CREATE TABLE locations_demo


)
location_id NUMBER(4) Constraint Constraint_loc_id_pk
PRIMARY KEY ,
street_address VARCHAR2(40) ,
postal_code VARCHAR2(12)
);
Co ns tr a i nt Ty pe : -

Primary Key Example .3

CREATE TABLE locations_demo


)
location_id NUMBER(4) ,
street_address VARCHAR2(40) ,
postal_code VARCHAR2(12) ,
Constraint Constraint_loc_id_pk PRIMARY KEY
(Location_id)
);
Co ns tr a i nt Ty pe : -

Unique Key
Unique Key

Primary Key
Co ns tr a i nt Ty pe : -

Unique
Unique Key Key

 accept only one null value

 unique key use many time in


table.
Co ns tr a i nt Ty pe : -

Primary
Unique Key

Key
Primary key does not accept null value

 primary key use only one time


in table.
Co ns tr a i nt Ty pe : -

Foreign Key .4
Unique Key
 A FOREIGN KEY in one table points to a
PRIMARY KEY in another table

 The FOREIGN KEY constraint is used to


prevent actions that would destroy links
between tables.
Co ns tr a i nt Ty pe : -

Foreign Key Example .4

Unique Key
The "Persons" table:

CIty Address FirstName LastName P-Id

Sandnes Timoteivn Ola Hansen 1


10
Sandnes Borgvn23 Tove Svendson 2

Sandnes Storagt 20 Kari Pettersen 3


Co ns tr a i nt Ty pe : -

Foreign Key Example .4

Unique Key
The “Order" table:

P_id OrderNo O_Id


3 77895 1
3 44678 2
2 22456 3
1 24562 4
Co ns tr a i nt Ty pe : -

Foreign Key Example .4

"P_Id" column in the "Orders" table points to the

e
"P_Id" column in the "Persons" table.

No t
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.
Co ns tr a i nt Ty pe : -

Foreign Key Example .4


First step must create “Person” Table

Create Table Person


(
P_Id number Constraint constraint_person_person_Id_PK primary key,
LastName varcahr2(45),
FirstName varchar2(45),
Address varchar2(45),
City varchar2(45)
);
Co ns tr a i nt Ty pe : -

Foreign Key Example .4

Create Table Order


(
Order_id number(15) CONSTRAINT con_Order_id_pk Primary Key,
OredrNO number(30) ,
P_id number(15) CONSTRINT con_person_order_id_FK references Person (p_id)
);
Co ns tr a i nt Ty pe : -

Check Key .5

 The CHECK constraint is used to limit


the value range that can be placed in a
column.
 If you define a CHECK constraint on a
single column it allows only certain values
for this column
Co ns tr a i nt Ty pe : -

Check Key Example .5

CREATE TABLE divisions


(
div_no NUMBER CONSTRAINT check_divno CHECK
(div_no BETWEEN 10 AND 99),

div_name VARCHAR2(9) CONSTRAINT check_divname_cc CHECK


(div_name = UPPER(div_name))

);
Co ns tr a i nt Ty pe : -

Check
DefaultKey
Key.5.6

 The DEFAULT constraint is used to


insert a default value into a column
 The default value will be added to all
new records
if no other value is specified.
Co ns tr a i nt Ty pe : -

Check
DefaultKey
Key.5Example .6
CREATE TABLE Persons
(
P_Id Number(15),
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT 'Sandnes'
);
o s i t e K e y E x a mpl e
 Comp

Create table person


(
Person_ID Number(15),
Person_phone number(15),
Constraint con_person_un
Unique(Person_ID,Person_Phone)
);
Domain Types in SQL

• char(n). Fixed length character string, with user-specified length n.


• varchar(n). Variable length character strings, with user-specified
maximum length n.
• int. Integer (a finite subset of the integers that is machine-dependent).
• smallint. Small integer (a machine-dependent subset of the integer
domain type).
• numeric(p,d). Fixed point number, with user-specified precision of p
digits, with n digits to the right of decimal point.
• real, double precision. Floating point and double-precision floating point
numbers, with machine-dependent precision.
• float(n). Floating point number, with user-specified precision of at least n
digits.
Integrity constraints in the ALTER TABLE command

ALTER TABLE Student ADD Primary key(Reg_no);

ALTER TABLE Course


ADD CONSTRAINT Reg_fkey
FOREIGN KEY (Stu_Reg) REFERENCES Student(Stu_Reg);

ALTER TABLE Student


DROP Primary key;

ALTER TABLE Course


DROP CONSTRAINT Reg_fk;

ALTER TABLE Student ADD city varchar(20)

ALTER TABLE Student modify city char(30)


Select Command and Logical Operator

Logical Operators Description


OR For the row to be selected at least one of the conditions must be true.
AND For a row to be selected all the specified conditions must be true.
NOT For a row to be selected the specified condition must be false.

SELECT first_name, last_name, subject


FROM student_details
WHERE subject = 'Maths' OR subject = 'Science'

SELECT first_name, last_name, age


FROM student_details
WHERE age >= 10 AND age <= 15;

SELECT first_name, last_name, games


FROM student_details
WHERE NOT games = 'Football'
Oracle Function

A function is an expression in which an SQL keyword or special operator


executes some operation
• sum()
• Avg()
• Max()
• Min()
• Count()

SELECT MAX (flight_date) FROM FlightAvailability

SELECT SUM (economy_seats_taken + business_seats_taken +


firstclass_seats_taken)
as seats_taken FROM FLIGHTAVAILABILITY;

SELECT AVG (DISTINCT flying_time), SUM (DISTINCT miles)


FROM Flights

SELECT COUNT (DISTINCT flying_time), SUM (DISTINCT miles)


FROM Flights
Grouping data from Tables in SQL

The Oracle PL/SQL GROUPING function is used to identify the final aggregated rows in grouped rows using ROLLUP and
CUBE extension clauses. It returns numeric values to identify the column value in an aggregated row

SELECT COUNT (country), region FROM Countries GROUP BY region HAVING COUNT (country) > 1

SELECT fact_1_id,
fact_2_id,
SUM(sales_value) AS sales_value
FROM dimension_tab
GROUP BY ROLLUP (fact_1_id, fact_2_id)
ORDER BY fact_1_id, fact_2_id;

FACT_1_ID FACT_2_ID SALES_VALUE


---------- ---------- -----------
1 1 4363.55
1 2 4794.76
1 3 4718.25
1 4 5387.45
1 5 5027.34
1 24291.35
2 1 5652.84
2 2 4583.02
2 3 5555.77
2 4 5936.67
2 5 4508.74
2 26237.04
Grouping data from Tables in SQL

In addition to the subtotals generated by the ROLLUP extension, the CUBE extension will generate subtotals for all combinations
of the dimensions specified. If "n" is the number of columns listed in the CUBE, there will be 2n subtotal combinations.
SELECT fact_1_id,
fact_2_id,
SUM(sales_value) AS sales_value
FROM dimension_tab
GROUP BY CUBE (fact_1_id, fact_2_id)
ORDER BY fact_1_id, fact_2_id;

FACT_1_ID FACT_2_ID SALES_VALUE


---------- ---------- -----------
1 1 4363.55
1 2 4794.76
1 3 4718.25
1 4 5387.45
1 5 5027.34
1 24291.35
2 1 5652.84
2 2 4583.02
2 3 5555.77
2 4 5936.67
2 5 4508.74
2 26237.04
1 10016.39
2 9377.78
3 10274.02
4 11324.12
5 9536.08
Database Design
Normalization

Ashish Rastogi
Understanding Data Redundancy

What is data
redundancy?
Understanding Data Redundancy (Contd.)

Redundancy means repetition


of data.
Understanding Data Redundancy (Contd.)

Redundancy:
Increases the time involved in updating, adding, and deleting
data.
Increases the utilization of disk space and hence, disk I/O
increases.
Redundancy can, therefore, lead to:
Insertion, modification, and deletion of data, which may cause
inconsistencies.
Errors, which are more likely to occur when facts are repeated.
Unnecessary utilization of extra disk space.
Understanding Data Redundancy (Contd.)

Consider the STUDENT table, as shown in the following


diagram.
STUDENT
STUDENTID

STUDENTNAME

STUDENTBIRTHDATE

STUDENTADDRESS

STUDENTCITY

STUDENTZIP

STUDENTCLASS

STUDENTSEMESTER

STUDENTTEST1

STUDENTTEST2
Understanding Data Redundancy (Contd.)

The STUDENT table contains the values for each attribute,


as shown in the following diagram.

STUDENTID STUDENTNAME …… STUDENTSEMESTER STUDENTTEST1 STUDENTTEST2

001 Mary …… SEM-1 40 65

001 Mary …… SEM-2 56 48

002 Jake …… SEM-1 93 84

002 Jake …… SEM-2 85 90

The details of the students, such as STUDENTID and


STUDENTNAME are repeated while recording marks of different
semesters.
Definition of Normalization

How can I
remove data
redundancy?
Definition of Normalization (Contd.)

We can remove data redundancy


with the help of normalization. Let
us understand this concept.
Definition of Normalization (Contd.)

Normalization:
Is a method of breaking down complex table structures into
simple table structures by using certain rules.
Has the following benefits:
It helps in maintaining data integrity.
It helps in simplifying the structure of tables, therefore, making a
database more compact.
It helps in reducing the null values, which reduces the complexity
of data operations.
Definition of Normalization (Contd.)

Some rules that should be followed to achieve a good


database design are:
Each table should have an identifier.
Each table should store data for a single type of entity.
Columns that accept NULLs should be avoided.
The repetition of values or columns should be avoided.
Definition of Normalization (Contd.)

Normalization results in the formation of tables that satisfy


certain normal forms.
The normal forms are used to remove various types of
abnormalities and inconsistencies from the database.
The most important and widely used normal forms are:
First Normal Form (1NF)
Second Normal Form (2NF)
Third Normal Form (3NF)
Boyce-Codd Normal Form (BCNF)
Definition of Normalization (Contd.)

First Normal Form (1NF):


A table is said to be in 1NF when each cell of the table
contains precisely one value.
The guidelines for converting a table into 1NF are:
Place the related data values in a table. Further, define similar
data values with the column name.
There should be no repeating group in the table.
Every table must have a unique primary key.
Definition of Normalization (Contd.)

Consider the PROJECT table, as shown in the following diagram.

PROJECT table is not in first normal form because cells


Primary key in PROJCODE and HOURS have more than one value.
Definition of Normalization (Contd.)

By applying the 1NF definition to the PROJECT table, you arrive at the table, as
shown in the following diagram.
Definition of Normalization (Contd.)

Consider the STUDENT table, as shown in the following diagram.

STUDENT table contains null values in PHONE


NUMBER2 column, and the number of telephone
Primary key numbers per student is restricted to two.
Definition of Normalization (Contd.)

If a student has three telephone


numbers, you are constrained to
record only two and leave the third
unrecorded.
Definition of Normalization (Contd.)

By applying the 1NF definition to the STUDENT table, you can arrive at the
tables, as shown in the following diagram.
Definition of Normalization (Contd.)

To convert the table to 2NF, you


must first understand the concept
of functional dependency.
Definition of Normalization (Contd.)

Functional dependency:
Attribute A is functionally dependent on B if and only if, for each
value of B, there is exactly one value of A.
Attribute B is called the determinant.
Definition of Normalization (Contd.)

Consider the REPORT table, as shown in the following diagram.

Primary key
Definition of Normalization (Contd.)

In the REPORT table:


For a particular value of ROLL_NUMBER+COURSE_CODE, there
is precisely one corresponding value for MARKS.
Hence, MARKS is functionally dependent on
ROLL_NUMBER+COURSE_CODE.
This can be symbolically represented as:
(ROLL_NUMBER, COURSE_CODE)MARKS.
Definition of Normalization (Contd.)

The following diagram shows the functional dependency between


MARKS and ROLL_NUMBER+COURSE_CODE.

ROLL_NUMBER

MARKS

COURSE_CODE
Definition of Normalization (Contd.)

The other functional dependencies in the REPORT table are:


COURSE_CODECOURSE_NAME
COURSE_CODET_NAME (Assuming one course is taught by only one
teacher.)
T_NAMEROOM_NUMBER (Assuming each teacher has his/her own,
unshared room.)
MARKSGRADE
Definition of Normalization (Contd.)

COURSE_NAME, T_NAME, and ROOM_NUMBER attributes are


partially dependent on the whole key.
This dependency is called partial dependency, as shown in the
following diagram.

COURSE_NAME

ROLL_NUMBER

T_NAME

COURSE_CODE

ROOM_NUMBER
Definition of Normalization (Contd.)

ROOM_NUMBER is dependent on T_NAME, and T_NAME is


dependent on COURSE_CODE, as shown in the following
diagram.
Definition of Normalization (Contd.)

This type of dependency is called


as transitive dependency.
Definition of Normalization (Contd.)

The following diagram shows the transitive dependency.

COURSE_CODE T_NAME ROOM_NUMBER


Definition of Normalization

Second Normal Form (2NF):


A table is said to be in 2NF when:
It is in the 1NF, and
No partial dependency exists between non-key attributes and
key attributes.

The guidelines for converting a table into 2NF are:


Find and remove attributes that are functionally dependent on
only a part of the key and not on the whole key. Place them in
a different table.
Group the remaining attributes.
Definition of Normalization (Contd.)

Consider the PROJECT table, as shown in the following diagram.

The preceding table could lead to the following problems:


Insertion
Updation
Deletion
Definition of Normalization (Contd.)

Consider the PROJECT table, as shown in the following diagram.

The preceding table could lead to the following problems:


The department of an employee cannot be recorded until the
Insertion employee is assigned a project.
Updation
Deletion
Definition of Normalization (Contd.)

Consider the PROJECT table, as shown in the following diagram.

The preceding table could lead to the following problems:


For an employee, ECODE, DEPT, and DEPTHEAD are
Insertion repeated. Any change will have to be recorded in every row of
the EMPLOYEE table.
Updation
Deletion
Definition of Normalization (Contd.)

Consider the PROJECT table, as shown in the following diagram.

The preceding table could lead to the following problems:


Insertion
Updation
When the project finishes, the employee details are deleted.
Deletion This leads to loss in information about the department to
which employee belongs.
Definition of Normalization (Contd.)

Let us check if the PROJECT


table is in 2NF.
Definition of Normalization (Contd.)

Hours is functionally dependent on the


Composite key whole key, ECODE+PROJCODE.
Definition of Normalization (Contd.)

Dept is functionally dependent on part of


Composite Key the key, which is ECODE.
Definition of Normalization (Contd.)

DEPTHEAD is functionally dependent on


ECODE; however, it is not dependent on
Composite Key the attribute, PROJCODE.
Definition of Normalization (Contd.)

To convert the PROJECT table into


2NF, you must remove the
attributes that are not functionally
dependent on the whole key.
Definition of Normalization (Contd.)

You should place the removed


attributes in a different table along
with the attribute they are
functionally dependent on.
Definition of Normalization (Contd.)

The EMPLOYEEDEPT and PROJECT tables are in 2NF, as shown in the


following diagram.
Definition of Normalization (Contd.)

Third Normal Form (3NF):


A relation is said to be in the 3NF if and only if:
It is in 2NF, and
No transitive (indirect) dependency exists between non-key attributes
and key attributes.

The guidelines for converting a table into 3NF are:


Find and remove non-key attributes that are functionally dependent on
attributes that are not the primary key. Place them in a different table.
Group the remaining attributes.
Definition of Normalization (Contd.)

Consider the EMPLOYEE table, as shown in the following diagram.

The preceding table could lead to the following problems:


Insertion
Updation
Deletion
Definition of Normalization (Contd.)

Consider the EMPLOYEE table, as shown in the following diagram.

The preceding tableThe


could lead to
department theoffollowing
head problems:
a new department that does not have any
employees at present cannot be entered in the DEPTHEAD column.
Insertion
Updation
Deletion
Definition of Normalization (Contd.)

Consider the EMPLOYEE table, as shown in the following diagram.

The preceding table could lead to the following problems:


Insertion For a department, DEPTHEAD is repeated. Any change will
have to be made consistently across the table.
Updation
Deletion
Definition of Normalization (Contd.)

Consider the EMPLOYEE table, as shown in the following diagram.

The preceding table could lead to the following problems:


Insertion
If an employee record is deleted, the information
Updation about DEPTHEAD will also be deleted.
Deletion
Definition of Normalization (Contd.)

Let us check if the


EMPLOYEE table is in 3NF.
Definition of Normalization (Contd.)

DEPTHEAD is functionally dependent on DEPT,


Primary key which is not a primary key.
Definition of Normalization (Contd.)

To convert the EMPLOYEE table into 3NF, you must remove the
DEPTHEAD column and place it in another table, as shown in
the following diagram.
Definition of Normalization (Contd.)

Boyce-Codd Normal Form (BCNF):


The original definition of 3NF was not sufficient in some
situations. It was not satisfactory for the tables:
That had multiple candidate keys.
Where the multiple candidate keys were composite.
Where the multiple candidate keys overlapped (had at least one
attribute in common).

The guidelines for converting a table into BCNF are:


Find and remove the overlapping candidate keys. Place the part
of the candidate key and the attribute it is functionally dependent
on, in a different table.
Group the remaining items into a table.
Definition of Normalization (Contd.)

Consider the PROJECT table, as shown in the following


diagram. NAME+PROJCODE can also be chosen
Primary Key as the primary key and hence, is a
candidate key.

PROJECT table is already in 3NF


Definition of Normalization (Contd.)

The following points describe the functional dependencies in


the PROJECT table:
HOURS is functionally dependent on ECODE+PROJCODE.
HOURS is also functionally dependent on NAME+PROJCODE.
NAME is functionally dependent on ECODE.
ECODE is functionally dependent on NAME.

You will notice that the PROJECT table has:


Multiple candidate keys that are ECODE+PROJCODE and
NAME+PROJCODE.
Composite candidate keys.
Candidate keys that overlap since the PROJCODE attribute is
common between the two candidate keys.
Definition of Normalization (Contd.)

The only non-key item is HOURS, which is dependent on the


whole key, ECODE+PROJCODE or NAME+PROJCODE.
ECODE and NAME are determinants since they are
functionally dependent on each other.
As per BCNF, the determinants have to be candidate keys.
You can remove NAME and ECODE and place them in a
different table.
Definition of Normalization (Contd.)

You can remove NAME and ECODE and place them in a


different table, as shown in the following diagram.
Fourth Normal Form (4NF)

In the fourth normal form,


• It should meet all the requirement of 3NF
• Attribute of one or more rows in the table should not result in
more than one rows of the same table leading to multi-valued
dependencies
To understand it clearly, consider a table with Subject, Lecturer who
teaches each subject and recommended Books for each subject.
Fourth Normal Form (4NF)

• If we observe the data in the table above it satisfies 3NF. But


LECTURER and BOOKS are two independent entities here. There is no
relationship between Lecturer and Books. In the above example, either
Alex or Bosco can teach Mathematics. For Mathematics subject ,
student can refer either 'Maths Book1' or 'Maths Book2'. i.e.;
• SUBJECT --> LECTURER
• SUBJECT-->BOOKS

This is a multivalued dependency on SUBJECT. If we need to select both


lecturer and books recommended for any of the subject, it will show up
(lecturer, books) combination, which implies lecturer who recommends
which book. This is not correct.
Fourth Normal Form (4NF)

To eliminate this dependency, we divide the table into two as below:


Fifth Normal Form (5NF)

A database is said to be in 5NF, if and only if,


• It's in 4NF
• If we can decompose table further to eliminate redundancy and anomaly, and when
we re-join the decomposed tables by means of candidate keys, we should not be
losing the original data or any new record set should not arise. In simple words,
joining two or more decomposed table should not lose records nor create new
records.
Consider an example of different Subjects taught by different lecturers and the
lecturers taking classes for different semesters.
Note: Please consider that Semester 1 has Mathematics, Physics and Chemistry and
Semester 2 has only Mathematics in its academic year!!
Fifth Normal Form (5NF)

In above table, Rose takes both Mathematics and Physics class for Semester 1,
but she does not take Physics class for Semester 2. In this case, combination of
all these 3 fields is required to identify a valid data. Imagine we want to add a
new class - Semester3 but do not know which Subject and who will be taking
that subject. We would be simply inserting a new entry with Class as Semester3
and leaving Lecturer and subject as NULL. As we discussed above, it's not a
good to have such entries. Moreover, all the three columns together act as a
primary key, we cannot leave other two columns blank!
Fifth Normal Form (5NF)

Hence we have to decompose the table in such a way that it satisfies all the rules till 4NF
and when join them by using keys, it should yield correct record. Here, we can represent
each lecturer's Subject area and their classes in a better way. We can divide above table
into three - (SUBJECT, LECTURER), (LECTURER, CLASS), (SUBJECT, CLASS)
SQL Vs NoSQL

Video 2

99
Identifying the Types of Indexes

Index:
Enables fast searching of data.
Accelerates queries that join tables, and performs sorting and
grouping.
Enforces uniqueness of rows, (if configured for that)
Contains a collection of keys and pointers.
Keys are the values built from one or more columns in the
table.
Identifying the Types of Indexes (Contd.)

Pointers store the address of the location where a data page


is stored in the memory, as depicted in the following figure.
Identifying the Types of Indexes (Contd.)

Indexes are of the following types:


Clustered index
Nonclustered index
Identifying the Types of Indexes (Contd.)

Clustered index:
It sorts and stores the data rows in the table based on their key values.
The following figure displays a clustered index on the Employee table.
Identifying the Types of Indexes (Contd.)

Nonclustered index:
The physical order of the rows is not the same as the index
order.
The following figure represents the working of a nonclustered
index.
Creating Indexes

Index:
Is created on the most frequently queried column in tables or
views.
Based on two or more columns is called a composite index.
Can be created by using the CREATE INDEX statement.
Creating Indexes (Contd.)

You can create a clustered index on the EmployeeID attribute of the Employee table by
using the following statement:
CREATE CLUSTERED INDEX IX_EmployeeID
ON Employee (EmployeeID)
WITH FILLFACTOR = 10

The following statement creates a nonclustered index on the ManagerID attribute of the
Employee table:
CREATE NONCLUSTERED INDEX IDX_Employee_ManagerID
ON Employee (ManagerID)
Creating Indexes (Contd.)

Consider the following guidelines while creating indexes on a


table:
Create clustered indexes on columns that have unique or not null
values.
Do not create an index that is not used frequently. You require
time and resources to maintain indexes.
Create a clustered index before creating a nonclustered index. A
clustered index changes the order of rows. A nonclustered index
would need to be rebuilt if it is built before a clustered index.
Create nonclustered indexes on all columns that are frequently
used in predicates and join conditions in queries.
SQL Queries

10
How to create a table with the same structure with data
as in the Student table?

Ans. Create table Student2 as Select * from Student;

10
Write q query to find all the employees whose salary is between
5000 to 50000.

Ans. SELECT * FROM EmployeePosition WHERE Salary BETWEEN '5000' AND


'50000';

11
Write a SQL query to fetch all employee records from EmployeeDetails
table who have a salary record inEmployeeSalary table.

Ans. SELECT * FROM EmployeeDetails E WHERE EXISTS (SELECT * FROM


EmployeeSalary S WHEREE.EmpId = S.EmpId);

11
Write a SQL query to fetch duplicate records from a table.

Ans. SELECT EmpId, Project, Salary, COUNT(*) FROM EmployeeSalary GROUP BY


EmpId, Project, SalaryHAVING COUNT(*) > 1;

11
Write a SQL query to fetch project-wise count of employees
sorted by project's count in descending order.

Ans. SELECT Project, count(EmpId) EmpProjectCount FROM EmployeeSalary GROUP


BY Project ORDER BY EmpProjectCount DESC;

11
Write a SQL query to fetch all the Employees who are also
managers from EmployeeDetails table.

Ans. SELECT DISTINCT E.FullName FROM EmpDetails E INNER JOIN EmpDetails M


ON E.EmpID =M.ManagerID;

Or
SELECT DISTINCT E.FullName FROM EmpDetails E JOIN EmpDetails M ON E.EmpID
=M.ManagerID;

11
Joins
Querying Data by Using Joins

What are
Joins?
Querying Data by Using Joins (Contd.)

Joins:
Allow to retrieve data from multiple tables.
Can be of the following types:
Inner join
Outer join
Cross join
Equi join
Self join
Using an Inner Join

Inner join:
Retrieves records from multiple tables after comparing
values present in a common column.
Retrieves only those rows that satisfy the join condition.
Syntax:
SELECT column_name, column_name [,column_name]
FROM table1_name JOIN table2_name
ON table1_name.ref_column_name join_operator
table2_name.ref_column_name
Using an Inner Join (Contd.)

Let us now understand the


working of inner join.
Using an Inner Join (Contd.)

COLUMNS COLUMNS
ABC BDE

Table X Table Y

INNER JOIN

ABCDE

COMMON ROWS

OUTPUT
Using an Inner Join (Contd.)

For example:
SELECT e.EmployeeID,e.Title,
eph.Rate,eph.PayFrequency
FROM Employee e JOIN EmployeePayHistory eph
ON e.EmployeeID = eph.EmployeeID
Output

Employee table EmployeePayHistory table


Using an Inner Join (Contd.)

An inner join is the default join.


Therefore, you can also apply an
inner join by using the JOIN
keyword.
Using an Outer Join

Outer join:
Displays the result set containing all the rows from one table
and the matching rows from another table.
Displays NULL for the columns of the related table where it
does not find matching records.
Is of the following types:
Left outer join
Right outer join
Full outer join
Using an Outer Join (Contd.)

Let us now understand how


different types of outer join
works.
Using an Outer Join (Contd.)

COLUMNS COLUMNS
ABC BDE

Table X Table Y

LEFT OUTER JOIN

ABCDE

ALL ROWS FROM


TABLE X AND
COMMON ROWS
FROM TABLE Y

OUTPUT
Using an Outer Join (Contd.)

COLUMNS COLUMNS
ABC BDE

Table X Table Y

RIGHT OUTER JOIN

ABCDE

ALL ROWS FROM


TABLE Y AND
COMMON ROWS
FROM TABLE X

OUTPUT
Using an Outer Join (Contd.)

COLUMNS COLUMNS
ABC BDE

Table X Table Y

FULL OUTER JOIN

ABCDE

ALL ROWS FROM


TABLE Y AND TABLE
Y AND COMMON
ROWS ONLY ONCE

OUTPUT
Using an Outer Join (Contd.)

Syntax:
SELECT column_name, column_name
[,column_name]
FROM table1_name [LEFT | RIGHT| FULL] OUTER
JOIN table2_name ON
table1_name.ref_column_name join_operator
table2_name.ref_column_name
Using an Outer Join (Contd.)

Left outer join:


Returns all rows from the table specified on the left side of the
LEFT OUTER JOIN keyword and the matching rows from the
table specified on the right side.
Displays NULL for the columns of the table specified on the
right side where it does not find matching records.
For example:
SELECT p.ProductID, p1.SalesOrderID,
p1.UnitPrice FROM SpecialOfferProduct p LEFT
JOIN SalesOrderDetail] p1 ON p.
ProductID = p1.ProductID WHERE
SalesOrderID IS NULL
Using an Outer Join (Contd.)

The following figure displays the output of the preceding


query.

Displays NULL for


the ProductIDs for
which no transaction
was performed
Using an Outer Join (Contd.)

Right outer join:


Returns all the rows from the table specified on the right side
of the RIGHT OUTER JOIN keyword.
Returns the matching rows from the table specified on the left
side.
For example:
SELECT e.Title, d.JobCandidateID FROM Employee
e
RIGHT JOIN JobCandidate d ON
e.EmployeeID=d.EmployeeID
Using an Outer Join (Contd.)

The following figure displays the output of the preceding


query.

Displays the
JobCandidateID column
from the JobCandidate
table and the Title
column from the
matching rows of the
Employee table
Using an Outer Join (Contd.)

Full outer join:


Is a combination of left outer join and right outer join.
Returns all the matching and non-matching rows from both
the tables.
For example:
SELECT e.EmployeeID, e.EmployeeName,
ed.EmployeeEducationCode,
ed.Education
FROM Employee e FULL JOIN Education ed
ON e.EmployeeEducationCode =
ed.EmployeeEducationCode
Using an Outer Join (Contd.)

The following figure displays the output of the preceding


query.

The employee details and


. highest educational
their
qualification is displayed.
For non-matching values,
NULL is displayed.
Using a Cross Join

Cross join:
Is also known as the Cartesian Product.
Joins each row from one table with each row of the other
table.
Let us now understand the
working of cross join.
Using a Cross Join (Contd.)

COLUMNS COLUMNS
ABC BDE

Table X Table Y

n ROWS
CROSS JOIN m ROWS

ABCDE

ALL ROWS (n X m)
EACH ROW OF
TABLE X JOINED
WITH EACH ROW OF
OUTPUT TABLE Y
Using a Cross Join (Contd.)

For example, consider the following figure.

The result set contains nine rows.


Using a Cross Join (Contd.)

Consider the following query:


SELECT A.CompDescription, B.AddOnDescription, A.Price +
B.Price AS 'Total Cost' FROM ComputerDetails A CROSS JOIN
AddOnDetails B

Output

Combines the records of both the tables to display the total price
of a computer with all the possible combinations

You might also like