0% found this document useful (0 votes)
23 views48 pages

23CS1303 Unit 2 DBMS R 2023 PDF

Unit II of the Database Management Systems course covers the relational database model, detailing concepts such as relations, schemas, keys, and integrity constraints. It introduces SQL for data definition and querying, along with relational algebra operations for manipulating data. Key types, including primary, foreign, and candidate keys, are explained, alongside the advantages of relational databases and examples of relational algebra operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views48 pages

23CS1303 Unit 2 DBMS R 2023 PDF

Unit II of the Database Management Systems course covers the relational database model, detailing concepts such as relations, schemas, keys, and integrity constraints. It introduces SQL for data definition and querying, along with relational algebra operations for manipulating data. Key types, including primary, foreign, and candidate keys, are explained, alongside the advantages of relational databases and examples of relational algebra operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 48

Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

UNIT – II RELATIONAL DATABASE

Relational Data Model - Concept of Relations, Schema-Instance distinction, Keys,


Referential integrity and Foreign keys, Relational algebra operators, SQL -
Introduction, Data Definition in SQL, Table, Key and Foreign key definitions,
Update behaviours. Querying in SQL, Notion of aggregation, Aggregation
functions Group by and Having clauses, Embedded SQL, Query Processing.

RELATIONAL DATA MODEL:


– The relational model uses a collection of tables to represent both data
and the relationships among those data. Each table has multiple columns,
and each column has a unique name. Tables are also known as relations.
The relational model is an example of a record-based model.
– Each record type defines a fixed number of fields, or attributes.
– The columns of the table correspond to the attributes of the record type.

Fig: Relation Student


Here, Data are organized in two-dimensional tables called relations.

❖ The tables are related to each other

❖ The term relation is used to refer to a table, while

❖ The term tuple is used to refer to a row.

❖ The term attribute refers to a column of a table.

❖ A set of permitted values, called the domain of that attribute.

1
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

❖ A domain is atomic if elements of the domain are considered to be

indivisible units. For example , Age, deptcode, deptname, SSN, phone


number, etc.

CONCEPT OF RELATIONS:
❖ Relation Schema: A relation schema represents the name of the

relation with its attributes.


A relation schema2 R, denoted by R(A1, A2, … , An), is made up of a
relation name R and a list of attributes, A1, A2, … , An

❖ Name – each relation in a relational database should have an unique

name among other relations.

❖ Attribute – each column in a relation. Each attribute Ai is the name of a

role played by some domain D in the relation schema R.


o The degree of the relation – the total number of attributes for a
relation.

❖ Tuple – each row in a relation.

❖ The cardinality of the relation – the total number of rows in a relation

❖ Relation instance – Relation instance is a finite set of tuples in the

RDBMS system. Relation instances never have duplicate tuples.

❖ Relation key - Every row has one, two or multiple attributes, which is

called relation key.

❖ Domain-D is called the domain of Ai and is denoted by dom(Ai).

❖ Attribute domain – Every attribute has some pre-defined value and

scope which is known as attribute domain.

2
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

❖ A relation instanceto refer to a specific instance of a relation, i.e.,

containing a specific set of rows.


Database Schema :
The logical design of the database is called database schema. For
example, The schema for that relation instructor as ,
instructor(ID,name,dept_name,salary)

● Database Instance :

It is defined as a snapshot of the data in the database at a given instant in time.


Application programs are programs that are used to interact with the database.

● Schema diagram :

A relation schema consists of a list of attributes and their corresponding


domains.
A schema diagram is a pictorial depiction of the schema of a database that
shows the relations in the database, their attributes, and primary keys and
foreign keys.

RELATIONAL INTEGRITY CONSTRAINTS & KEYS

3
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

- An integrity constraint is a mechanism used by oracle to prevent invalid data


entry into the table. It has enforcing the rules for the columns in a table. The
types of the integrity constraints are:
- Integrity constraints are specified on a database schema and are expected to
hold on every valid database state of that schema. In addition to domain, key,
and NOT NULL constraints, two other types of constraints are considered
part of the relational model: entity integrity and referential integrity.
- Relational Integrity constraints is referred to conditions which must be
present for a valid relation.
Three types of constraints
1. Domain constraints- Domain constraints can be violated if an
attribute value is not appearing .Eg. Not Null , Check
2. Key constraints (or ) Entity Integrity - An attribute that can
uniquely identify a tuple in a relation is called the key of the table . Eg.
Unique , Primary Key. The entity integrity constraint states that no
primary key value can be NULL.
3. Referential integrity constraints - A foreign key is an important
attribute of a relation which should be referred to in other
relationships. Eg. : Foreign Key , References Key.
The referential integrity constraint is specified between two relations
and is used to maintain the consistency among tuples in the two
relations.
Note :

The null value is a special value that signifies that the value is unknown or does
not exist.

4
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

A transactionis a collection of operations that performs a single logical


function in a database application.
Some popular Relational Database management systems(RDBSM) are:
● DB2 and Informix Dynamic Server - IBM

● Oracle and RDB – Oracle

● SQL Server and Access - Microsoft

Advantages :
● Simplicity: A relational data model is simpler than the hierarchical and
network model.
● Structural Independence: The relational database is only concerned with
data and not with a structure
● Easy to use

● Query capability: It makes possible for a high-level query language like


SQL.
● Data independence: The structure of a database can be changed without
having to change any application
● Scalable: Regarding a number of records, or rows, and the number of
fields, a database should be enlarged to enhance its usability.
KEY :
- Key plays an important role in relational database; An attribute that
can uniquely identify a tuple in a relation is called the key of the
table. It also establishes relationship among tables.
K⊆R
Non-key Attribute:
- The attributes (or column ) excluding the candidate keys are called as
non-key attributes(or column).

5
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

Types of keys ,
1. Primary Key
2. Super Key
3. Candidate Key
4. Composite / Compound Key
5. Foreign Key

❖ Super Key – A super key is a set of one of more columns (attributes) to

uniquely identify rows in a table.Super Key is a superset of Candidate key.


Example ,
Emp_SSN Emp_Number Emp_Name
12345678 226 Steve
9
567456236 225 John
The above table has following super keys. All of the following sets of super key
are able to uniquely identify a row of the employee table.
● { Emp_SSN }

● { Emp_Number }

● { Emp_SSN, Emp_Number }

● { Emp_SSN, Emp_Name }

● { Emp_SSN, Emp_Number, Emp_Name }

● { Emp_Number, Emp_Name }

❖ Candidate Key – A super key with no redundant attribute is known as

candidate key. Each Candidate Key can work as Primary Key. In short,
minimal superkeys are called candidate keys. Candidate key is a subset of
super key.
Example 1:
The candidate keys we have selected are:
● { Emp_SSN }

● { Emp_Number }

6
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

In the above example, we have not chosen { Emp_SSN, Emp_Name } as


candidate key because { Emp_SSN } alone can identify a unique row in the
table and Emp_Name is redundant.

Example 2:

Emp_id Emp_SSN Emp_name Email

101 363647 John [email protected]

105 467657 Peter [email protected]

104 567885 Rose [email protected]

103 568583 Kenny [email protected]

Set of Candidate Keys

● {Emp_id}

● {Emp_SSN}

● {Email}

❖ Primary Key -A primary key is a minimal set of attributes (columns) in a

