Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 104

DBMS

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
DBMS

DBMS : Data Base Management System ... for storage of data and efficient retrieval of data.

A DBMS has to be persistent (it should be accessible when the program created the data do not exist or even
the application that created the data is restarted).

DBMS has to provide some uniform methods independent of a specific application for accessing the
information that is stored.
It mostly supports single user

Example : Foxpro

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
RDBMS

• RDBMS is based on relational model, in which data is represented in the form of relations,
with enforced relationships between the tables.
• RDBMS defines the integrity constraint for the purpose of holding ACID PROPERTY.
• In RDBMS, normalization process will be present to check the database table consistency
• RDBMS helps in recovery of the database in case of loss of data
• Example : Oracle, MySQL

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Differences between

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
What is a table?
• The data in an RDBMS is stored in database objects which are called as tables. This table is basically
a collection of related data entries and it consists of numerous columns and rows.
• Remember, a table is the most common and simplest form of data storage in a relational database.
The following program is an example of a Students table

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
What is a field?
• Every table is broken up into smaller entities called fields. The fields in the CUSTOMERS table
consist of ID, NAME, AGE, ADDRESS and SALARY.
• A field is a column in a table that is designed to maintain specific information about every
record in the table.
What is a Record or a Row?
• A record is also called as a row of data is each individual entry that exists in a table. For
example, there are 7 records in the above CUSTOMERS table. Following is a single row of data
or record in the CUSTOMERS table −
1 | Ramesh | 32 | Ahmedabad | 2000.00

A record is a horizontal entity in a table.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
What is a column?
• A column is a vertical entity in a table that contains all information associated with a specific field in a
table.
• For example, a column in the CUSTOMERS table is ADDRESS, which represents location description
and would be as shown below −
ADDRESS
|Ahmedabad |
| Delhi |
| Kota |
| Mumbai |
| Bhopal |
| MP |
| Indore |

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
What is a NULL value?
•A NULL value in a table is a value in a field that appears to be blank, which means a field with a NULL value
is a field with no value.
•It is very important to understand that a NULL value is different than a zero value or a field that contains
spaces. A field with a NULL value is the one that has been left blank during a record creation.

SQL Constraints
•Constraints are the rules enforced on data columns on a table. These are used to limit the type of data that can
go into a table. This ensures the accuracy and reliability of the data in the database.
•Constraints can either be column level or table level. Column level constraints are applied only to one column
whereas, table level constraints are applied to the entire table

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
ER Modelling

• ER model stands for an Entity-Relationship model. It is a high-level data model. This model
is used to define the data elements and relationship for a specified system.
• It develops a conceptual design for the database. It also develops a very simple and easy to
design view of data.
• In ER modeling, the database structure is portrayed as a diagram called an entity-
relationship diagram.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
ER diagram into table

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
ER diagram into table

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Following are some of the most commonly used constraints available in SQL −
• NOT NULL Constraint − Ensures that a column cannot have a NULL value.
• DEFAULT Constraint − Provides a default value for a column when none is specified.
• UNIQUE Constraint − Ensures that all the values in a column are different.
• PRIMARY Key − Uniquely identifies each row/record in a database table.
• FOREIGN Key − Uniquely identifies a row/record in any another database table.
• CHECK Constraint − The CHECK constraint ensures that all values in a column satisfy certain
conditions.
• INDEX − Used to create and retrieve data from the database very quickly

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Data Integrity
• The following categories of data integrity exist with each RDBMS −
• Entity Integrity − There are no duplicate rows in a table.
• Domain Integrity − Enforces valid entries for a given column by restricting the type, the
format, or the range of values.
• Referential integrity − Rows cannot be deleted, which are used by other records.
• User-Defined Integrity − Enforces some specific business rules that do not fall into entity,
domain or referential integrity.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Database Normalization
• Database normalization is the process of efficiently organizing data in a database. There are two
reasons of this normalization process −
• Eliminating redundant data, for example, storing the same data in more than one table.
• Ensuring data dependencies make sense also improving data integrity
• Without normalization we may face issues such as
o Insertion anamoly
o Update anamoly
o Deletion anamoly

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Student_id S_Name S_Dep S_Credit Tower Room Dep_HOD
1 Manoj CSE 8 SJT 215 A
2 Srinkanth IT 7 SJT 211 B
3 Kavya ECE 8 TT 204 C
4 Rohit CSE 9 SJT 215 A
5 Soniya EEE 7.4 TT 201 D
6 Karan ECE 8.1 TT 204 C

