Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
43 views77 pages

Unit 2

DBMS UNIT 2, UNIT II

Uploaded by

Dead Man
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)
43 views77 pages

Unit 2

DBMS UNIT 2, UNIT II

Uploaded by

Dead Man
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/ 77

DataBaseManagementSystem 1

B.Tech. 5thSem.

AL/CS-502: Database Management System

Unit-2

Relational Model in DBMS

Relational model can represent as a table with column sand rows. Each row is known as a
tuple . Each table of the column has a name or attribute.
Domain: It contains a set of atomic values that an attribute can take.

Attribute : It contains the name of a column in a particular table. Each attribute Ai must
have a domain, dom(Ai).

Tuple; A tuple, also known as a record or row, is a basic unit of data in a relational
database management system (DBMS). A tuple represents a single instance of a relation, or
table, in the database. Each tuple contains a set of values, or attributes, that correspond to
the columns, or fields, of the relation.

Relational instance:In the relational database system,the relational instance is


represented by a finite set of tuples. Relation instances do not have duplicate tuples.

Relational schema:A relational schema contains the name of the relation and name
of all columns or attributes.
DataBaseManagementSystem 2

Relational key:In the relational key ,each row has one or more attributes. It can
identify the row in the relation uniquely.

Example: STUDENT Relation

NAME ROLL_N PHONE_NO ADDRESS AGE


O

Ram 14795 7305758992 Noida 24

Shyam 12839 9026288936 Delhi 35

Laxman 33289 8583287182 Gurugram 20

Mahesh 27857 7086819134 Ghaziabad 27

Ganesh 17282 90289i3988 Delhi 40

o In the given table, NAME,ROLL_NO,PHONE_NO,ADDRESS, and AGE are the


attributes.
o The instance of schema STUDENT has 5 tuples.
o t3=<Laxman,33289,8583287182,Gurugram,20>
DataBaseManagementSystem 3

Properties of Relations

• Name of the relation is distinct from all other relations.


• Each relation cell contains exactly one atomic (single) value.
• Each attribute contains a distinct name.
• Attribute domain has no significance.
• tuple has no duplicate value.
• Order of tuple can have a different sequence.
DataBaseManagementSystem 4

Structure of relational databases

The database and the database structure are defined in the installation process.
The structure of the database depends on whether the database is Oracle
Database, IBM® Db2®, or Microsoft SQL Server.

A database that can be perceived as a set of tables and manipulated in accordance


with the relational model of data. Each database includes:

• a set of system catalog tables that describe the logical and physical
structure of the data
• a configuration file containing the parameter values allocated for the
database
• a recovery log with ongoing transactions and achievable transactions
DataBaseManagementSystem 5

Domains

Introduction to Database Domain

The data type defined for a column in a database is called a database domain. This data type can either be
a built-in type (such as an integer or a string) or a custom type that defines data constraints.

To understand this more effectively, let's think like this :


A database schema has a set of attributes, also called columns or fields, that define the database. Each
attribute has a domain that specifies the types of values that can be used, as well as other information
such as data type, length, and values.
We will also take an example : Let's say that we have a table, that stores student records. Now, suppose
there is a column, or attribute to store the students' contact numbers. The column for contact numbers
should only expect numeric values, usually of the type INT, which is the domain for that attribute.
DataBaseManagementSystem 6

Relations

Relation is sometimes used to refer to a table in a relational


database but is more commonly used to describe the
relationships that can be created between those tables in a
relational database. In relational databases, a relationship exists
between two tables when one of them has a foreign key that
references the primary key of the other table.

This single fact allows relational databases to split and store data
in different tables, yet still link the disparate data items together.
It is one of the features that makes relational databases such
powerful and efficient stores of information.
Data Base Management System 1

SQL KEYS
Keys are one of the basic requirements of a relational database
model. It is widely used to identify the tuples (rows) uniquely in
the table. We also use keys to set up relations amongst various
columns and tables of a relational database.

Different Types of Database Keys

• Candidate Key

• Primary Key

• Super Key

• Alternate Key

• Foreign Key

• Composite Key
Data Base Management System 2

Candidate Key
• It is a minimal super key.

• It is a super key with no repeated data is called a candidate


key.

• The minimal set of attributes that can uniquely identify a


record.

• It must contain unique values.

• It can contain NULL values.

• Every table must have at least a single candidate key.

• A table can have multiple candidate keys but only one


primary key.

• The value of the Candidate Key is unique and may be null


for a tuple.
Data Base Management System 3

• There can be more than one candidate key in a


relationship.

• Example:

CREATE TABLE employee (

empno INTEGER NOT NULL PRIMARY KEY,

ss_no INTEGER NOT NULL UNIQUE,

ename CHAR (19),

sal NUMERIC (10, 2),

deptno INTEGER NOT NULL

);

You declare a column as a candidate key by using the


keyword UNIQUE. Precede the UNIQUE keyword with
the NOT NULL specification. Like a primary key, a
candidate key also uniquely identifies a row in a table.
Note that a table can have only one primary key, but can
have any number of candidate keys.
Data Base Management System 4
If you supply a duplicate value for a candidate key in
an INSERT or UPDATE operation, the operation returns an
error.

Primary Key

There can be more than one candidate key in relation out of which
one can be chosen as the primary key. For Example, STUD_NO, as
well as STUD_PHONE, are candidate keys for relation STUDENT but
STUD_NO can be chosen as the primary key (only one out of many
candidate keys).

• It is a unique key.

• It can identify only one tuple (a record) at a time.

• It has no duplicate values, it has unique values.

• It cannot be NULL.

Example:

STUDENT table -> Student(STUD_NO, SNAME,


ADDRESS, PHONE) , STUD_NO is a primary key
Data Base Management System 5

Super Key

The set of attributes that can uniquely identify a tuple is known as Super
Key. For Example, STUD_NO, (STUD_NO, STUD_NAME), etc. A super key is a
group of single or multiple keys that identifies rows in a table. It supports
NULL values.

• Adding zero or more attributes to the candidate key generates the super
key.

• A candidate key is a super key but vice versa is not true.

• Super Key values may also be NULL.

Example:

Consider the table shown above.


STUD_NO+PHONE is a super key.
Data Base Management System 6

Relation between Primary Key, Candidate Key, and Super Key

Alternate Key

The candidate key other than the primary key is called an alternate
key.

• All the keys which are not primary keys are called alternate keys.

• It is a secondary key.

• It contains two or more fields to identify two or more records.


Data Base Management System 7

Foreign Key

A FOREIGN KEY is a field (or collection of fields) in one table, that


refers to the PRIMARY KEY in another table.

The table with the foreign key is called the child table, and the
table with the primary key is called the referenced or parent table.

Look at the following two tables:


Data Base Management System 8

CREATE TABLE Orders