table that uniquely identifies tuples (rows) in that table.


Example : Primary key, Unique key, Alternate key(all keys other than
primary key) are subset of Super Keys.
Create table STUDENT( Stu_Id number primary key,Stu_Name
varchar2(25) not null, Stu_Age number not null)

❖ Composite / Compound Key – A key that consists of more than one attribute

to uniquely identify rows (also known as records & tuples) in a table is called
composite key.
Example ,

7
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

Create table ORDER(Customer_ID number not null, Product_ID number


not null,Order_Quantity number not null, Primary key (Customer_ID,
Product_ID))

❖ Foreign Key – Foreign keys are the columns of a table that points to the

primary key of another table. They act as a cross-reference between tables.


Example ,
Department Table
CREATE TABLE Department (DeptID number PRIMARY KEY, Name
varchar2 (50) NOT NULL, Address varchar2(20) NOT NULL)

CREATE TABLE Department (DeptID number, Name varchar2 (50) NOT


NULL, Address varchar2(20) NOT NULL, constraint pk1 PRIMARY
KEY(DeptID) );

Student Table
CREATE TABLE Student (Studid number PRIMARY KEY,
RollNovarchar(10) NOT NULL,Name varchar2(50) NOT NULL, EnrollNo
number UNIQUE,Addressvarchar(200) NOT NULL, DeptID number
FOREIGN KEYREFERENCES Department(DeptID))

Sl.No. Super Key Candidate Key


1. It is the superset of all such It is the subset or the part of the Super
attributes that can uniquely key.
identify the table.
2. The super key attribute can be An attribute holding a candidate key
NULL, which means its values can never be NULL, which means its
can be null. values cannot be null.
3. It is not at all compulsory that all On the other hand, all candidate keys
super keys are candidate keys. are super keys.
4. More number of attributes forms Minimal number of attributes form
super key candidate key

Sl.No. Primary Key Foreign Key

8
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

1 Primary key uniquely identify a Foreign key is a field in the table that is
record in the table. primary key in another table.
2 Primary Key can't accept null Foreign key can accept multiple null
values. value.
3 We can have only one Primary We can have more than one foreign key
key in a table. in a table.
4 By default, Primary key is Foreign key do not automatically create
clustered index an index, clustered or non-clustered.

RELATIONAL ALGEBRA

▪ The relational algebra provides a set of operations that take one or

more relations as input and return a relation as an output.

▪ 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.

▪ The relational algebra defines a set of operations on relations.

The fundamental operations in the relational algebra are


Unary Operations -operate on one relation.

✔ Select

✔ Project

✔ Rename

Binary Operations - operate on pairs of relations

✔ Union

✔ Set difference

✔ Set intersection

✔ Cartesian product

Other Operations are ,

9
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

✔ Natural join, and

✔ Assignment.

The Select Operation :(σ)


The select operation selects tuples that satisfy a given predicate.It is denoted by
sigma (σ).
Syntax: σ p(r)
Where:
σ is used for selection prediction
r is used for relation
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 =, ≠,
≥, <, >, ≤.
Example 1 :Selects tuples from books where subject is 'database' and 'price'
is 450
σsubject = "database" and price = "450" (Books)
Example 2 :Selects tuples from books where subject is 'database' and 'price'
is 450 or those books published after 2010
σsubject = "database" and price = "450" or year > "2010" (Books)

The Project Operation :( ∏ )


Project operation is used to project only a certain set of attributes of a
relation.
It removes duplicate tuples, so the result is a set of tuples and hence a
valid relation.
Syntax: ∏A1, A2......An (r)
where A1, A2 etc are attribute names(column names),r is used for relation.
Example 1 :Selects and projects columns named as subject and author from
the relation Books.
∏subject, author (Books)
The Rename Operation:
To rename the attributes in a relation, we simply list the new attribures in
parathesis as in the following example.
TEMP<-- σDno=5(EMPLOYEE)
R(First_name,Last_name,Salary)<--πFName,Lname,Salary(TEMP)

10
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

SET OPERATORS:
The Union Operation (∪):
This operation is used to fetch data from two relations(tables) or temporary
relation(result of another operation).
Syntax: A∪B
where A and B are relations.
Note: For this operation to work, the relations(tables) specified should
have same number of attributes(columns) and same attribute
domain(i.e.data types).
Example:
Consider the relation SUPPLIER and PARTS,

Result:

The Intersection Operation ( ):


The intersection operation defines a relation consisting of the set of all tuples
that are in both of the given sets.
Syntax: A B

Result:

11
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

The Set-Difference Operation(- ) :


This operation is used to find data present in first relation and not present
in the second relation.

Syntax: A - B
where A and B are relations.

Example:

In a similar way, B-A is Given by,

The Cartesian Product ( X ) :


This type of operation is helpful to merge columns from two relations.
That is it combines the tuples of one relation with all the tuples of the other
relation.

Syntax: AX B

BINARY OPERATORS:
JOIN Operator(⋈ ) :
JOIN is used to combine related tuples from two relations.
Join operation is essentially a cartesian product followed by a selection criterion.
Natural Join( ⋈ )
Natural join can only be performed if there is a common attribute (column)
between the relations. The name and type of the attribute must be same. Such
12
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