Insertion anamoly
If a new department has to be updated in this table where a student is not enrolled yet. We cant enter student id, name,
credit etc.
Updation anamoly
If a room of a particular department is shifted to another room, say room 215 to 225 for CSE. In this the room attribute
has to be updated for all the tuples which might result in updation anamoly it is not done properly
Deletion anamoly
If a particular tuple is deleted which results in the loss of other information which may not be specific to a particular
record, then that is called delete anamoly. E.g. deletion of student id 5 results in deletion of EEE department details in
table.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
To overcome previously mentioned anamolies, we’ll reconstruct the table in a way that the
redundant information are kept minimal.
This can be achieved using normlization

Student_id S_Name S_Dep S_Credit Dept_Id Tower Room Dep_HOD


1 Manoj CSE 8 CSE SJT 215 A
2 Srinkanth IT 7 IT SJT 211 B
3 Kavya ECE 8 ECE TT 204 C
4 Rohit CSE 9 EEE TT 201 D
5 Soniya EEE 7.4
6 Karan ECE 8.1

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
• Normalization guidelines are divided into normal forms; think of a form as the format or the
way a database structure is laid out. The aim of normal forms is to organize the database
structure, so that it complies with the rules of first normal form, then second normal form
and finally the third normal form.
• It is your choice to take it further and go to the fourth normal form, fifth normal form and so
on, but in general, the third normal form is more than enough.
First Normal Form (1NF)
Second Normal Form (2NF)
Third Normal Form (3NF)

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
• First Normalization is a simple scalable design which can be easily extended
• If a table is not in 1 NF then we can say it is a bad design
• 1NF follows 4 rules
o Each column should contain atomic values
o A column should hold a value of same type. Do not mix any value of a column like, integer for one
row and a string for another etc.
o Each column should have a unique name
o Order in which the data stored should not matter

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Roll_No Name Subject
101 Rohan Java, C
102 Rekha Networks
103 Sunil Python, DS

• Above table satisfies three rules out of 4 to achieve 1NF


• Only issue here is Subject column is holding non atomic values.
• This can be eliminated by modifying the entries as

Roll_No Name Subject


101 Rohan Java
102 Rekha Networks
103 Sunil Python
101 Rohan C
103 Sunil DS

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
• A table is in second normalization form
• If it is in 1 NF
• Doesn’t have any partial dependency

Marks Id Student IdSubject Id Marks Subject Id Teacher


Marks Id Student Id Subject Id Marks Teacher
1 101 Java 85 Java Mr. Java
1 101 Java 85 Mr. Java
2 102 Java 90 Network Mr. Network
2 102 Java 90 Mr. Java
3 102 Networks 75 Python Mr. Python
3 102 Networks 75 Mr. Network
4 103 Python 82 C Mr. C
4 103 Python 82 Mr. Python
5 101 C 91 DS Mr. DS
5 101 C 91 Mr. C
6 103 DS 67 OS Mr. OS
6 103 DS 67 Mr. DS

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
• A table is in third normalization form
• If it is in 2 NF
• It should not have transitive dependency
Marks Id Student Id Subject Id Marks Exam name Total marks
1 101 Java 85
2 102 Java 90
3 102 Networks 75
4 103 Python 82
5 101 C 91
6 103 DS 67

• Consider above table, here exam name depends on student and subject
• Total marks depends on exam but not primary key (Consider a subject has theory or practicals or assignments as
different types of exams). But exam name depends on subject. This is called transitive dependency. This can be
avoided by splitting marks table like this