(
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

It may be worth noting that, unlike the Primary Key of any given relation,
Foreign Key can be NULL as well as may contain duplicate tuples i.e. it need
not follow uniqueness constraint. For Example, STUD_NO in the
STUDENT_COURSE relation is not unique. It has been repeated for the first
and third tuples. However, the STUD_NO in STUDENT relation is a primary
key and it needs to be always unique, and it cannot be null.
Data Base Management System 9

Relation between Primary Key and Foreign Key

Composite Key

Sometimes, a table might not have a single column/attribute that uniquely


identifies all the records of a table. To uniquely identify rows of a table, a
combination of two or more columns/attributes can be used. It still can give
duplicate values in rare cases. So, we need to find the optimal set of
attributes that can uniquely identify rows in a table.

• It acts as a primary key if there is no primary key in a table

• Two or more attributes are used together to make a composite key.

• Different combinations of attributes may give different accuracy in terms of


identifying the rows uniquely.

Example:

FULLNAME + DOB can be combined


together to access the details of a student.
Data Base Management System 10

Different Types of Keys

Integrity Constraints

1. Integrity constraints are the set of


predefined rules that are used to maintain
the quality of information
2. Integrity constraints ensure that the data
insertion, data updating, data deleting and
other processes have to be performed in
Data Base Management System 11

such a way that the data integrity is not


affected.
3. They act as guidelines ensuring that data in
the database remain accurate and
consistent. So, integrity constraints are used
to protect databases. The various types of
integrity constraints are

Types of Integrity Constraints:

• Domain Constraints

• Not-Null Constraints

• Entity integrity Constraints

• Key Constraints

• Primary Key Constrains

• Referential integrity constraints


Data Base Management System 12

Types of Integrity Constraints:

• Domain Constraints

• Not-Null Constraints

• Entity integrity Constraints

• Key Constraints

• Primary Key Constrains

• Referential integrity constraints

Domain Constraints

These are defined as the definition of valid set of


values for an attribute. The data type of domain
Data Base Management System 13

include string, char, time, integer, date, currency


etc. The value of the attribute must be available
in comparable domains.

Not-Null Constraints

It specifies that within a tuple, attributes overs


which not-null constraint is specified must not
contain any null value.

Example:

Let, the not-null constraint be specified on the


“Semester” attribute in the relation/table given
below, then the data entry of 4th tuple will
violate this integrity constraint, because the
Data Base Management System 14

“Semester” attribute in this tuple contains null


value. To make this database instance a legal
instance, its entry must not be allowed by
database management system.

Entity Integrity Constraints

Entity integrity constraints state that primary


key can never contain null value because
primary key is used to determine individual rows
in a relation uniquely, if primary key contains
null value then we cannot identify those rows. A
Data Base Management System 15

table can contain null value in it except primary


key field.

Example:

It is not allowed because it is containing primary


key as NULL value.

Key Constraints

Keys are the entity set that are used to identify


an entity within its entity set uniquely. An entity
set can contain multiple keys, but out of them
one key will be primary key. A primary key is
Data Base Management System 16

always unique, it does not contain any null value


in table.

Example:

Primary Key Constraints

It states that the primary key attributes are


required to be unique and not null. That is,
primary key attributes of a relation must not
have null values and primary key attributes of
two tuples must never be same. This constraint
is specified on database schema to the primary
key attributes to ensure that no two tuples are
same.
Data Base Management System 17

Example

Here, in the below example the Student_id is the


primary key attribute. The data entry of 4th
tuple violates the primary key constraint that is
specifies on the database schema and therefore
this instance of database is not a legal instance.

Referential integrity constraints

It can be specified between two tables. In case of


referential integrity constraints, if a Foreign key
in Table 1 refers to Primary key of Table 2 then
Data Base Management System 18

every value of the Foreign key in Table 1 must be


null or available in Table 2.

Example:

Here, in below example Block_No 22 entry is not


allowed because it is not present in 2nd table.
Data Base Management System 19
Data Base Management System 20
Data Base Management System 21

SQL

What is SQL?

SQL is a short-form of the structured query language, and it is pronounced as S-Q-


L or sometimes as See-Quell.
This database language is mainly designed for maintaining the data in relational
Data Base Management System 22
database management systems. It is a special tool used by data professionals for
handling structured data (data which is stored in the form of tables). It is also
designed for stream processing in RDBMS.

You can easily create and manipulate the database, access and modify the table
rows and columns, etc. This query language became the standard of ANSI in the
year of 1986 and ISO in the year of 1987.
If you want to get a job in the field of data science, then it is the most important
query language to learn. Big enterprises like Facebook, Instagram, and LinkedIn,
use SQL for storing the data in the back-end.

SQL (Structured Query Language) is used to perform operations on the records


stored in the database, such as updating records, inserting records, deleting
records, creating and modifying database tables, views, etc.
SQL is not a database system, but it is a query language.

Suppose you want to perform the queries of SQL language on the stored data in
the database. You are required to install any database management system in
your systems, for example, Oracle, MySQL, MongoDB, PostgreSQL, SQL Server,
DB2, etc.

Data definition language (DDL)


Data definition language (DDL) is a language that allows the user to define the
data and their relationship to other types of data.
Data Base Management System 23
Data Definition language statements work with the structure of the database table.
• Various data types used in defining columns in a database table
• Integrity and value constraints
• Viewing, modifying and removing a table structure
Data Base Management System 24

DDL Commands

The Data Definition Languages (DDL) Commands are as follows −


• Create − It is used to create a new table or a new database.
• Alter − It is used to alter or change the structure of the database table.
• Drop − It is used to delete a table, index, or views from the database.
• Truncate − It is used to delete the records or data from the table, but
its structure
remains as it is.
When you create a table, you have to specify the following −
• Table name.
• Name of each column.
• Data type of each column.
• Size of each column.

Data types

When a table is created, each column in the table is assigned a


data type. Some of the important data types are as follows −
• Varchar2
• Char
• Number
Data Base Management System 25

SQL CREATE TABLE Statement


A Table is a combination of rows and columns. For creating a table we have to
define the structure of a table by adding names to columns and providing data
type and size of data to be stored in columns.

Syntax:

CREATE table
table_name (

Column1 datatype
(size), column2
datatype (size),

columnN datatype(size)

);

Here table_name is name of the table, column is the name of column


Data Base Management System 26

SQL CREATE TABLE Example

Let us create a table to store data of Customers, so the table name is Customer, Columns are
Name, Country, age, phone, and so on.
CREATE TABLE Customer( CustomerID INT
PRIMARY KEY,
CustomerName VARCHAR(50), LastName
VARCHAR(50), Country VARCHAR(50),
Age int(2), Phone int(10)
);

Output:

SQL ALTER TABLE – ADD, DROP, MODIFY


The ALTER TABLE statement in SQL is used to add, remove, or modify columns in an existing
table. The ALTER TABLE statement is also used to add and remove various constraints on existing
tables.

ALTER TABLE ADD Column Statement in SQL

ADD is used to add columns to the existing table. Sometimes we may require to add additional
Data Base Management System 27
information, in that case, we do not require to create the whole database again, ADD
comes to our rescue.

ALTER TABLE ADD Column Statement Syntax:

ALTER TABLE table_name ADD (Columnname_1 datatype, Columnname_2


datatype, …Columnname_n datatype);

The following SQL adds an “Email” column to the “Students” table:

ALTER TABLE ADD Column Statement Example:

ALTER TABLE Students ADD Email


varchar(255);

ALTER TABLE DROP Column Statement


Data Base Management System 28
DROP COLUMN is used to drop columns in a table. Deleting the unwanted
columns from the table.

ALTER TABLE DROP Column Statement Syntax:

ALTER TABLE table_name


DROP COLUMN
column_name;

The following SQL drop an “Email” column to the “Students” table:

ALTER TABLE DROP Column Statement Example:

ALTER TABLE
Students DROP
COLUMN Email;

ALTER TABLE MODIFY Column Statement in SQL

It is used to modify the existing columns in a table. Multiple columns can also be
modified at once. *Syntax may vary slightly in different databases.

ALTER TABLE MODIFY Column Statement Syntax:


Data Base Management System 29
ALTER TABLE table_name

MODIFY column_name column_type;

ALTER TABLE MODIFY Column Statement


Syntax(SQL Server):

ALTER TABLE table_name

ALTER COLUMN column_name column_type;

ALTER TABLE MODIFY Column Statement


Example:

ALTER TABLE table_name


MODIFY COLUMN column_name datatype;

SQL ALTER TABLE Queries

Suppose there is a student database:

ROLL_N NAME
O
Data Base Management System 30

1 Ram

2 Abhi
Data Base Management System 31

ROLL_N NAME
O

3 Rahul

4 Tanu

To ADD 2 columns AGE and COURSE to table Student.

Query:

ALTER TABLE Student ADD


(AGE number(3),COURSE varchar(40));

Output:

ROLL_N NAME AG COURS


O E E

1 Ram

2 Abhi

3 Rahul

4 Tanu
Data Base Management System 32
MODIFY column COURSE in table Student.

Query:

ALTER TABLE Student


MODIFY COURSE
varchar(20);
After running the above query the maximum size of the Course Column is
reduced to 20 from 40.

DROP column COURSE in table Student.

Query:

ALTER TABLE Student


DROP COLUMN
COURSE;
Output:
Data Base Management System 33

ROLL_N NAME AG
O E

1 Ram

2 Abhi

3 Rahul

4 Tanu

SQL | DROP, TRUNCATE

DROP

DROP is used to delete a whole database or just a table.


In this article, we will be learning about the DROP statement which destroys
objects like an existing database, table, index, or view. A DROP statement in SQL
removes a component from a relational database management system (RDBMS).

Syntax:

DROP object object_name


Data Base Management System 34

Examples 1:

To Drop a table

DROP TABLE table_name;


table_name: Name of the table to be deleted.

Examples 2:

To Drop a database

DROP DATABASE database_name;


database_name: Name of the database to be deleted.

TRUNCATE

The major definition between TRUNCATE and DROP is that truncate is used to
delete the data inside the table not the whole table.
TRUNCATE statement is a Data Definition Language (DDL) operation that is used
to mark the extent of a table for deallocation (empty for reuse). The result of this
operation quickly
Data Base Management System 35
removes all data from a table, typically bypassing several integrity-enforcing
mechanisms. It was officially introduced in the SQL:2008 standard. The
TRUNCATE TABLE mytable statement is logically (though not physically) equivalent
to the DELETE FROM mytable statement (without a WHERE clause).

Syntax:

TRUNCATE TABLE table_name;

table_name: Name of the table to be


truncated. DATABASE name –
student_data

DROP vs TRUNCATE

• Truncate is normally ultra-fast and it’s ideal for deleting data from a
temporary table.
• Truncate preserves the structure of the table for future use, unlike drop
table where the table is deleted with its full structure.
• Table or Database deletion using a DROP statement cannot be rolled back,
so it must be used wisely.

To delete the whole database

Query:

DROP DATABASE student_data;


Data Base Management System 36
After running the above query whole database will be deleted.

To truncate the Student_details table from the student_data database.

Query:

TRUNCATE TABLE Student_details;


After running the above query Student_details table will be truncated, i.e, the
data will be deleted but the structure will remain in the memory for further
operations.

SQL | ALTER (RENAME)


Sometimes we may want to rename our table to give it a more relevant name.
For this purpose we can use ALTER TABLE to rename the name of table.
*Syntax may vary in different databases.

Syntax(Oracle,MySQL,MariaDB):

ALTER TABLE table_name


RENAME TO
new_table_name;
Data Base Management System 37
Columns can be also be given new name with the use of
ALTER TABLE. Syntax(MySQL, Oracle):

ALTER TABLE table_name

RENAME COLUMN old_name TO


new_name; Syntax(MariaDB):

ALTER TABLE table_name

CHANGE COLUMN old_name TO new_name;

Sample Table:

Student

ROLL_N NAME AG
O E

1 Ram 20

2 Abhi 21

3 Rahul 22

4 Tanu 19

QUERY:
Data Base Management System 38
• Change the name of column NAME to FIRST_NAME in table Student.

ALTER TABLE Student RENAME


COLUMN NAME TO FIRST_NAME;
OUTPUT:

ROLL_N FIRST_NAM AG
O E E

1 Ram 20
Data Base Management System 39

ROLL_N FIRST_NAM AG
O E E

2 Abhi 21

3 Rahul 22

4 Tanu 19

• Change the name of the table Student to Student_Details

ALTER TABLE Student RENAME


TO Student_Details; OUTPUT:

Student_Details

ROLL_N FIRST_NAM AG
O E E

1 Ram 20

2 Abhi 21

3 Rahul 22

4 Tanu 19
Data Base Management System 40

DQL (Data Query Language):


DQL statements are used for performing queries on the data within schema
objects. The purpose of the DQL Command is to get some schema relation
based on the query passed to it. We can define DQL as follows it is a component
of SQL statement that allows getting data from the database and imposing order
upon it. It includes the SELECT statement. This command allows getting the data
out of the database to perform operations with it. When a SELECT is fired against
a table or tables the result is compiled into a further temporary table, which is
displayed or perhaps received by the program i.e. a front-end.
Data Base Management System 41

SQL | SELECT Query


The SELECT Statement in SQL is used to retrieve or fetch data from a database.
We can fetch either the entire table or according to some specified rules. The
data returned is stored in a result table. This result table is also called the result
set. With the SELECT clause of a SELECT command statement, we specify the
columns that we want to be displayed in the query result and, optionally, which
column headings we prefer to see above the result table. The select clause is the
first clause and is one of the last clauses of the select statement that the
database server evaluates. The reason for this is that before we can determine
what to include in the final result set, we need to know all of the possible
columns that could be included in the final result set.

SELECT Statement in SQL


To fetch the entire table or all the fields in the table:

Syntax:

SELECT * FROM table_name;

— asterisks represent all attributes of the table

Query to fetch the fields ROLL_NO, NAME, AGE from the table Student:

Query:
Data Base Management System 42
SELECT ROLL_NO, NAME, AGE FROM Student;

To fetch all the fields from the table Student:


SELECT * FROM Student;

SELECT Statement with WHERE Clause


Suppose we want to see table values with specific conditions then Where Clause
is used with select statement.

Query:

SELECT CustomerName FROM Customer WHERE Age = '21';

DML (Data Manipulation Language):


The SQL commands that deals with the manipulation of data present in the
database belong to DML or Data Manipulation Language and this includes most
of the SQL statements. It is the component of the SQL statement that controls
access to data and to the database. Basically, DCL statements are grouped with
DML statements.
List of DML commands:
Data Base Management System 43
• INSERT : It is used to insert data into a table.
• UPDATE: It is used to update existing data within a table.
• DELETE : It is used to delete records from a database table.

SQL INSERT INTO Statement


The INSERT INTO statement of SQL is used to insert a new row/record in a
table. There are two ways of using the SQL INSERT INTO statement for inserting
rows.

SQL INSERT Query

1. Only Values

The first method is to specify only the value of data to be inserted without the
column names.

INSERT INTO Syntax:

INSERT INTO table_name VALUES (value1, value2,


value3) table_name: name of the table. value1,
value2 ;

value of first column, second column,… for the new record


Data Base Management System 44

Column Names And Values Both

In the second method we will specify both the columns which we want to fill
and their corresponding values as shown below:

Insert Data in Specified Columns – Syntax:

INSERT INTO table_name (column1, column2,


column3) VALUES ( value1, value2, value3);

table_name: name of the table.

column1: name of first column, second column


. value1, value2, value3 value of first column, second column,… for
the new record

Suppose there is a Student database and we want to add values.

ROLL_N NAME ADDRESS PHONE AG


O E

1 Ram Delhi xxxxxxxxxxxx 18


xx

2 RAMESH GURGAO xxxxxxxxxxxx 18


Data Base Management System 45
N xx
Data Base Management System 46

ROLL_N NAME ADDRESS PHONE AG


O E

3 SUJIT ROHTAK xxxxxxxxxxxx 20


xx

4 SURESH ROHTAK xxxxxxxxxxxx 18


xx

3 SUJIT ROHTAK xxxxxxxxxxxx 20


xx

2 RAMESH GURGAO xxxxxxxxxxxx 18


N xx

Method 1 (Inserting only values) – SQL INSERT Query

If we want to insert only values then we use the following query:

Query:

INSERT INTO Student


VALUES
('5','HARSH','WEST
BENGAL',
'XXXXXXXXXX','19');

Output:
Data Base Management System 47
The table Student will now look like this:

ROLL_N NAME ADDRESS PHONE Ag


O e

1 Ram Delhi XXXXXXXX 18


XX

2 RAMESH GURGAON XXXXXXXX 18


XX

3 SUJIT ROHTAK XXXXXXXX 20


XX

4 SURESH Delhi XXXXXXXX 18


XX

3 SUJIT ROHTAK XXXXXXXX 20


XX

2 RAMESH GURGAON XXXXXXXX 18


XX

5 HARSH WEST XXXXXXXX 19


BENGAL XX
Data Base Management System 48

Method 2 (Inserting values in only specified columns) – SQL INSERT INTO


Statement If we want to insert values in the specified columns then we
use the following query: Query:

INSERT INTO Student (ROLL_NO,


NAME, Age) VALUES
('5','PRATIK','19');

Output:

The table Student will now look like this:

ROLL_N NAME ADDRESS PHONE Age


O

1 Ram Delhi XXXXXXXXX 18


X

2 RAMESH GURGAO XXXXXXXXX 18


N X

3 SUJIT ROHTAK XXXXXXXXX 20


X

4 SURESH Delhi XXXXXXXXX 18


X

3 SUJIT ROHTAK XXXXXXXXX 20


X
Data Base Management System 49

2 RAMESH GURGAO XXXXXXXXX 18


N X

5 PRATIK null null 19

Notice that the columns for which the values are not provided are filled by null.
Which are the default values for those columns?

To insert multiple rows in a table using Single SQL Statement:

Syntax:

INSERT INTO
table_name(Column1,Column2,Column3,…….)
VALUES (Value1, Value2,Value3,…..),

(Value1, Value2,Value3,…..),
(Value1, Value2,Value3,…..),

……………………….. ;
Data Base Management System 50
Where,
• table_name: name of the table.
Column 1: name of the first column, second column.
• Values: Value1, Value2, Value3: the value of the first column, second column.
• For each new row inserted, you need To provide Multiple lists of values where
each list is separated by “,”. Every list of values corresponds to values to be
inserted in each new row of the table. Values in the next list tell values to be
inserted in the next Row of the table.

Example:

The following SQL statement inserts multiple rows in Student Table.

Query:

INSERT INTO STUDENT(ID, NAME,AGE,GRADE,CITY)


VALUES(1,"AMIT KUMAR",15,10,"DELHI"),
(2,"GAURI RAO",18,12,"BANGALORE"),
(3,"MANAV BHATT",17,11,"NEW DELHI"),
(4,"RIYA KAPOOR",10,5,"UDAIPUR");

Output:

Thus STUDENT Table will look like this:

ID NAME AG GRAD CIT


Data Base Management System 51
E E Y

1 AMIT KUMAR 15 10 DELHI

2 GAURI RAO 18 12 BANGALOR


E

3 MANAV 17 11 NEW DELHI


BHATT

4 RIYA KAPOOR 10 5 UDAIPUR

SQL | UPDATE Statement


The UPDATE statement in SQL is used to update the data of an existing table in
the database. We can update single columns as well as multiple columns using
the UPDATE statement as per our requirement.
In a very simple way, we can say that SQL commands (UPDATE and DELETE) are
used to change the data that is already in the database. The SQL DELETE
command uses a WHERE clause.

Syntax
Data Base Management System 52
UPDATE table_name SET column1 = value1, column2 =
value2,… WHERE condition;

table_name: name of the table

column1: name of first , second, third


column…. value1: new value for first, second,
third column…. condition: condition to select
the rows for which the values of columns needs
to be updated.

Parameter Explanation

1. UPDATE: Command is used to update the column value in the table.

2. WHERE: Specifies the condition which we want to implement on the table.

Note: In the above query the SET statement is used to set new values to the
particular column and the WHERE clause is used to select the rows for which the
columns are needed to be updated. If we have not used the WHERE clause then
the columns in all the rows will be updated. So the WHERE clause is used to
choose the particular rows.

Let’s see the SQL update statement with examples.

Query:
Data Base Management System 53
Update Single Column

Update the column NAME and set the value to ‘Nitin’ in the rows where the
Age is 22.
UPDATE Customer SET CustomerName
= 'Nitin' WHERE Age = 22;

Updating Multiple Columns

Update the columns NAME to ‘Satyam’ and Country to ‘USA’ where


CustomerID is 1.
UPDATE Customer SET CustomerName = 'Satyam',
Country = 'USA' WHERE CustomerID = 1;

SQL | DELETE Statement


Existing records in a table can be deleted using the SQL DELETE Statement. We
can delete a single record or multiple records depending on the condition we
specify in the WHERE clause. Syntax:
DELETE FROM table_name WHERE some_condition;

table_name: name of the table

Parameter Explanation
Data Base Management System 54
• Some_condition: condition to choose a particular record.
Data Base Management System 55
• DELETE FROM table_name(means we have to delete from table.
Note: We can delete single as well as multiple records depending on the condition
we provide in the WHERE clause. If we omit the WHERE clause then all of the records
will be deleted and the table will be empty.

Deleting Single Record

Delete the rows where NAME = ‘Rithvik’. This will delete only the fourth row.

Query:

DELETE FROM GFG_EMPLOyees WHERE NAME = 'Rithvik';

Deleting Multiple Records

Delete the rows from the table GFG_EMPLOyees where the department is
“Development”. This will delete 2 rows(the first row and the seventh row).

Query:

DELETE FROM GFG_EMPLOyees


WHERE department = 'Development';

Delete All of the Records


Data Base Management System 56
There are two queries to do this as shown below,

Query:

DELETE FROM GFG_EMPLOyees;

Or

DELETE * FROM GFG_EMPLOyees;

SQL JOINS

SQL JOIN

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

Let's look at a selection from the "Orders" table:


Data Base Management System 57
Then, look at a selection from the "Customers" table:

Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the

"Customers" table.

The relationship between the two tables above is the "CustomerID" column.

Then, we can create the following SQL statement (that contains an INNER JOIN), that selects records

that have matching values in both tables:


Data Base Management System 58

-- join operations in sql

-- INNER JOIN IN SQL

create table orders (OrderID int,CustomerID int,OrderDate date);

create table Customers (CustomerID int,CustomerName


VARCHAR(50),

ContactName VARCHAR(50),

Country VARCHAR(50));

INSERT INTO orders VALUES(12,8, '2023-07-12');


Data Base Management System 59
INSERT INTO Customers VALUES(2,'vinay','vinay','india');

select * from orders;

select * from Customers;

SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate

FROM

Orders

INNER JOIN

Customers

ON Orders.CustomerID=Customers.CustomerID;

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
Data Base Management System 60

• Look at this diagrame

• Queries

• SELECT Customers.CustomerName,Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

• RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from
the left table

• Look at the diagrame

• Quaries

SELECT Customers.CustomerName, Orders.OrderID

FROM Customers

right JOIN Orders ON Customers.CustomerID = Orders.CustomerID

ORDER BY Customers.CustomerName;
Data Base Management System 61
• FULL (OUTER) JOIN: Returns all records when there is a match in either left or right table

Relational Algebra
Relational algebra is a procedural query language. It gives a step by step process to obtain the result of
the query. It uses operators to perform queries.

Types of Relational operation

1. Select Operation:

o The select operation selects tuples that satisfy a given predicate.

o It is denoted by sigma (σ).

Notation: σ p(r)

Where:

σ is used for selection prediction

r is used for relation


Data Base Management System 62
p is used as a propositional logic formula which may use connectors like: AND OR and NOT. These
relational can use as relational operators like =, ≠, ≥, , ≤.

For example :LOAN Relation

BRANCH_NAME LOAN_NO AMOUNT

Downtown L-17 1000

Redwood L-23 2000

Perryride L-15 1500

Downtown L-14 1500

Mianus L-13 500

Roundhill L-11 900

Perryride L-16 1300

Input:

σBRANCH_NAME="perryride"(LOAN)
Output:

BRANCH_NAME LOAN_NO AMOUNT

Perryride L-15 1500

Perryride L-16 1300


Data Base Management System 63

1. ProjectOperation:
This operation shows the list of those attributes that we wish to appear in the result. Rest of the
attributes are eliminated from the table.
It is denotedby ∏.

Notation :
∏A1,A2,An(r) Where
A1, A2, A3 is used as an attribute name of relation r

NAME STREET CITY

Jones Main Harrison

Smith North Rye

Hays Main Harrison

Curry North Rye

Johnson Alma Brooklyn

Brooks Senator Brooklyn

Input:

∏NAME,CITY(CUSTOMER)

Output:
Data Base Management System 64

NAME CITY

Jones Harrison

Smith Rye

Hays Harrison

Curry Rye

Johnson Brooklyn

Brooks Brooklyn

1. Union Operation:

o Suppose there are two tuples R and S. The union operation contains all the tuples that are
either in R or S or both in R & S.
o It eliminates the duplicate tuples. It is denoted by ∪
o Notation: R ∪ S
A union operation must hold the following condition:
o R and S must have the attribute of the same number..

o Duplicate tuples are eliminated automatically.


o Example:
Data Base Management System 65
DEPOSITOR RELATION

CUSTOMER_NAME ACCOUNT_N
O

Johnson A-101

Smith A-121

Mayes A-321

Turner A-176

Johnson A-273

Jones A-472

Lindsay A-284

BORROW RELATION

CUSTOMER_NAME LOAN_NO

Jones L-17

Smith L-23

Hayes L-15

Jackson L-14

Curry L-93

Smith L-11

Williams L-17

Input:
Data Base Management System 66
∏CUSTOMER_NAME(BORROW) ∪ ∏CUSTOMER_NAME(DEPOSITOR)
Output:

CUSTOMER_NAM
E

Johnson

Smith

Hayes

Turner

Jones

Lindsay

Jackson

Curry

Williams

Mayes

1. Set Intersection:
o Suppose there are two tuples R and S. The set intersection operation contains all tuples that
are in both R & S.
It is denoted by intersection ∩.
Data Base Management System 67
Notation:R∩S
Example:Using the above DEPOSITOR table and BORROW table
Input:

∏CUSTOMER_NAME(BORROW) ∩ ∏CUSTOMER_NAME(DEPOSITOR)
Output:

CUSTOMER_NAME

Smith

Jones

1. Set Difference:
o Suppose there are two tuples R and S. The set intersection operation contains all tuples
that are in R but not in S.
o It is denoted by intersection
minus(-). Notation: R - S
Example:Using the above DEPOSITOR table and BORROW table
Input:

∏CUSTOMER_NAME(BORROW) - ∏CUSTOMER_NAME(DEPOSITOR)
Output:

CUSTOMER_NAM
E

Jackson

Hayes

Willians

Curry
Data Base Management System 68
1. Cartesian product

o The Cartesian product is used to combine each row in one table with each row in the
other table. It is also known as a cross product.
o It is denoted by
X.
o Notation: E X D

Example:
EMPLOYEE

EMP_ID EMP_NAME EMP_DEPT

1 Smith A

2 Harry C

3 John B

DEPARTMENT

DEPT_NO DEPT_NAME

A Marketing

B Sales

C Legal
Data Base Management System 69
Input:

1. EMPLOYEE X DEPARTMENT

Output:

EMP_ID EMP_NAME EMP_DEPT DEPT_NO DEPT_NAME

1 Smith A A Marketing

1 Smith A B Sales

1 Smith A C Legal

2 Harry C A Marketing

2 Harry C B Sales

2 Harry C C Legal

3 John B A Marketing

3 John B B Sales

3 John B C Legal

1. Rename Operation:
The rename operation is used to rename the output relation. It is denoted by rho (ρ). Example:
We can use the rename operator to rename STUDENT relation to STUDENT1. ρ(STUDENT1,
STUDENT).
Data Base Management System 70

Relational Calculus
1. Tuple Relational Calculus (TRC)
It is a non-procedural query language which is based on finding a number of tuple
variables also known as range variable for which predicate holds true.
A Query in the tuple relational calculus is expressed as following notation

{T | P (T)} or {T | Condition (T)}

T is the resulting tuples

P(T) is the condition used to fetch T.

For example:

{ T.name | Author(T) AND T.article = 'database' }

Output: This query selects the tuples from the AUTHOR relation. It returns a tuple with 'name' from Author
who has written an article on 'database'.

TRC (tuple relation calculus) can be quantified. In TRC, we can use Existential (∃) and Universal Quantifiers
(∀).

For example:

{ R| ∃T ∈ Authors(T.article='database' AND R.name=T.name)}

Output: This query will yield the same result as the previous one.

2. Domain Relational Calculus (DRC)


The second form of relation is known as Domain relational calculus. In domain relational calculus, filtering
variable uses the domain of attributes. Domain relational calculus uses the same operators as tuple
calculus. It uses logical connectives ∧ (and), ∨ (or) and ┓ (not). It uses Existential (∃) and Universal
Quantifiers (∀) to bind the variable. The QBE or Query by example is a query language related to domain
relational calculus.

Notation:

{ a1, a2, a3, ..., an | P (a1, a2, a3, ... ,an)}


Data Base Management System 71
a1, a2 are attributes
P stands for formula built by inner attributes

For example:

{< article, page, subject > | ∈ mysqldb ∧ subject = 'database'}

Output: This query will yield the article, page, and subject from the relational javatpoint, where the subject
is a database.

You might also like