joins result in two attributes in the resulting relation having exactly the same
value. A `natural join' will remove the duplicate attribute(s).

Example :
SELECTemp_no,emp_name,job_name,dep_name,location
FROMemp_mast
NATURALJOINdep_mast;
Output :
EMP_NO EMP_NAME JOB_NAME DEP_NAME LOCATION
---------- -------------------- ---------- ---------- ----------
1234 Alex Clerk FINANCE PARIS
2345 Jack Consultant MARKETING LONDON
3456 Paul Manager FINANCE PARIS
Example Database table:
Table Name :emp_mast
EMP_NO EMP_NAME JOB_NAME MGR_ID DEPT_NO
------------ -------------------- ----------------- ------------- ---------------
1234 Alex Clerk 4567 15
2345 Jack Consultant 3456 25
3456 Paul Manager 1234 15
4567 Jenefer Engineer 2345 45

Table Name :dep_mast


DEPT_NO DEP_NAME LOCATION
--------------- ----------------- -----------------
15 Finance Paris
25 Marketing London
35 Hr Delhi
Different Types of SQL JOINs :
❖ (INNER) JOIN: Returns records that have matching values in both tables.

Example :
SELECT emp_no,emp_name,job_name,dep_name,location
FROM emp_mastINNER JOINdep_mastUSING(dept_no);
Output :
EMP_NO EMP_NAME JOB_NAME DEP_NAME LOCATION
--------- ---------- ---------- ---------- --------
1234 Alex Clerk FINANCE PARIS
13
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

2345 Jack Consultant MARKETING LONDON


3456 Paul Manager FINANCE PARIS

Types of Inner Join:


● Equi join

● Non-Equi Join:
EQUIJOINS ( = ) :
An equijoin is a join with a join condition containing an equality operator.
This is represented by (=) sign. This join retrieves information by using equality
condition.
Example : Table Name : emp_mast

EMP_NO EMP_NAME JOB_NAME MGR_ID DEPT_NO


---------- -------------------- ----------------- ------------- ---------------
1234 Alex Clerk 4567 15
2345 Jack Consultant 3456 25
3456 Paul Manager 1234 15
4567 Jenefer Engineer 2345 45

Table Name :dep_mast

DEPT_NO DEP_NAME LOCATION


---------- ---------- ----------
15 FINANCE PARIS
25 MARKETING LONDON
35 HR DELHI

Example SQL :
SELECT emp_no,emp_name,job_name,dep_name FROM emp_maste, dep_mastd
WHERE e.dept_no=d.dept_no;
Output:

EMP_NO EMP_NAME JOB_NAME DEP_NAME


---------- -------------------- ----------------- ----------------
1234 Alex Clerk FINANCE
2345 Jack Consultant MARKETING
3456 Paul Manager FINANCE
NON-EQUI JOIN:
An nonequi join is an inner join statement that uses an unequal
operation (i.e.: <>, >, <, !=, BETWEEN, etc.) to match rows from different tables.

14
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

Example SQL :
SELECT emp_no,emp_name,job_name,dep_name FROM emp_maste, dep_mastd
WHERE e.dept_no>d.dept_no;
Output :
EMP_NO EMP_NAME JOB_NAME DEP_NAME
---------- -------------------- ---------- ----------
2345 Jack Consultant FINANCE
4567 Jenefer Engineer FINANCE
4567 Jenefer Engineer MARKETING
4567 Jenefer Engineer HR

OUTER JOINScan be used when we want to keep all the tuples in R, all those in S,
or all those in both relations regardless of whether they have matching tuples in
the other relation.
Relation Loan

Relation borrower

(i) Left Outer Join:


It takes all tuples in the left relation that did not match with any tuple in right
relation and pads the tuples with null value.
It is denoted by in R S
Notation: R S
Eg,

(ii) Right Outer Join:


Right outer join is denoted by R S. It pads the tuple in right relation that did
not match with any tuple from left relation with null value
Eg,

15
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

(iii) Full Outer Join:


A third operation, full outer join, denoted by keeps all tuples in both the left
and the right relations when no matching tuples are found, padding them with
null values as needed.
Eg,

Example:

(A ∩ B) (A ∩ B) U A

(A ∩ B) UB (A ∩ B) U(A–B)U (B–
A)

OTHER JOIN OPERATIONS:


SELF JOINS :

16
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

A self join is such a join in which a table is joined with itself. For example,
when you require details about an employee and his manager (also an
employee).

Example SQL :
SELECT a1.emp_no,a2.emp_name,a1.job_name,a2.dept_no
FROM emp_masta1,emp_mast a2
WHERE a1.emp_no=a2.mgr_id;
CROSS JOINS:
A Cross Join or Cartesian join or Cartesian product is a join of every row of
one table to every row of another table.
Example :
SELECT emp_no,emp_name,job_name,dep_name,location
FROM emp_mast CROSS JOIN dep_mast;

EMP_NO EMP_NAME JOB_NAME DEP_NAME LOCATION


---------- -------------------- ---------- ---------- ---------
1234 Alex Clerk FINANCE PARIS
2345 Jack Consultant FINANCE PARIS
3456 Paul Manager FINANCE PARIS
4567 Jenefer Engineer FINANCE PARIS
1234 Alex Clerk MARKETING LONDON
2345 Jack Consultant MARKETING LONDON
3456 Paul Manager MARKETING LONDON
4567 Jenefer Engineer MARKETING LONDON
1234 Alex Clerk HR DELHI
2345 Jack Consultant HR DELHI
3456 Paul Manager HR DELHI
4567 Jenefer Engineer HR DELHI

Summary :

Inner Join Inner join, includes only those tuples that satisfy the matching
criteria.

Theta Join(θ) The general case of JOIN operation is called a Theta join. It is
denoted by symbol θ.

17
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

EQUI Join ( = ) When a theta join uses only equivalence condition, it becomes
aequi join.

Eg. : SELECT emp_no,emp_name,job_name,dep_name FROM


emp_maste,dep_mastd WHERE e.dept_no = d.dept_no;

Natural Join(⋈) Natural join can only be performed if there is a common


attribute (column) between the relations.

Outer Join In an outer join, along with tuples that satisfy the matching
criteria.

Left Outer Join( ) In the left outer join, operation allows keeping all tuple in the
left relation.

Right Outer join( In the right outer join, operation allows keeping all tuple in the
) right relation.

Full Outer Join( ) In a full outer join, all tuples from both relations are included in
the result irrespective of the matching condition.

SQL INTRODUCTION
A query languageis a language in which a user requests information from
the database.
In general two types,

❖ Procedural language - The user instructs the system to perform a

sequence of operations on the database to compute the desired result.

❖ Nonprocedural language - The user describes the desired information

without giving a specific procedure for obtaining that information.


The relational query languages define a set of operations that operate on
tables, and output tables as their results. These operations can be combined to
get expressions that express desired queries.
Advantages of SQL:

18
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

● No coding needed

● Well defined standards

● Portability

● Interactive Language

● Multiple data views

Disadvantages of SQL
● Difficult Interface

● Partial Control

● Implementation

● Cost

Applications of SQL
● Data Integration Scripts

● Analytical Queries

● Retrieve Information

Basic Data Types:


Various Data Types :
1. Character Datatypes:

✔ Char – fixed length character string that can varies between

1-2000 bytes

✔ Varchar / Varchar2 – variable length character string, size

ranges from 1-4000 bytes.

✔ Long - variable length character string, maximum size is 2 GB

2. Number Datatypes :

✔ Number – {p=38,s=0}

19
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

✔ Number(p) - fixed point

✔ Number(p,s) –floating point (p=1 to 38,s= -84 to 127)

3. Date Datatype: used to store date and time in the table.

✔ DB uses its own format of storing in fixed

length of 7 bytes for century, date, month,


year, hour, minutes, and seconds.

✔ Default data type is “dd-mon-yy”

4. Raw Datatype: used to store byte oriented data like binary data
and byte string.
5. Other :

✔ CLOB – stores character object with single byte character.

✔ BLOB – stores large binary objects such as graphics, video,

sounds.

✔ BFILE – stores file pointers to the LOB’s.

DDL COMMANDS:
● DDL stands for Data Definition Language.

● It is a language used for defining and modifying the data and its structure.

20
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

All DDL commands are auto-committed. That means it saves all the
changes permanently in the database.
The commands used are:
✔ CREATE Table – Create a new Table, database, schema

✔ ALTER Table – Alter existing table, column description

✔ DROP Table – Delete existing objects from database

✔ TruncateTable – Delete all the records from table .

✔ Rename - To rename a table


The Create Table Command :
The create table command defines each column of the table uniquely. Each
column has minimum of three attributes.
● Name

● Data type
● Size(column width).
For example ,
Table Name : Student
Column name Data type Size
Reg_no varchar2 10
Name char 30
DOB date
Address varchar2 50
Command :
CREATE TABLE Student ( Reg_no number(10),Name char(30),DOB
date,Address varchar2(50));
Data Constraint :
✔ Oracle allows constraints for attaching in the table columns via SQL
syntax that checks data for integrity.
✔ The constraints is a rule which works into the table, it disallows the that
data which are not following the rule of data constraints.

INTEGRITY CONSTRAINT
An integrity constraint is a mechanism used by oracle to prevent invalid
data entry into the table. It has enforcing the rules for the columns in a table. The
types of the integrity constraints are:
a) Domain Integrity - Not Null , Check
b) Entity Integrity - Unique , Primary Key
c) Referential Integrity - Foreign Key , References Key
General Types of Data Constraints:

21
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

Input/output Constraints
1. The Primary key Constraint
2. The Foreign key Constraint
Business Rule Constraints
1. Check Constraint
2. Unique Constraint
3. NOT NULL Constraint
Primary key :
❖ A primary key is one or more column(s) in a table used to uniquely
identify each row in the table. A primary key column in a table has special
attributes :
❖ A primary key is the combination of (NOT NULL+UNIQUE) key constraints.

❖ A single column primary key is called Simple key. And a multicolumn


primary key is called a Compositeprimary key.
PRIMARY KEY constraint defined at the column level :
Syntax :
<col_name><datatype> (<size>) PRIMARY KEY
For example ,
CREATE TABLE Sales_Order(Order_no varchar2(6) PRIMARY KEY,Order_Date
date,Client_no varchar2(6),Dely_addr varchar2(25),Order_status varchar2(10));

PRIMARY KEY Constraint defined at the table level:


Syntax: ( Composite / Compound Key )
Primary key ( <col_name, <col_name>,)
Example:
CREATE TABLE sales_order_details(Detlorder_no varchar2(6),Product_no
varchar2(7),product_rate number(8,2), primary
key(Detlorder_no,Product_no));
Foreign key :
Foreign keys represents the relationships between tables. A foreign key is
a column(or group of columns) whose values are derived from the primary or
unique key of the some other tables.
The table in which the foreign key is defined is called a foreign table or
detail table. The table that defines the primary key or unique key and is
referenced by the foreign key is called primary table or master table.
Syntax:
<col_name><datatype> (<size>) REFERENCES <table_name> [(<col_name>)]
Example:
Create table sales_order_details(Detlorder_no varchar2(6), product_no
varchar2(6), product_rate number(8,2) ,foreign key(detlorder_no)
referencessales_order.order_no);

Principal of Foreign Key/References:


22
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

● If ON DELETE CASCADE option is set, a DELETE operation in the master


table will trigger a delete operation for corresponding records in all detail
table(Child table ) .
● It must be matching Data Type for both Primary key and Foreign key
attribute.
The CHECK constraint:
CHECK constraint must be specified as a logical expression that evaluates
either to TRUE or FALSE
Syntax:
<col_name><data_Type> (<size>) CHECK (<logical expression>)
Example :
CREATE TABLEClient_Master(client_no varchar2(6) CHECK
(client_nolike’c%’),
Name varchar2(20) CHECK (name=upper(name)),city varchar2(15) CHECK
(city IN(‘Allahabad’,’Lucknow’)));

Unique key :
The Unique key disallows the similar value in same column of a table.
Syntax :
<col_name><data_type> (<size>) UNIQUE
For Example,
CREATE TABLE Student(Reg_no varchar2(10) PRIMARY KEY,Name
varchar2(20),
Phone number(10) UNIQUE, Address varchar2(20) default ‘Chennai’, DOB date
Not Null , city varchar2(15) CHECK (country IN(‘india’,’America’)));
NULL Value :
A NULL value is different from a blank or a zero.
NOT NULL Constraint
When a column is defined as NOT NULL , then that column becomes a
mandatory column. it must be enter a value into that column.
For Example,
CREATE TABLE Student(Reg_no varchar2(10) PRIMARY KEY, Name
varchar2(30) NOT NULL, Phone number(10) UNIQUE,Address
varchar2(50)NOT NULL , DOB date);
Creating a Database:
create database database-name;
Example,
create database Test;

ALTER TABLE Command :


● An ALTER command allows to alter or modify the structure of the

database. By Using this add additional column, drop existing column and
even change the data type of columns
The general syntax :

23
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

ALTER TABLEtable_name ADD column_name (for adding a new


column)
ALTER TABLEtable_name RENAME To new_table_name (for renaming a
table)
ALTER TABLEtable_name MODIFY column_name data type (for
modifying a column)
ALTER TABLE table_name DROP COLUMN column_name (for deleting a
column)
Example :
ALTER TABLE Student MODIFY (Name Varchar2 (40));
Alter table student add (gpa number (2,3));
Alter table student modify (gpa number (3,3));
Alter Table student add constraint pkey1 primary key (reg_no);
Note:
Restriction on the ALTER TABLE :
Using the ALTER TABLE clause the following tasks cannot be performed.
● Change the name of the table

● Change the name of the column


●Decrease the size of a column if table data exists
DROP TABLE:
It will destroy the table and all data which will be recorded in it.
Syntax:
DROP TABLE <table_name>
Example:
DROP TABLE Student;
TRUNCATE TABLE :
Truncate statement to delete all the rows from table permanently .But this
command will not destroy the table's structure.
● This command is same as DELETE command, but TRUNCATE command
does not generate any rollback data.

Syntax:
TRUNCATE TABLE <Table_name>
Example:
TRUNCATE TABLE Student;
Rename :
The rename command is used to rename a table or object.
Syntax,
RENAME TABLE <old_name> TO <new_name>;
For Example ,
RENAME TABLE emp TO employee;

24
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

DML COMMAND :
Data Manipulation Language (DML) statements are used for managing
data in database. DML commands are not auto-committed. It means changes
made by DML command are not permanent to database, it can be rolled back.
✔ INSERT :used for inserting a data into a table.
✔ UPDATE :used to modify the records present in existing table.
✔ DELETE : used to delete some or all records from the existing table.
✔ SELECT : used to retrieve data from the database
INSERT command
Insert command is used to insert data into a table.
INSERT into table-name values(data1,data2,..)
For example ,
// Insert all field values
INSERT into Student values (102 , 'Alex' , null);
// Insert particular Field values
INSERT into Student(id,name) values(102,'Alex');
● UPDATE Statement:
- Used to modify or update an already existing row or rows of a table.
Updating Single column:
Syntax:
UPDATE “tablename” SET “column1” = [new value] WHERE
“condition”;
Consider the following table Store_information
store_name sales txn_date
------------------------------ ---------- --------- -------------------- ---
Los Angeles 1500 jan-05-1999
San Diego 250 jan-07-1999
Los Angeles 300 jan-08-1999
Boston 700 jan-08-1999

SQL> UPDATE store_information SET sales =500 WHERE store_name=


‘los angeles’ AND txn_date= ‘jan-08-1999’;
Result:
store_name sales txn_date
------------------------------ ---------- --------- -------------------- ---
Los Angeles 1500 jan-05-1999
San Diego 250 jan-07-1999
Los Angeles 500 jan-08-1999
Boston 700 jan-08-1999
Updating Multiple column:
UPDATE “table_name” SET column1= [value1], column2=[value2]
WHERE “condition”;

25
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

eg,
SQL> UPDATE store_information SET sales=600,txn_date= ‘jan-15
1999’ WHERE store_name= ‘San diego’;
Result:
store_name sales txn_date
------------------------------ ---------- --------- -------------------- ---
Los Angeles 1500 jan-05-1999
San Diego 600 jan-15 1999
Los Angeles 500 jan-08-1999
Boston 700 jan-08-1999

● DELETE Statement:
- Delete statement is used to remove records from the table.
Syntax:
DELETE FROM “table_name” WHERE “condition”;
SQL> DELETE FROM store_information WHERE store_name= ‘los
angeles’;
Result:
San Diego 600 jan-15 1999
Boston 700 jan-08-1999

Deletion Using SubQuery:


Consider table GeographyBelow ,
region_code Total_sales
East Boston
East Newyork
West Los angeles
West San diego

SQL>DELETE FROM store_information WHERE store_nameIN( SELECT


Total_sales FROM Geography WHERE region_code = ‘east’;
Result:
store_name sales txn_date
------------------------------ ---------- --------- -------------------- ---
Los Angeles 1500 jan-05-1999
San Diego 250 jan-07-1999
Los Angeles 300 jan-08-1999

SELECT STATEMENT:
● SELECT command is used to retrieve the specific data from the database.
● It returns a result set of records from one or more tables.
SELECT Command has many optional clauses are as stated below:
Clause Description

26
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

WHERE It specifies which rows to retrieve.


GROUP BY It is used to arrange the data into groups.
HAVING It selects among the groups defined by the GROUP BY clause.
ORDER BY It specifies an order in which to return the rows.
AS It provides an alias which can be used to temporarily rename tables
or columns.

Eg, consider the following STORE _INFORMATION table:


store_name sales txn_date
------------------------------ ---------- --------- -------------------- --------------------
Los Angeles 1500 jan-05-1999
San Diego 250 jan-07-1999
Los Angeles 300 jan-08-1999
Boston 700 jan-08-1999

SQL> SELECT “ Column-name FROM Table_name”;


There are three ways to retrieve data from table.
- Retrieve one column
- retrieve multiple columns
- retrieve all columns
Select one column:
SQL>SELECT store_name FROM store_information;
Result:
store_name
------------------------------ ---------- --------- -------------------- --------------------
Los Angeles
San Diego
Los Angeles
Boston
Select Multiple Columns:
To select sname and age from student relation, we use
SQL> SELECT Store_name, sales FROM store_information;
Result:
store_name sales
------------------------------ ----------
Los Angeles 1500
San Diego 250
Los Angeles 300
Boston 700
Select All columns:
2 ways are there to select all columns. One way is to list the column name of each
column and second way is to use * symbol.
SQL> SELECT * FROM store_information;
27
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

Result:
store_name sales txn_date
------------------------------ ---------- --------- -------------------- ---
Los Angeles 1500 jan-05-1999
San Diego 250 jan-07-1999
Los Angeles 300 jan-08-1999
Boston 700 jan-08-1999
Distinct:
SELECT keyword allows us to grab all information from a column(or columns) on
a table.
This necessarily means that there will be redundancies.
To select each distinct element, add DISTINCT after SELECT .(I,e) This keyword is
used along with select keyword to display unique values from the specified
column. It avoids duplicates during display.
Syntax:
SELECT DISTINCT “ column_name” FROM “table_name”;
SQL> SELECT DISTINCT store_name FROM store_information;
Result:
store_name
Los Angeles
San Diego
Boston
WHERE Clause:
WHERE Clause is used to filter the result based on ceratin conditions.
Syntax:
SELECT “ column_name” FROM “table_name” WHERE “ condition”;
To select all stores with sales above $1000 in table store_information,
SQL>SELECT store_name FROM store_information WHERE
sales>1000
Result:
store_name
Los Angeles

WHERE Clause with OR operator:


To view all the data with sales greater than $1000 or with transaction date of “
jan-08-1999”, use the SQL statement below.-
SELECT * FROM store_information WHERE sales>1000 OR txn_date =
“jan -08-1999”
Result:
store_name sales txn_date
------------------------------ ---------- --------- -------------------- ---
Los Angeles 1500 jan-05-1999
Los Angeles 300 jan-08-1999
Boston 700 jan-08-1999

WHERE Clause with And Or:

28
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

Compound conditions are made up of multiple simple conditions connected by


AND or OR.
Syntax:
SELECT “column_name” FROM “ table_name” WHERE “ simple
condition1”{[AND|OR] “Simple condition”};
SQL> SELECT store_name FROM store_information WHERE
sales>1000 OR (sales <500 AND sales >275);
Result:
store_name
Los angeles

IN Operator:
Syntax for using IN keyword is as follows,
SELECT “column_name” FROM “table_name” WHERE “ column_name”
IN (value1, value2..);

SQL> SELECT * FROM store_information WHERE store_name IN ( ‘ Los


Angeles’, San diego’);
Result:
store_name sales txn_date
------------------------------ ---------- --------- -------------------- ---
Los Angeles 1500 jan-05-1999
San Diego 250 jan-07-1999
Los Angeles 300 jan-08-1999

BETWEEN Operator:
In order to select data that is within a range of values, the between operator is
used. (AND should be included).
Syntax:
SELECT “ column_name “ FROM “ table_name” WHERE “column_name”
BETWEEN (‘value1, value 2’);
SQL> SELECT * FROM store_information WHERE txn_date BETWEEN
‘JAN-06-1999’ and ‘JAN-10-1999’
Result:
store_name sales txn_date
------------------------------ ---------- --------- -------------------- ---
San Diego 250 jan-07-1999
Los Angeles 300 jan-08-1999
Boston 700 jan-08-1999
We can also use BETWEEN operator to exclude a range of values by addingNOT
infront of BETWEEN.
SQL> SELECT * FROM store_information WHERE sales NOT BETWEEN 280
and 1000;
Result:
store_name sales txn_date
------------------------------ ---------- --------- -------------------- ---

29
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

Los Angeles 1500 jan-05-1999


San Diego 250 jan-07-1999
LIKE Predicate: (used for Patter match)
% (percentage) represents one or more elements
_ (underscore) represents exactly one element.
These two wildcards are used with LIKE keyword in SQL. LIKE is used to a search
based on pattern matching.
Syntax:
SELECT “column name” FROM “ table_name” WHERE “column_name”
LIKE {PATTERN};
SQL> SELECT * FROM TABLE store_information WHERE store_name
LIKE ‘%AN%’;

Result:
store_name sales txn_date
------------------------------ ---------- --------- -------------------- ---
Los Angeles 1500 jan-05-1999
San Diego 250 jan-07-1999
Los Angeles 300 jan-08-1999

ARITHMETIC Operation:
The select clause may also contain arithmetic expressions involving the
operators +,-,*, and / operating on constants or attributes of tuples.

SQL>SELECT store_name, sales + 10 FROM store_information;

Result:
store_name sales
------------------------------
Los Angeles 1510
San Diego 260
Los Angeles 310
Boston 710

CONCATENATION Operator :
This combines information from two or more columns in a sentence according to
the format specified.

Eg,
SQL> select Store_name || ' has got very good ' || ‘sales’ ||sales|| ' on ' ||
txn_date AS "REPORT" from store_information;

Result:
REPORT
-------------------------------------------------------------------
Los angeles has got very good sales 1500 on jan-05-1999

30
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

San Diego has got very good sales 250 on jan-07-1999


Los Angeles has got very good sales 300 on jan-08-1999
Boston has got very good sales 700 on jan-08-1999

AGGREGATE Functions:
Consider the following store_information table,
store_name sales txn_date
------------------------------ ---------- --------- -------------------- -
Los Angeles 1500 jan-05-1999
San Diego 300 jan-07-1999
Los Angeles 300 jan-08-1999
Boston 900 jan-08-1999

These functions operate on the multiset of values of a column of a relation, and


return a value.
avg: average value
min: minimum value
max: maximum value
sum: sum of values
count: number of values
AVERAGE:
SQL> SELECT AVG ( sales)result FROM store_information;
result
---------
750
MINIMUM:
SQL> SELECT MIN (sales) result FROM store_information;
result
--------------------
300
MAXIMUM:
SQL>SELECT MAX (sales) result FROM store_information;
result
--------------------
1500
SUM:
SQL> SELECT SUM (sales) result FROM store_information;
result
---------
3000
COUNT:
SQL> SELECT COUNT(sales) result FROM store_information;
result
---------
4
ORDER BY CLAUSE

31
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

The order by clause arranges the contents of the table in ascending order (by
default) or in descending order (if specified explicitly) according to the specified
column.
If both ASC and DESC are not specified, then default order is ASC.

SQL>SELECT store_name,sales, txn_date FROM store_information ORDER


BY sales DESC
Result:
store_name sales txn_date
------------------------------ ---------- --------- -------------------- ---
Los Angeles 1500 jan-05-1999
Boston 700 jan-08-1999
Los Angeles 300 jan-08-1999
San Diego 250 jan-07-1999

It is also possible to sort the result by using expression.


For eg, in the following table product_sales

prod_ID price units


---------------------------------------------------------------------------
1 10 9
2 15 4
3 25 3
SQL> SELECT prod_ID, price * units revenue FROM product_sales ORDER
BY price * units DESC;
Result:
Prod_ID revenue
1 90
3 75
2 60
GROUP BY CLAUSE:
This clause group rows based on distinct values that exists for specified columns.
Syntax:
SELECT “column_name1” , SUM( “column_name2”) FROM “table_name”
GROUP_BY “column_name1”;
Eg
SQL> SELECT store_name, SUM( sales) FROM store_information GROUP
BY store_name;
Result:
store_name (SUM) sales
------------------------------ ----------
Los Angeles 1800
San Diego 250
Boston 700
SELECT txn_date, SUM (sales) FROM store_information GROUP BY Txn_date;

32
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

Result:
txn_date (SUM) sales
--------- -------------------- ---
jan-05-1999 1500
jan-07-1999 250
jan-08-1999 1000

HAVING CLAUSE:
The having clause can be used in conjunction with the group by clause.
Having imposes a condition on the group by clause, which further filters the
groups created by the group by clause.
Syntax:
SELECT “column_name1”, Function(“column_name2”) FROM
“table_name” [GROUP_BY “column_name1”] HAVING (arithmetic
function conditions);
Eg,
SQL> SELECT store_name, SUM(sales) FROM store_information
GROUP_BY store_name HAVING SUM(sales)>1500;
Result:
store_name SUM(sales)
------------------------------ ----------
Los Angeles 1800
SUB QUERIES:
Subqueries can be placed in a number of SQL clauses, including the WHERE
clause, the HAVING clause, and the FROM clause.
The subquery is enclosed in parentheses.
The subquery is placed on the right side of the comparison condition.
Eg,
SQL>SELECT store_name, sales, txn_date FROMstore_information
WHERE txn_date> = ( SELECT txn_date FROM Store_information
WHERE store_name = ‘Los Angeles’);
Result:
store_name sales txn_date
------------------------------ ---------- --------- -------------------- ---
Los Angeles 1500 jan-05-1999
San Diego 250 jan-07-1999
San Francisco 300 jan-08-1999
Boston 700 jan-08-1999

Consider the following f-staff table below,


Note:
The SELECT statement in parentheses is the inner query or ‘subquery’. It
executes first, before the outer query.
TCL and DCL Commands
Transaction Control Language (TCL) :

33
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

Transaction control statements manage changes made by DML statements.


A transaction is a set of SQL statements which Oracle treats as a Single
Unit. i.e. all the statements should execute successfully or none of the statements
should execute.
TCL Commands are ,

✔ COMMIT : Make changes done in transaction permanent.

✔ ROLLBACK : Rollbacks the state of database to the last commit point.

✔ SAVEPOINT : Use to specify a point in transaction to which later you can

rollback.
COMMIT :
Commit command is used to permanently save any transaction into
database.
Syntax :
COMMIT [WORK] ;
For Example
SQL> insert into emp (empno,ename,sal) values (101,’Abid’,2300);
SQL> commit;
ROLLBACK :
To rollback the changes done in a transaction give rollback statement.
Rollback restore the state of the database to the last commit point.
Syntax :
Rollback to savepoint-name;
For example,
SQL> delete from emp;
SQL> rollback;
SAVEPOINT :
Specify a point in a transaction to which later you can roll back.
Syntax :
savepointsavepoint-name;
For Example,

34
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

SQL> insert into emp (empno,ename,sal) values (109,’Sami’,3000);


SQL>savepoint a;
SQL> insert into dept values (10,’Sales’,’Hyd’);
SQL>savepoint b;
SQL> insert into salgrade values (‘III’,9000,12000);
SQL> rollback to a;

Data Control Language(DCL) Command :


● DCL is used to control user access in a database.

● This command is related to the security issues.

1. GRANT
2. REVOKE
● It is used to grant or revoke access permissions from any database user.

GRANT Command :
● GRANT command gives user's access privileges to the database.

Syntax:
GRANT <privilege list> ON <relation name or view name> TO <user/role
list>;
Example,
GRANT ALL ON employee TO pec;
GRANT insert, update ON employee TO pec;

REVOKE command :
It is used to cancel previously granted or denied permissions.It revokes access
privileges for database objects previously granted to other users.
Syntax :
REVOKE <privilege list> ON <relation name or view name> FROM
<user name>;
Example :
REVOKEupdate ON employee from pec;

35
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

EMBEDDED SQL (or) STATIC SQL


- Embedded SQL is a powerful method that allows the integration of
high−level programming languages with database management systems
(DBMS). It acts as a bridge between applications and databases which
helps in data manipulation and communication.
- Various database management systems offer embedded SQL, giving
developers the freedom to select the one that best serves their
requirements.
- Popular DBMS that support Embedded SQL are Altibase, IBM Db2,
Microsoft SQL Server, Mimer SQL, Oracle Database, PostgreSQL, and SAP
Sybase.
- The SQL standard defines embeddings of SQL in a variety of programming
languages such as C, C++, Cobol, Pascal, Java, PL/I, and Fortran.

Host hanguage vs Embedded SQL:

⮚ A language in which SQL queries are embedded is referred to as a host

language, and the SQL structures permitted in the host language


constitute embedded SQL.

⮚ Programs written in the host language can use the embedded SQL

syntax to access and update data stored in a database.

⮚ An embedded SQL program must be processed by a special preprocessor

prior to compilation. The preprocessor replaces embedded SQL requests


with host-language declarations and procedure calls that allow runtime
execution of the database accesses. Then, the resulting program is
compiled by the host-language compiler. This is the main distinction
between embedded SQL and JDBC or ODBC.

⮚ Static or Embedded SQL are SQL statements in an application that do not

change at runtime.

Structure of embedded SQL:

36
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

1. Connection to DB:
The first step in using embedded SQL is establishing a connection to the
database. This is done using the CONNECT keyword, preceded by EXEC SQL to
indicate that it is a SQL statement.
Connect to the database :
EXEC SQL connect to oracle user PECIT using SIT;
EXEC SQL CONNECT db_name;

EXEC SQL statement is used to identify embedded SQL request to the


preprocessor
EXEC SQL <embedded SQL statement > ;

2. Declaration Section:
The declaration section is used to declare variables that will be used in SQL
queries and to capture the results of those queries.
Types of variables used in the host language are: Host Variable Declaration &
Indicator Variable Declaration.
Host Variable Declaration :
These are the variables of host language used to pass the value to the
query as well as to capture the values returned by the query. Variables of the
host language can be used within embedded SQL statements, but they must be
preceded by a colon(:) to distinguish them from SQL variables.

❖ To declare host variables within BEGIN DECLARE and END DECLARE

section.

❖ When host variables are used in a SQL query, it should be preceded by

colon ‘:’ to indicate that it is a host variable.

37
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

❖ It substitutes the value of host variable and compiles when using pre-

compiler compiles SQL code .


Method 1 : ( using C code with its data type )
EXEC SQL BEGIN DECLARE SECTION;
int ST_ID;
char ST_NAME [15];
char ADDR[20];
EXEC SQL END DECLARE SECTION;
Method 2:
We can allow the compiler to fetch the data type of column (ie. from
table) and assign it to the host variable. It is done using ‘BASED ON’ clause.

EXEC SQL BEGIN DECLARE SECTION;


BASED ON STUDENT.ST_ID sid;
BASED ON STUDENT.ST_NAME sname;
BASED ON STUDENT.ADDR saddress;
EXEC SQL ENDDECLARE SECTION;

Indicator Variable :
The indicator variable sets/gets NULL values to the column, it passes/ gets
different integer values(ie. 0-Correct value ,1- NULL Value , > 0 –
Trimmed(Original Length ) the Column , , -2 - Trimmed(Original Length is
unknown ))
Example :
EXEC SQL SELECT std_name INTO :sname INDICATOR :ind_sname
FROM student WHERE student_id =:std_id;

3. Execution Section :
This is the execution section, and it contains all the SQL queries and
statements prefixed by ‘EXEC SQL’.
Example:
EXEC SQL SELECT * FROM student WHERE student_id =:std_id;

38
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

EXEC SQL SELECT std_nameINTO :sname :ind_sname FROM student WHERE


student_id =:std_id;
INSERT INTO student (std_id, std_name) VALUES (:sid, :sname);
UPDATE student SET address = :std_addr WHERE std_id = :sid;

4. Error Handling Section:


Error handling is essential in embedded SQL. In embedded SQL, error handling is
based on the host language. In C programs, error handling is typically done using
labels and the WHENEVER statement. The WHENEVER statement is used to
define the action to be taken when a certain condition occurs. The condition can
be SQLWARNING, SQLERROR, or NOT FOUND. The action can be CONTINUE, DO
<function>, GOTO , or STOP.
EXEC SQL WHENEVER SQLWARNING DO display_warning();
EXEC SQL WHENEVER SQLERROR STOP;
EXEC SQL WHENEVER NOT FOUND GOTO lbl_no_records;

Advantages of Embedded SQL:


Ease of Database Usage
Security and authorization
Integration of Frontend and Backend
Error prevention
Disadvantages of Embedded SQL:
Knowledge of the Host Language Required
Complex Development Model
Limited SQL Flexibility

DYNAMIC SQL

⮚ Dynamic SQL allows the program to construct an SQL query as a

character string at runtime, submit the query, and then retrieve the
result into program variables a tuple at a time.

⮚ The dynamic SQL component of SQL allows programs to construct and

submit SQL queries at runtime.

⮚ Dynamic SQL queries are prepared at program execution time, not

compilation time. This means that the compiler cannot check for errors

39
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

at compilation time and preprocessor macros cannot be used within


Dynamic SQL.

⮚ Dynamic SQL can issue a CREATE TABLE or CREATE VIEW and

perform an INSERT or SELECT on that table or view at runtime.

Schema diagram for the university database,

40
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

2 : Schema for Airline Reservation System:

*****************

PART A:

1. Explain the basic structure of a relational database with an example.


[April/May ‘2010]
- Relational databases store data in the form of tables (logically).
- The rows of a table are called as tuples.
- The columns of a table are known as attributes.
- Tables are called as relations.

41
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

- For eg, EMPLOYEE_ID,FIRST_NAME, LAST_NAME,DEPARTMENT_ID are


attributes.

2. What are the primary key constraints [April/May’13]


- It is a candidate key that is chosen by the database designer as the principal
means of identifying entities within an entity set.
- For Example Roll_no is primary key of student Entity set.
- The primary key should be chosen such that its attributes are never or rarely
changed.
3. Distinguish the term primary key and super key.[Nov/Dec’12]
[May/Jun’14] [April/May'17]
Primary key: A primary key is a column (or columns) in a table that uniquely
identifies the rows in that table.
✔ Should choose an attribute whose value never, or very rarely, changes.

✔ The values placed in primary key columns must be unique for each row.

✔ E.g. email address, Employee_ID


Super Key:
A Super Key is an attribute or set of attributes that uniquely identify an entity in
the entity set.
Example:
{customer_name, customer_street} and
{customer_name} are both superkeys of Customer, when no two customers can
possibly have the same name.

4. List out various relational algebra operators.[Nov/Dec’10]/Mention the


unary operators in relational algebra with example[Nov/Dec 2023]
The relational algebra is a collection of operators that take relations as their
operands and return a relation as their result.
It uses operators to perform queries. An operator can be
either unary or binary.
Traditional Operators from set theory
▪UNION

▪INTERSECTION

▪DIFFERENCE

42
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

▪CARTESIAN PRODUCT
Unary relational operators
▪SELECT

▪PROJECT
Binary Relational Operator
▪JOIN

▪DIVIDE

5. What are the four major categories of constraints. [Nov/Dec’10] / What are
the Different Types of Keys in Database [June 2021]
SuperKey, Candidate Key, Primary Key, Foreign Key

6. Define SQL. Name the categories of SQL Commands. [May/June ‘16]


- SQL is a standardized query language for requesting information from
a database.
- All relational database management systems like MySQL, MS access, Oracle,
Sybase, postgres, SQL Server uses standard database language called SQL.
- The DBMS processes the SQL request, retrieves the requested data from the
Database, and returns it.
- The process of requesting data from a database and receiving back the
results is called a db query and hence the name Structured Query Language.
Categories of SQL are,
DDL,DML,DCL,TCL

7. Why does SQL allows duplicate tuples in a table or in query result.?


[Nov/Dec’15]
▪Because database tables store data that are found in the real world,and real
world entities have duplicates and triplicates and so on. So if two people
have same name,age,sex,nationality, they will be stored as duplicates in the
table, distinguished maybe, by some kind of a distinct ID field.
▪So in short, tables allow duplicates because duplicates occur in nature.

▪You can add DISTINCT to avoid duplicates. Duplicated rows in tables can be
restricted with UNIQUE keys.
8. Define DDL,DML,TCL and DCL [May/June’15]/ Data Definition Language:
(DDL) [Nov/Dec’16] Data Definition Language: (DDL) [Nov/Dec’16]
- DDL statements are used to create, change, and remove data structures from the
database.
43
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

9. Define DML[May/June’15]
A data manipulation language(DML) used for Selecting , inserting, deleting
and updating data in a database.
Used for managing 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.

10. Define DCL [Nov/Dec’14][May/June’15]


Data control language(DCL)
Data control language controls the user access to the database objects.
- DCL commands are used to enforce database security in a multiple user
database environment. Only Database Administrator's or owner's of the
database object can provide/remove privileges on a database object.
- It is used to create roles, permissions, and referential integrity as well it is
used to control access to database by securing it.
o GRANT - gives user's access privileges to database
o REVOKE - withdraw access privileges given with the GRANT command

11. Define TCL.[May/June’15]


▪Transactional Control Language ( TCL)

▪TCL is abbreviation of Transactional Control Language. It is used to manage


different transactions occurring within a database.
▪Transactions are a fundamental concept of all database systems.

▪Transactions allow users to make changes to data and then decide whether to
save or discard the work
- COMMIT
- ROLLBACK

44
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

- SAVEPOINT

12. List the Set Operations of SQL.


Union, Union All, Intersect , Minus (difference)

13. What are aggregate Functions? List the aggregate functions used in
SQL.?
AVG() - Returns the average value
COUNT() - Returns the number of rows
FIRST() - Returns the first value
LAST() - Returns the last value
MAX() - Returns the largest value
MIN() - Returns the smallest value
SUM() - Returns the sum

14. What is Embedded SQL? [April/May '11]


- In Embedded SQL, Database statements are embedded into host
programming language .
- They are identified using special prefix called EXEC SQL.
- This EXEC string precedes all SQL commands in a host language program.
- A Precompiler or Preprocessor scans the source program code to identify
database statements and extract them for processing by DBMS.
- They are replaced by in the program by function calls to the DBMS generated
code. This technique is called Embedded SQL

15. Give the Schema Structure for Airline Reservation System.


+----------------+ +----------------+ +-----------------+
| Passengers | | Flights | | Reservations |
+----------------+ +----------------+ +-----------------+
| PassengerID (PK)| | FlightID (PK) | | ReservationID |
| FirstName | | FlightNumber | | PassengerID (FK)|
| LastName | | DepartureAirport| | FlightID (FK) |
| Email | | ArrivalAirport | | ReservationDate |
| Phone | | DepartureDateTime| | SeatNumber |
+----------------+ | ArrivalDateTime| | Status |
| AvailableSeats |
| TicketPrice |
+-----------------+

+----------------+ +----------------+
| Users | | Payments |
+----------------+ +----------------+
| UserID (PK) | | PaymentID (PK) |

45
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

| Username | | ReservationID (FK)|


| Password | | PaymentDate |
| UserType | | Amount |
+----------------+ | PaymentStatus |
+----------------+

16. Database relation Loan_records is given below:


Loan_records(borrower,bank_manager,loan_amount)
What is the output of following SQL query? [Nov/Dec 2023]
select count(*) from ((select borrower, bank_manager from
loan_records)as S natural join (select bank_manager,loan_amount from
loan_records)as T);

soln: eg,
| borrower | bank_manager | loan_amount |
|---------- |------------- -|-------------|
Alice John 5000
Bob Mary 7000
Charlie John 8000
David Mary 6000

Natural Join:
| borrower | bank_manager | loan_amount | bank_manager | loan_amount |
--------- -------------- ----------------------------------------
Alice John 5000 John 8000
Bob Mary 7000 Mary 6000

Output:
2

PART B:

1. Differentiate between foreign key constraints and referential integrity


constraints with suitable example. (6) [Nov/Dec’17]
2. State and Explain the command DDL,DML,DCL with suitable Example.
[Nov/Dec’17]/ Explain about SQL Fundamentals [May/June ‘16]
3. Justify the need of embedded SQL. Consider the relation student (stud_no,
name,mark,grade). Write embedded dynamic SQL statements in C language
to retrieve all students records whose marks is more than 90.
[Nov/Dec’17]

46
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

4. Explain using queries How a SQL relation can be defined using various
constraints? Also, Explain Other Data Definition Language Statements in
Detail
5. Explain about DDL (8) DML(4) EMBEDDED SQL (8) [May/Jun‘16]
[Nov/Dec’14]
6. Describe six clauses in SQL Query and show what type of constructs can be
specified in each of the six clauses. [Nov/Dec’15]
7. Explain select, project and Cartesian product operations in relational
algebra with an example. [Nov/Dec’16]/List the operations of relational
algebra and purpose of each with example. [April/May'17]
8. Explain Embedded SQL In detail./What is embedded SQL.Give Example.
[Nov/Dec'16]/Justify the need for embedded SQL. Consider the relation
student (Regno,name,mark and grade).Write embedded dynamic SQL
program in C language to retrieve all the students records whose mark is
more than 90. [April/May'17]
9. What are the several parts of SQL query language ? What are the basic built
in types used during SQL create statement? State and given example for the
basic structure of SQL queries? [June 2021]
10. Consider the following relations and write the queries using SQL and
Relational Algebra:[ Nov/Dec 2023]
Student(rollno,name,deptid,gender,advisor)
Course(courseid,cname,deptid,credits)
Enrollment(rollno,courseid,grade)
Faculty(empid,name,doj,deptid,salary)
Teaching(empid,courseid)
Department(deptid,name,hod)
1. Retrieve the student's name who have not registered for DBMS and DAA.
2. Retrieve the faculty name and course name who are teaching ECE courses
with 3 credits
3. Retrieve the students name registered for ECE and CSE courses
4. Retrieve the faculty details who are handling more than one course.
Soln:
1. SELECT DISTINCT s.name FROM Student s WHERE s.rollno NOT IN
( SELECT e.rollno FROM Enrollment e WHERE e.courseid IN ('DBMS', 'DAA')
);
2. SELECT f.name AS faculty_name, c.cname AS course_name FROM Faculty f
JOIN Teaching t ON f.empid = t.empid JOIN Course c ON t.courseid =
c.courseid WHERE c.deptid = 'ECE' AND c.credits = 3;
3. SELECT DISTINCT s.name FROM Student s JOIN Enrollment e ON s.rollno =
e.rollno JOIN Course c ON e.courseid = c.courseid WHERE c.deptid IN ('ECE',
'CSE');
4. SELECT f.* FROM Faculty f JOIN Teaching t ON f.empid = t.empid
GROUP BY f.empid HAVING COUNT(t.courseid) > 1;

47
Unit – II 23CS1303 DATABASE MANAGEMENT SYSTEMS PEC/IT

PART C

1. Write DDL, DML, DCL commands for the student database which contains
student details : name , id, DOB, branch, DOJ and Course details:
Coursename, Stud_id, Faculty_name, id, Marks [Nov/Dec’17]
2. Consider the relation schema givenbelow, design and draw an ER diagram
that capture the information of this scheme.
Employee(empno,name,office,age)
Books(isbn,title,authors,publisher)
Loan(empno,isbn,date)
Write the following queries in relational algebra and SQL.
(i) Find the names of employees who have borrowed a book published by
McGraw-Hill
(ii) Find the names of employees who have borrowed all books published
by McGraw -Hill [April/May'17]

48

You might also like