Marks Id Student Id Subject Id Marks Exam name Total marks

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
• A table is in BCNF or 3.5 normal form
• If it is in 3 NF
• For any dependency A->B , A should be a super key
StudentId Subject Professor
101 Java PJ 1
102 C PC 1
101 Python PP 1
104 Java PJ 2
101 C PC 2
102 Python PP 2

• Above table(College enrollment table) is in 1NF, 2NF and 3 NF but the professor. So far we know non-prime
attribute depends on prime attribute or other non-prime attribute. In this case subject is dependent on professor
but professor is not a super key. So this violates BCNF. This can be sorted by splitting college enrollment table
like below

Student Id Prof Id Prof Id Prof Name Subject

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
• A table is in 4th normal form
• If it is in BCNF NF
• And should not have multi valued dependency
• Multivalued dependency A->> B says, there exists for A more than 1 values of B
o Multivalued dependency arises if there is atleast 3 columns in a table A, B & C
o And for
Studen Id A->>, B&
Course C Hobby
must not depend on each other
101 C Cricket
101 Java Dance
102 Python Cricket
102 Java Dance

• Above table doesn’t satisfy 4th NF. To achieve that student enrollment table has to be splitted like below

Student Id Course Student IdHobby

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
DATATYPES IN RDBMS

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
SQL Datatype
SQL Datatype is used to define the values that a column can contain.
Every column is required to have a name and data type in the
database table.
Datatype of SQL:
1. Binary Datatypes
• There are Three types of binary Datatypes which are given below:
Data Type Description
binary It has a maximum length of 8000 bytes. It contains fixed-length binary data.
varbinary It has a maximum length of 8000 bytes. It contains variable-length binary data.
image It has a maximum length of 2,147,483,647 bytes. It contains variable-length binary data.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
2. Exact Numeric Datatype
The subtypes are given below:

Int It is used to specify an integer value.


smallint It is used to specify small integer value.
Bit It has the number of bits to store.
decimal It specifies a numeric value that can have a decimal number.
numeric It is used to specify a numeric value.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
3. Character String Datatype
The subtypes are given below:
Char
It has a maximum length of 8000 characters. It contains Fixed-length non-unicode characters.
Varchar
It has a maximum length of 8000 characters. It contains variable-length non-unicode characters.
text
It has a maximum length of 2,147,483,647 characters. It contains variable-length non-unicode
characters.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
4. Date and time Data types
The subtypes are given below:

date It is used to store the year, month, and days value.


Time It is used to store the hour, minute, and second values.
timestamp It stores the year, month, day, hour, minute, and the second value.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
SQL commands

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
SQL commands

SQL commands or instructions that are used to communicate with the database. It also performs certain tasks, functions and queries the data.

Types of SQL commands

DDL (Data Definition Language)


Create, Drop, Alter

DML (Data Manipulation Language)


Insert, Update, Delete

DQL (Data Query Language)


Select

DCL (Data Control Language)


Grant and Revoke

TCL (Transaction Control Language)


Commit, Rollback and save point

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
TABLE CREATION IN RDBMS

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Creating a basic table involves naming the table and defining its columns and each column's data type.

The SQL CREATE TABLE statement is used to create a new table.


Syntax

CREATE TABLE table_name


( column1 datatype,
column2 datatype,
column3 datatype, ..... columnN datatype, PRIMARY KEY( one or more columns ) );

The following code block is an example, which creates a CUSTOMERS table with an ID as a primary key and NOT NULL are the
constraints showing that these fields cannot be NULL while creating records in this table −
CREATE TABLE CUSTOMERS
( ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2), PRIMARY KEY (ID) );

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
You can verify if your table has been created successfully by looking at the message displayed by
the MySQL, otherwise you can use the DESC command as follows −
DESC CUSTOMERS;
Output

ID int(11) NO PRI

NAME varchar(20) NO

AGE int(11) NO
ADDRESS char(25) YES

SALARY decimal(18,2) YES

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Create Table Using Another Table
• A copy of an existing table can also be created using CREATE TABLE.
• The new table gets the same column definitions. All columns or specific columns can be
selected.
• If you create a new table using an existing table, the new table will be filled with the existing
values from the old table.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Syntax

CREATE TABLE new_table_name AS


    SELECT column1, column2,...
    FROM existing_table_name
    WHERE ....;

The following SQL creates a new table called "TestTables" (which is a copy of the "Customers" table): 
Example
CREATE TABLE TestTable AS
SELECT customername, contactname
FROM customers;

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MODIFYING THE STRUCTURE IN RDBMS

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The SQL ALTER TABLE command is used to change the structure of an existing
table.
It helps to add or delete columns, create or destroy indexes, change the type of
existing columns, or rename columns on an existing.

It can also be used to change the constraints on an existing .

Syntax:
ALTER TABLE <table_name>( ADD column1    data_type[(size)], ADD column2
   data_type[(size)], ...);

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Parameters:
Name Description
table_name Name of the table where data is stored.
column1,column2 Name of the columns of a table.
data_type Char, varchar, integer, decimal, date and more.
size Maximum length of the column of a table.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
SQL ALTER TABLE statement to add/drop a column to a table
• In the following topic, we are discussing the SQL ALTER TABLE statement, which adds a column
to a table. If not specified otherwise, the column will be added at the end of the table.

ALTER TABLE Customers
ADD email varchar(50);
If records are already available in the table, email field will be null if no constraints are not added.

ALTER TABLE Customers
DROP Email;

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
SQL ALTER TABLE statement to change the type or size of an attribute
• In the following topic, we are discussing the SQL ALTER TABLE statement, which modifies the
size of an attribute or type of an attribute.

ALTER TABLE Customers
MODIFY email varchar(255);

ALTER TABLE Customers
MODIFY dob year;

(Modification of the type will not be possible if there exists a record which has incompatible value)

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
SQL ALTER TABLE statement to change the constraint on a table
• In the following topic, we are discussing the SQL ALTER TABLE statement, which modifies some
constraint on a table.

ALTER TABLE Customers
MODIFY dob date not null;

Modification of the type will not be possible if there exists a record which has incompatible value
i.e if there exists a record which already violates not null constraint, then the alter table will result an
error.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
SQL ALTER TABLE statement to add or drop PRIMARY KEY of a table
In the following example, we are going to discuss about the usage of SQL ALTER TABLE statement to add and drop primary
key of a table.

To add a PRIMARY KEY to an existing table, the following SQL statement can be used:

SQL Code:
ALTER TABLE customers
ADD PRIMARY KEY(ID);

Or
ALTER TABLE customers
DROP PRIMARY KEY;

If there exists some records which has some attributes that violates the primary key property will result in error

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
MANIPULATING DATA IN RDBMS

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Data manipulation commands are used to manipulate data in the database.

Some of the Data Manipulation Commands are-

INSERT – To add a record in a table


UPDATE – To modify attribute(s) in a table
DELETE – To delete record(s) in a table

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Insert
• Insert statement is used to insert data into database tables.
General Syntax: 
• INSERT INTO <TABLE NAME> (<COLUMNS TO INSERT>) VALUES (<VALUES TO INSERT>)
Example:
Insert into customers values (1234, "Bill", 55, "123 Wallstreet NY", 1010000000, '1977-04-06');
Insert into customers (id, name, age, address, salary) values (1234, "Bill", 55, "123 Wallstreet NY", 1010000000)

Note : if the number of entries in value set doesn’t match with columns count, record will not be inserted

Update
• The update command updates existing data within a table.
General syntax:
• UPDATE <TABLE NAME> SET <COLUMN NAME> = <UPDATED COLUMN VALUE>, <COLUMN NAME> = <UPDATED
COLUMN VALUE>, <COLUMN NAME> = <UPDATED COLUMN VALUE>,… WHERE <CONDITION>
Example: update customers set name=’AMIT’ where id=1234;
Note : while updatingSMART
or inserting oneRESOURCES
TRAINING should notINDIA
insertPVT.
incompatible
LTD. types1 © 2018 SMART Training Resources Pvt. Ltd.
Delete
• Deletes records from the database table according to the given constraints.
General Syntax:
• DELETE FROM <TABLE NAME> WHERE <CONDITION>Example:
delete from Employee where e_id=5;
To delete all records from the table:
delete * from <TABLE NAME>;

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
QUERYING IN RDBMS

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
SELECT SQL Query
SELECT statement is used to retrieve data from a table. It is the most used SQL query.
We can retrieve complete table data, or partial by specifying conditions using the WHERE
clause.

In SELECT, we can specify the names of the columns which we want in the resultset.

Syntax of SELECT statement


SELECT column_name1, column_name2, column_name3, ...
column_nameN FROM table_name;

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Time for an Example
Consider the following student table,
Sid name age address
101Adam 15 Chennai
102Alex 18 Delhi
103Abhi 17 Banglore
104Ankit 22 Mumbai

SELECT s_id, name, age FROM student;


The above query will fetch information of s_id, name and age columns of the student table and display them,

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Sid name age
101 Adam 15
102 Alex 18
103 Abhi 17
104 Ankit 22

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
As you can see the data from address column is absent, because we did not specif it in our SELECT
query
Select all records from a table
• A special character asterisk * is used to address all the data(belonging to all columns) in a
query. SELECT statement uses * character to retrieve all records from a table, for all the
columns.

SELECT * FROM student;


The above query will show all the records of student table, that means it will show complete
dataset of the table.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Sid name age address
101 Adam 15 Chennai
102 Alex 18 Delhi
103 Abhi 17 Banglore
104 Ankit 22 Mumbai

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Select a particular record based on a condition
• We can use the WHERE clause to set a condition,
• SELECT * FROM student WHERE name = 'Abhi'; The above query will return the following
result,
103Abhi17Rohtak

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Performing Simple Calculations using SELECT Query
Consider the following employee table.

Eid name age salary


101 Adam 26 5000
102 Ricky 42 8000
103 Abhi 25 10000
104 Rohan 22 5000

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The SELECT query adds 3000 to the existing salary or all employees,
• SELECT eid, name, salary+3000 FROM employee;

Eid name salary+3000


101 Adam 8000
102 Ricky 11000
103 Abhi 13000
104 Rohan8000

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Select
Select statement retrieves the data from database according to the constraints specifies alongside.
• SELECT <COLUMN NAME> FROM <TABLE NAME> WHERE <CONDITION> GROUP BY
<COLUMN LIST> HAVING <CRITERIA FOR FUNCTION RESULTS> ORDER BY <COLUMN
LIST>

General syntax:
• Example: select * from employee where e_id>100;

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
JOINS IN RDBMS

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Joins in DBMS and Types

A JOIN clause is used to combine rows from two or more tables based
on a related column between them.

Joins in DBMS and Types


Joins can be broadly classified into two types, Inner Joins and Outer
joins

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Different Types of SQL JOINs
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the right
table
RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from the
left table
FULL (OUTER) JOIN: Returns all records when there is a match in either left or right table

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The INNER JOIN keyword selects records that have matching values in both tables.

SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
• The LEFT JOIN keyword returns all records from the left table (table1), and the matched records
from the right table (table2). The result is NULL from the right side, if there is no match.

SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The RIGHT JOIN keyword returns all records from the right table (table2), and the matched records
from the left table (table1). The result is NULL from the left side, when there is no match.
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
• The FULL OUTER JOIN keyword returns all records when there is a match in left (table1) or right
(table2) table records.
• Note: FULL OUTER JOIN can potentially return very large result-sets!
• Tip: FULL OUTER JOIN and FULL JOIN are the same.
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Looking at above tables we realize that they have a common attribute called DPT_NAME, thus
after the natural join the table becomes as             

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Outer join
• Left outer join – All the tuples of left table is displayed irrespective of whether it satisfies the
matching conditions. Thus in the left all the tuples have been displayed but in the right only those
are present that satisfy the matching conditions. For example consider below example of two
tables – country table that has 3 records and state table that has 4 records. Country names are
given the country_id that has to match with the country_id in the state table. India’s state is
Karnataka and Tamil Nadu, state of Pakistan is Islamabad but Nepal does not have state in the
given table so right part will be null.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
So for left join, left side table have all the values but right side only has those whose COUNTRY_ID
has been matched. 

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
LEFT OUTER JOIN
Bangladesh has not occurred since there is no match found.
2. Right outer join – All the tuples of right table are displayed irrespective of whether it satisfies
the matching conditions or not.. Thus in the right, all the tuples have been displayed but in the
left only those are present that satisfy the matching conditions. The previous example can be
implemented here as well.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Full outer join– Tuples from both the relations takes part irrespective of whether it has the matching
or non-matching conditions. Example is as shown

FULL OUTER JOIN

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
SUBQUERY IN RDBMS

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
What is subquery in SQL?

A subquery is a SQL query nested inside a larger query.

A subquery may occur in :


- A SELECT clause
- A FROM clause
- A WHERE clause

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
• The subquery can be nested inside a SELECT, INSERT, UPDATE, or DELETE
statement or inside another subquery.
• A subquery is usually added within the WHERE Clause of another SQL SELECT
statement.
• You can use the comparison operators, such as >, <, or =. The comparison operator
can also be a multiple-row operator, such as IN, ANY, or ALL.
• A subquery is also called an inner query or inner select, while the statement
containing a subquery is also called an outer query or outer select.
• The inner query executes first before its parent query so that the results of an inner
query can be passed to the outer query.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
You can use a subquery in a SELECT, INSERT, DELETE, or UPDATE statement to perform the
following tasks:
• Compare an expression to the result of the query.
• Determine if an expression is included in the results of the query.
• Check whether the query selects any rows.
Syntax :

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
• The subquery (inner query) executes once before the main query (outer query) executes.
• The main query (outer query) use the subquery result.
SQL Subqueries Example :
• In this section, you will learn the requirements of using subqueries. We have the following two
tables 'student' and 'marks' with common field 'StudentID'.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Now we want to write a query to identify all students who get better marks than that of the student
who's StudentID is 'V002', but we do not know the marks of 'V002'.
- To solve the problem, we require two queries. One query returns the marks (stored in
Total_marks field) of 'V002' and a second query identifies the students who get better marks
than the result of the first query.

First query:
SELECT * FROM `marks` WHERE studentid = 'V002';

Query result:

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
The result of the query is 80.
- Using the result of this query, here we have written another query to identify the students who
get better marks than 80. Here is the query :

Second query:
• SELECT a.studentid, a.name, b.total_marks FROM student a, marks b WHERE a.studentid =
b.studentid AND b.total_marks >80;

Query result:

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
• Above two queries identified students who get the better number than the student who's StudentID
is 'V002' (Abhay).
• You can combine the above two queries by placing one query inside the other. The subquery (also
called the 'inner query') is the query inside the parentheses. See the following code and query
result :

SELECT a.studentid, a.name, b.total_marks FROM student a, marks b WHERE a.studentid =


b.studentid AND b.total_marks > (SELECT total_marks FROM marks WHERE studentid =
'V002');

Query result:

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Subqueries: General Rules
• A subquery SELECT statement is almost similar to the SELECT statement and it is used to begin a
regular or outer query. Here is the syntax of a subquery:
• Syntax:

(SELECT [DISTINCT] subquery_select_argument FROM {table_name | view_name} {table_name |


view_name} ... [WHERE search_conditions] [GROUP BY aggregate_expression [,
aggregate_expression] ...] [HAVING search_conditions])

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Subqueries: Guidelines
• There are some guidelines to consider when using subqueries :
• A subquery must be enclosed in parentheses. 
• A subquery must be placed on the right side of the comparison operator. 
• Subqueries cannot manipulate their results internally, therefore ORDER BY clause cannot be
added into a subquery. You can use an ORDER BY clause in the main SELECT statement (outer
query) which will be the last clause.
• Use single-row operators with single-row subqueries. 
• If a subquery (inner query) returns a null value to the outer query, the outer query will not return
any rows when using certain comparison operators in a WHERE clause.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Type of Subqueries

• Single row subquery : Returns zero or one row.


• Multiple row subquery : Returns one or more rows.
• Multiple column subqueries : Returns one or more columns.
• Correlated subqueries : Reference one or more columns in the outer SQL statement. The subquery
is known as a correlated subquery because the subquery is related to the outer SQL statement.
• Nested subqueries : Subqueries are placed within another subquery.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Nested subqueries

• A subquery can be nested inside other subqueries. SQL has an ability to nest queries within
one another. A subquery is a SELECT statement that is nested within another SELECT
statement and which return intermediate results. SQL executes innermost subquery first,
then next level.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
PL/SQL IN RDBMS

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
PL/SQL Introduction
PL/SQL is Oracle’s proprietary server based procedural extension to
the SQL language. In this, all the statements of a block are passed to
oracle engine all at once which increases processing speed and
decreases the traffic.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Features of PL/SQL:

• PL/SQL is tightly integrated with SQL.


• It offers extensive error checking.
• It offers numerous data types.
• It offers a variety of programming structures.
• It supports structured programming through functions and
procedures.
• It supports object-oriented programming.
• It supports the development of web applications and server pages.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Advantages of PL/SQL:

• PL/SQL allows sending an entire block of statements to the database at


one time. This reduces network traffic and provides high performance for
the applications.
• PL/SQL gives high productivity to programmers as it can query,
transform, and update data in a database.
• PL/SQL saves time on design and debugging by strong features, such as
exception handling, encapsulation, data hiding, and object-oriented data
types.
• Applications written in PL/SQL are fully portable.
• PL/SQL provides high security level.
• PL/SQL provides access to predefined SQL packages.
• PL/SQL provides support for Object-Oriented Programming.
• PL/SQL provides support for developing Web Applications and Server
Pages.
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
SQL vs PL/SQL:
SQL
• SQL statement is a single query that is used to perform DDL, DML, and DQL operations.
• It is declarative, that defines what needs to be done, rather than how things need to be done.
• Executed as a single statement.
• Mainly used to manipulate data.
PL/SQL
PL/SQL is a block of codes that used to write the entire program blocks/ procedure/ function, etc.
PL/SQL is procedural that defines how the things needs to be done.
Execute as a whole block.
Mainly used to create an application.
It is an extension of SQL, so it can contain SQL inside it.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Structure of PL/SQL Block:
The basic unit in PL/SQL is a block. All PL/SQL programs are made up of blocks, which can be
nested within each other.
Each block consists of three parts
o Declarations
o Executable commands
o Exception handling

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
• Declare section starts with DECLARE keyword in which variables, constants, records as cursors
can be declared which stores data temporarily. It basically consists definition of PL/SQL
identifiers. This part of the code is optional.
• Execution section starts with BEGIN and ends with END keyword. This is a mandatory section
and here the program logic is written to perform any task like loops and conditional statements. It
supports all DML commands, DDL commands and SQL*PLUS built-in functions as well.
• Exception section starts with EXCEPTION keyword. This section is optional which contains
statements that are executed when a run-time error occurs. Any exceptions can be handled in this
section.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
PL/SQL identifiers
There are several PL/SQL identifiers such as variables, constants, procedures, cursors, triggers etc.
By default, identifiers are not case-sensitive. So you can use integer or INTEGER to represent a numeric value. Reserved keyword as an
identifier. Identifiers can consist of alphanumeric characters with a maximum size of 30
Variables:
Like several other programming languages, variables in PL/SQL must be declared prior to its use. They should have a valid name and data type as
well. Syntax for declaration of variables
variable_name datatype [NOT NULL := value ];

SQL> SET SERVEROUTPUT ON;

SQL> DECLARE
var1 INTEGER;
var2 REAL;
var3 varchar2(20) ;

BEGIN
null;
END;
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output:
PL/SQL procedure successfully completed. Explanation:

• SET SERVEROUTPUT ON: It is used to display the buffer used by the dbms_output.
• var1 INTEGER : It is the declaration of variable, named var1 which is of integer type. There are many other data
types that can be used like float, int, real, smallint, long etc. It also supports variables used in SQL as well like
NUMBER(prec, scale), varchar, varchar2 etc.
• PL/SQL procedure successfully completed.: It is displayed when the code is compiled and executed successfully.
• Slash (/) after END;: The slash (/) tells the SQL*Plus to execute the block.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
1.1) INITIALISING VARIABLES:
The variables can also be initialised just like in other programming
languages. Let us see an example for the same:
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
var1 INTEGER := 2 ;
var3 varchar2(20) := 'I Love GeeksForGeeks' ;

BEGIN
null;

END;
/

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output:
PL/SQL procedure successfully completed. Explanation:
• Assignment operator (:=) : It is used to assign a value to a variable.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
2) Displaying Output:
The outputs are displayed by using DBMS_OUTPUT which is a built-in package that enables the user to display
output, debugging information, and send messages from PL/SQL blocks, subprograms, packages, and triggers.
Let us see an example to see how to display a message using PL/SQL :

SQL> SET SERVEROUTPUT ON;


SQL> DECLARE
var varchar2(40) := 'I love GeeksForGeeks' ;

BEGIN
dbms_output.put_line(var);

END;
/

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output:
• I love GeeksForGeeks PL/SQL procedure successfully completed.

Explanation:

dbms_output.put_line : This command is used to direct the PL/SQL output to a screen.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Using Comments:
Like in many other programming languages, in PL/SQL also, comments can be put within the code which has no effect in the
code. There are two syntaxes to create comments in PL/SQL :
• Single Line Comment: To create a single line comment , the symbol – – is used.
• Multi Line Comment: To create comments that span over several lines, the symbol /* and */ is used.
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE

-- I am a comment, so i will be ignored.


var varchar2(40) := 'I love GeeksForGeeks' ;

BEGIN
dbms_output.put_line(var);

END;
/

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output:
• I love GeeksForGeeks PL/SQL procedure successfully completed.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Taking input from user:
Just like in other programming languages, in PL/SQL also, we can take input from the user
and store it in a variable. Let us see an example to show how to take input from users in
PL/SQL:

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
SQL> SET SERVEROUTPUT ON;

SQL> DECLARE

-- taking input for variable a


a number := &a;

-- taking input for variable b


b varchar2(30) := &b;

BEGIN
null;

END;
/

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Output:
Enter value for a: 24
old 2: a number := &a;
new 2: a number := 24;
Enter value for b: 'GeeksForGeeks'
old 3: b varchar2(30) := &b;
new 3: b varchar2(30) := 'GeeksForGeeks';

PL/SQL procedure successfully completed.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
(***) Let us see an example on PL/SQL to
demonstrate all above concepts in one single block of code.
--PL/SQL code to print sum of two numbers taken from the user.
SQL> SET SERVEROUTPUT ON;

SQL> DECLARE

-- taking input for variable a


a integer := &a ;

-- taking input for variable b


b integer := &b ;
c integer ;

BEGIN
c := a + b ;
dbms_output.put_line('Sum of '||a||' and '||b||' is = '||c);

END;
/
SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
Enter value for a: 2
Enter value for b: 3
Sum of 2 and 3 is = 5

PL/SQL procedure successfully completed.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.
PL/SQL Execution Environment:
• The PL/SQL engine resides in the Oracle engine. The Oracle engine can process not only
single SQL statement but also block of many statements. The call to Oracle engine needs to
be made only once to execute any number of SQL statements if these SQL statements are
bundled inside a PL/SQL block.

SMART TRAINING RESOURCES INDIA PVT. LTD. © 2018 SMART Training Resources Pvt. Ltd.

You might also like