0% found this document useful (0 votes)
3 views

iunit-dbms-notes

Good

Uploaded by

adi637963
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

iunit-dbms-notes

Good

Uploaded by

adi637963
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

lOMoARcPSD|41692702

IUnit DBMS Notes

database management system (Vel Tech Multi Tech Dr. Rangarajan Dr. Sakunthala
Engineering College)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Adithya K ([email protected])
lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

UNIT I : RELATIONAL DATABASES


Purpose of Database System – Views of data – Data Models – Database System
Architecture – Introduction to relational databases – Relational Model – Keys –
Relational Algebra – SQL fundamentals – Advanced SQL - features – Embedded SQL–
Dynamic SQL

1. INTRODUCTION TO DATABASE

➢ Database is collection of data which is related by some aspect. Data is collection of facts
and figures which can be processed to produce information. Mostly data represents
recordable facts.
➢ DBMS consists of a collection of interrelated data and a set of programs to access those
datas.
➢ Data aids in producing information which is based on facts.
➢ A database management system stores data, in such a way which is easier to retrieve,
manipulate and helps to produce information.
➢ So a database is a collection of related data that we can use for
o Defining - specifying types of data
o Constructing - storing & populating.
o Manipulating - querying, updating, reporting.
➢ A DBMS is a collection of software programs that allows a user to define datatypes,
structures, constraints, store data permanently, modify and delete operations.
➢ DBMS is basically a software used to add, modify, delete, select data from database.
➢ In simpler words, DBMS is a collection of interrelated data and software programs to
access those data.
DISADVANTAGES OF FILE SYSTEM OVER DB
➢ In the early days, File-Processing system is used to store records. It uses various files for
storing the records.
➢ Drawbacks of using file systems to store data:
o Data redundancy and inconsistency
o Multiple file formats, duplication of information in different files
o Difficulty in accessing data
o Need to write a new program to carry out each new task
o Data isolation 4 multiple files and formats
o Integrity problems- Hard to add new constraints or change existing ones
o Atomicity problem
o Failures may leave database in an inconsistent state with partial updates carried
Out. E.g. transfer of funds from one account to another should either complete or
not happen at all
o Concurrent access anomalies -Concurrent accessed needed for performance
o Security problems
➢ Database systems offer solutions to all the above problems

2. PURPOSE OF DATABASE SYSTEM

➢ The typical file processing system is supported by a conventional operating system. The

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

➢ system stores permanent records in various files, and it needs different application
programs to extract records from, and add records to, the appropriate files.
➢ A file processing system has a number of major disadvantages.
✓ Data redundancy and inconsistency
✓ Difficulty in accessing data
✓ Data isolation 3 multiple files and formats
✓ Integrity problems
✓ Atomicity of updates
✓ Concurrent access by multiple users
✓ Security problems
1. Data redundancy and inconsistency: In file processing, every user group maintains its own
files for handling its data processing applications.
2. Difficulty in accessing data:File processing environments do not allow needed data to be
retrieved in a convenient and efficient manner.
3. Data isolation :Because data are scattered in various files, and files may be in different
formats, writing new application programs to retrieve the appropriate data is difficult.
4. Integrity problems:The data values stored in the database must satisfy certain types of
consistency constraints. Example: The balance of certain types of bank accounts may never fall
below a prescribed amount . Developers enforce these constraints in the system by addition
appropriate code in the various application programs
5. Atomicity problems: Atomic means the transaction must happen in its entirety or not at all. It
is difficult to ensure atomicity in a conventional file processing system. Example: Consider a
program to transfer $50 from account A to account B. If a system failure occurs during the
execution of the program, it is possible that the $50 was removed from account A but was not
credited to account B, resulting in an inconsistent database state.
6. Concurrent access anomalies: For the sake of overall performance of the system and faster
response, many systems allow multiple users to update the data simultaneously. In such an
environment, interaction of concurrent updates is possible and may result in inconsistent data.
To guard against this possibility, the system must maintain some form of supervision. But
supervision is difficult to provide because data may be accessed by many different application
programs that have not been coordinated previously.
Example: When several reservation clerks try to assign a seat on an airline flight, the system
should ensure that each seat can be accessed by only one clerk at a time for assignment to a
passenger.
7. Security problems: Enforcing security constraints to the file processing system is difficult.

APPLICATION OF DATABASE
➢ Database Applications

o Banking: all transactions


o Airlines: reservations, schedules
o Universities: registration, grades
o Sales: customers, products, purchases
o Manufacturing: production, inventory, orders, supply chain
o Human resources: employee records, salaries, tax deductions
o Telecommunication: Call History, Billing

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

o Credit card transactions: Purchase details, Statements


3. VIEWS OF DATA

➢ It refers that how database is actually stored in database, what data and structure of data
used by database for data. So describe all this database provides user with views and
these are
o Data abstraction
o Instances and schemas

Data abstraction:
➢ As a data in database are stored with very complex data structure so when user come and
want to access any data, he will not be able to access data if he has go through this data
structure.
➢ So to simplify the interaction of user and database, DBMS hides some information which
is not of user interest, this is called data abstraction.So developer hides complexity from
user and store abstract view of data.
➢ Data abstraction has three level of abstractions

➢ Physical level / internal level


➢ Logical level / conceptual level
➢ View level / external level

Physical level: This is the lowest level of data abstraction which describe How data is actual
stored in database. This level basically describe the data structure and access path /indexing use
for accessing file.
Logical level: The next level of abstraction describe what data are stored in the database and
what are the relationship existed among those of data.
View level: In this level user only interact with database and the complexity remain unview user
see data and there may be many views of one data like chart and graph.

Instances and schemas:


➢ Schema is the overall description of the data base. The basic structure of how the data
will be stored in the DB is called Schema.
➢ Instances are the collection of information stored at a particular moment.

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

4. DATA MODELS IN DBMS

✓ A Data Model is a logical structure of Database. It describes the design of database to


reflect entities, attributes, relationship among data, constrains etc.
✓ This is the basic structure of the database that organizes the data, defines how the data are
stored, accessed and the relationships between the data. Types of Data Models:
✓ Types of Data models:

• Hierarchial Data Model:

• Network Model:

• Relational Model:

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

• Entity relationship model

• Object Oriented Model:

• Object Relational model:


• It combines the feature of relational model and object oriented model.

5. DBMS ARCHITECTURE
• DBMS architecture depends upon how users are connected to the database to get
their request done.

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

Database architecture can be seen as a single tier or multi-tier. But logically, database
architecture is of three types like: 1-tier architecture, 2-tier architecture and 3-tier
architecture.
1- Tier Architecture
• In this architecture, the database is directly available to the user. It means the user
can directly sit on the DBMS and uses it.
• Any changes done here will directly be done on the database itself. It doesn't provide
a handy tool for end users.
• The 1-Tier architecture is used for development of the local application, where
programmers can directly communicate with the database for the quick response.

2- Tier Architecture
• The 2-Tier architecture is same as basic client-server. In the two-tier architecture,
applications on the client end can directly communicate with the database at the
server side. For this interaction, API's like: ODBC, JDBC are used.
• The user interfaces and application programs are run on the client-side.
• The server side is responsible to provide the functionalities like: query processing and
transaction management.
• To communicate with the DBMS, client-side application establishes a connection with
the server side.

3- Tier Architecture
• The 3-Tier architecture contains another layer between the client and server. In this
architecture, client can't directly communicate with the server.
• The application on the client-end interacts with an application server which further
communicates with the database system.

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

• End user has no idea about the existence of the database beyond the application
server. The database also has no idea about any other user beyond the application.
• The 3-Tier architecture is used in case of large web application.

Three Schema Architecture


• The three schema architecture is also called ANSI/SPARC architecture or three-level
architecture.
• This framework is used to describe the structure of a specific database system.
• The three schema architecture is also used to separate the user applications and
physical database. The three schema architecture contains three-levels. It breaks the
database down into three different categories.

1. The internal level 3 has an internal schema which describes the physical storage
structure of the database. Uses a physical data model and describes the complete details
of data storage and access paths for the database.
2. The conceptual level 3 has a conceptual schema which describes the structure of the
database for users. It hides the details of the physical storage structures, and concentrates
on describing entities, data types, relationships, user operations and constraints. Usually a
representational data model is used to describe the conceptual schema.

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

3. The External or View level 3 includes external schemas or user views. Each external
schema describes the part of the database that a particular user group is interested in and
hides the rest of the database from that user group. Represented using the representational
data model.

• The three schema architecture is used to visualize the schema levels in a database.
• The three schemas are only descriptions of data, the data only actually exists is at the
physical level.

5.1 COMPONENTS OF DBMS


Database Users are differentiated by the way they expect to interact with the system
✓ Application programmers
✓ Sophisticated users
✓ Naïve users
✓ Database Administrator
✓ Specialized users etc..
1. Application programmers: Professionals who write application programs and using these
application programs they interact with the database system
2. Sophisticated users : These user interact with the database system without writing
programs, But they submit queries to retrieve the information
3. Specialized users: Who write specialized database applications to interact with the
database system.
4. Naïve users: Interacts with the database system by invoking some application programs that
have been written previously by application programmers
Eg : people accessing database over the web
5. Database Administrator: Coordinates all the activities of the database system; the
database administrator has a good understanding of the enterprise8s information resources and
needs.
✓ Schema definition
✓ Access method definition
✓ Schema and physical organization modification
✓ Granting user authority to access the database
✓ Monitoring performance
Storage Manager:The Storage Manager include these following components/modules
✓ Authorization Manager
✓ Transaction Manager
✓ File Manager
✓ Buffer Manager
➢ Storage manager is a program module that provides the interface between the low-level
data stored in the database and the application programs and queries submitted to the
system.
➢ The storage manager is responsible to the following tasks:
✓ Interaction with the file manager
✓ Efficient storing, retrieving and updating of data
Authorization Manager
✓ Checks whether the user is an authorized person or not

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

✓ Test the satisfaction of integrity constraints


Transaction Manager
✓ Responsible for concurrent transaction execution.
✓ It ensures that the database remains in a consistent state despite of the system
failure.
File manager
✓ Allocation of disk space and data structures used to represent information on disk.
Buffer manager
✓ Fetching data from disk storage into main memory.
Query Processor
✓ Translate query language into low level instructions.
DML Precompiler
✓ Convert DML statements embedded in an application programs to normal
procedure calls in a host language.
DDL Compiler
✓ Convert DDL statements to a set of tables containing metadata stored in a data
dictionary.
Data File
✓ Store the Data base itself.
Data Dictionary
✓ Stores information about the structure of the DB.
Indices
✓ Provide fast access to data items holding particular rules.

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

6. RELATIONAL DATABASE
➢ A relational database is a database system in which the database is organized and
accessed according to the relationships between data items without the need for any
consideration of physical orientation and relationship.
➢ Relationships between data items are expressed by means of tables.
➢ It is a tool, which can help you store, manage and disseminate information of various
kinds.
➢ It is a collection of objects, tables, queries, forms, reports, and macros, all stored in a
computer program all of which are inter-related.

10

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

➢ It is a method of structuring data in the form of records, so that relations between


different entities and attributes can be used for data access and transformation.
6..1 RELATIONAL MODEL
➢ A Relational Database Management System (RDBMS) is a system, which allows us to
perceive data as tables (and nothing but tables), and operators necessary to manipulate
that data are at the user8s disposal.
➢ Features of an RDBMS The features of a relational database are as follows:
✓ The ability to create multiple relations (tables) and enter data into them
✓ An interactive query language
✓ Retrieval of information stored in more than one table
✓ Provides a Catalog or Dictionary, which itself consists of tables ( called
system tables
➢ Basic Relational Database Terminology:

Catalog:
✓ A catalog consists of all the information of the various schemas
(external,conceptual and internal) and also all of the corresponding mappings
(external/conceptual, conceptual/internal).
✓ It contains detailed information regarding the various objects that are of interest
tothe system itself; e.g., tables, views, indexes, users, integrity rules, security
rules, etc.
✓ In a relational database, the entities of the ERD are represented as tables and their
attributes as the columns of their respective tables in a database schema.
✓ It includes some important terms, such as:
Table: Tables are the basic storage structures of a database where data about
something in the real world is stored. It is also called a relation or an entity.
Row: Rows represent collection of data required for a particular entity.
In order to identify each row as unique there should be a unique identifier called
the primary key, which allows no duplicate rows.
A row is also called a record or a tuple.
Column: Columns represent characteristics or attributes of an entity. Each
attribute maps onto a column of a table. Hence, a column is also known as an
attribute.
Relationship: Relationships represent a logical link between two tables. A
relationship is depicted by a foreign key column.
Degree: number of attributes
Cardinality: number of tuples
An attribute of an entity has a particular value. The set of possible values that a
given attribute can have is called its domain.
The data in an RDBMS is stored in database objects which are called as tables.
A field is a column in a table that is designed to maintain specific information
about every record in the table.
A record is also called as a row of data is each individual entry that exists in a
table.
A NULL value in a table is a value in a field that appears to be blank, which
means a field with a NULL value is a field with no value.

11

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

6.2 OPERATIONS IN RELATIONAL MODEL


➢ Four basic update operations performed on relational database model are Insert, update,
delete and select.

• Insert is used to insert data into the relation


• Delete is used to delete tuples from the table.
• Modify allows you to change the values of some attributes in existing tuples.
• Select allows you to choose a specific range of data.

7. KEYS ANS THEIR USE

Keys:
➢ An attribute or set of attributes whose values uniquely identify each entity in an entity set
is called a key for that entity set.
1. Primary Key:
➢ It is a minimum super key.
➢ It is a unique identifier for the table(a column or a column combination with the
property that at any given time no two rows of the table contain the same value
in that column or column combination).

2. Candidate Key:
➢ There may be two or more attributes or combinations of attributes that uniquely identify
an instance of an entity set. These attributes or combinations of attributes are called
candidate keys.

12

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

3. Super Key:
➢ If we add additional attributes to a key, the resulting combination would still uniquely
identify an instance of the entity set.
➢ Such augmented keys are called super keys.

4. Foreign Key:
➢ A foreign key is a field (or collection of fields) in one table that uniquely
identifies a row of another table. In simpler words, the foreign key is defined in a second
table, but it refers to the primary key in the first table.

13

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

5. Secondary Key:
➢ A secondary key is an attribute or combination of attributes that may not be a candidate
key, but that classifies the entity set on a particular characteristic.
➢ Any key consisting of a single attribute is called a simple key
➢ Combination of attributes is called a composite key.

7.1 RELATIONAL INTEGRITY CONSTRAINTS

• Relational Integrity constraints in DBMS are referred to conditions which must be present for a
valid relation. These Relational constraints in DBMS are derived from the rules in the mini-
world that the database represents.
• There are many types of Integrity Constraints in DBMS. Constraints on the Relational database
management system is mostly divided into three main categories are:
Domain Constraints
Key Constraints
Referential Integrity Constraints
Domain Constraints
➢ Attributes have specific values in real-world scenario. For example, age can only be a
positive integer
➢ Domain constraints specify that within each tuple, and the value of each attribute must be
unique. This is specified as data types which include standard data types integers, real
numbers, characters, Booleans, variable length strings, etc.
Key Constraints

14

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

➢ An attribute that can uniquely identify a tuple in a relation is called the key of the table.
The value of the attribute for different tuples in the relation has to be unique.

Referential Integrity Constraints


➢ Referential Integrity can be defined as an integrity constraint that specifies that the value
(or existence) of an attribute in one relation depend on the value (or existence) of an
attribute in the same or another relation.
➢ Referential Integrity constraints in DBMS are based on the concept of Foreign Keys.
➢ A foreign key is an important attribute of a relation which should be referred to in other
relationships. A foreign key is a key attribute of a relation that can be referred in other
relation.
➢ Referential integrity constraint states that if a relation refers to a key attribute of a
different or same relation, then that key element must exist.

8. 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. which takes instances of relations as input and yields
instances of relations as output.

15

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

➢ It uses operators to perform queries.

1. Select Operation:
• The select operation selects tuples that satisfy a given predicate.
• It is denoted by sigma (σ).
• Notation: σ 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 =, ≠, =, <, >, =.
Table Name : LOAN

2. Project Operation:

16

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

• 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 denoted by ∏.
• Notation: ∏ A1, A2, An (r)

• Where A1, A2, A3 is used as an attribute name of relation r.

3. Union Operation:
• 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.
• It eliminates the duplicate tuples.
• It is denoted by ∪.
• Notation: R ∪ S

17

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

4. Set Intersection:
• 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 n.

18

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

5. Set Difference:
• The result of set difference operation is tuples, which are present in one relation but
are not in the second relation.
• Notation r - s .
• Finds all the tuples that are present in r but not in s.

19

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

20

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

8. Joins operation in relational algebra


• Join operation in relational algebra is a combination of a Cartesian product followed by
which satisfy certain condition.
• A Join operation combines two tuples from two different relations, if and only if a given
condition is satisfied.
• There are different types of join operations.
(I) Natural Join (⋈) :
• A result of natural join is the set of tuples of all combinations in R and S that are equal on
their common attribute names.
• It is denoted by ⋈.
• Natural join is a binary operator.
• Natural join between two or more relations will result set of all combination of tuples
where they have equal common attribute.
• Let us see below example

21

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

(II) Outer Join

• Outer joins are used to include all the tuples from the relations included in join operation
in the resulting relation.
• An outer join is of three types:
1. Left outer join
2. Right outer join
3. Full outer join
• Consider the example:
EMPLOYEE:

22

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

FACT_WORKERS:

(i) Left outer join (÷)


• In Left outer join, all the tuples from the Left relation, say R, are included in the resulting
relation.
• If there are some tuples in relation R which are not matched with tuple in the Right
Relation S, then the attributes of relation R of the resulting relation become NULL.


(ii) Right outer join (ø)
• In Right outer join, all the tuples from the Right relation, say S, are included in the
resulting relation.
• If there are some tuples in relation S which are not matched with tuple in the Right
Relation R, then the attributes of relation S of the resulting relation become NULL.

23

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

(iii)Full outer join


• Full outer join is the combination of both left outer join and right outer join. It contains
all the tuples from both relations.
• For example:

9. SQL FUNDAMENTALS
➢ What is SQL?
• SQL stands for Structured Query Language
• SQL allows you to access a database
• SQL is an ANSI standard computer language
• SQL can execute queries against a database
• SQL can retrieve data from a database
• SQL can insert new records in a database

24

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

• SQL can delete records from a database


• SQL can update records in a database
• SQL is easy to learn
➢ SQL is an ANSI (American National Standards Institute) standard computer language for
accessing and manipulating database systems. SQL statements are used to retrieve and
update data in a database.
➢ SQL works with database programs like MS Access, DB2, Informix, MS SQL Server,
Oracle, Sybase, etc.
➢ There are many different versions of the SQL language, but to be in compliance with the
ANSI standard, they must support the same major keywords in a similar manner (such as
SELECT, UPDATE, DELETE, INSERT, WHERE, and others).
➢ SQL Database Tables
• A database most often contains one or more tables. Each table is by a name
(e.g. "Customers" or "Orders"). Tables contain records (rows) with data. Below is
an example of a table called "Persons":

SQL Language types:


➢ Structured Query Language(SQL) as we all know is the database language by the
➢ use of which we can perform certain operations on the existing database and also we can
use this language to create a database.
➢ SQL uses certain commands like Create, Drop, Insert, etc. to carry out the required tasks.
➢ These SQL commands are mainly categorized into four categories as:
1. DDL 3 Data Definition Language

25

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

2. DQL 3 Data Query Language


3. DML 3 Data Manipulation Language
4. DCL 3 Data Control Language
➢ Though many resources claim there to be another category of SQL clauses TCL –
Transaction Control Language. So we will see in detail about TCL as well.
1. DDL(Data Definition Language) :
➢ DDL or Data Definition Language actually consists of the SQL commands that can be
used to define the database schema.
➢ It simply deals with descriptions of the database schema and is used to create and modify
the structure of database objects in the database.
➢ Examples of DDL commands:
✓ CREATE 3 is used to create the database or its objects (like table, index,
function, views, store procedure and triggers).
✓ DROP 3 is used to delete objects from the database.
✓ ALTER-is used to alter the structure of the database.
✓ TRUNCATE3is used to remove all records from a table, including all
spaces for the records are removed.
✓ COMMENT 3is used to add comments to the data dictionary.
✓ RENAME 3is used to rename an object existing in the database.
2. 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
querypassed to it.
➢ Example of DQL:
• SELECT 3 is used to retrieve data from the database.
3. 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.
➢ Examples of DML:
✓ INSERT 3 is used to insert data into a table.
✓ UPDATE 3 is used to update existing data within a table.
✓ DELETE 3 is used to delete records from a database table.
4. DCL(Data Control Language):
➢ DCL includes commands such as GRANT and REVOKE which mainly deal with the
rights, permissions and other controls of the database system.
➢ Examples of DCL commands:
✓ GRANT-gives user9s access privileges to the database.
✓ REVOKE-withdraw user9s access privileges given by using the GRANT
command.
4. TCL(transaction Control Language):
➢ TCL commands deal with the transaction within the database.
➢ Examples of TCL commands:
✓ COMMIT3 commits a Transaction.
✓ ROLLBACK3 rollbacks a transaction in case of any error occurs.
✓ SAVEPOINT3sets a savepoint within a transaction.

26

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

✓ SET TRANSACTION3specify characteristics for the transaction.


➢ SQL (Structured Query Language) is a syntax for executing queries.
➢ But the SQL language also includes a syntax to update, insert, and delete records.
SQL-DML Query examples:

27

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

28

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

LIKE Condition

INSERT INTO

29

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

UPDATE

30

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

DELETE

31

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

ORDER BY

Aggregate functions in MS Access and SQL server


• Aggregate functions operate against a collection of values, but return a single value.

32

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

GROUP BY

33

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

HAVING

10. EMBEDDED SQL


• Embedded SQL is a method of inserting inline SQL statements or queries into the code of a
programming language, which is known as a host language.
• This is the simplest approach to embed SQL statements directly into the source code
files that will be used to create an application. This technique is referred to as
embedded SQL programming.
• Structure of embedded SQL defines step by step process of establishing a connection

34

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

with DB and executing the code in the DB within the high level language.
• High level programming language compilers cannot interpret SQL statements.
• Hence source code files containing embedded SQL statements must be preprocessed
before compiling.
• Thus each SQL statement coded in a high level programming language source code file must
be prefixed with the keywords EXEC SQL and terminated with either a semicolon or the
keyword END_EXEC.

Connection to Database:
• This is the first step while writing a query in high level languages. First connection to the DB
that we are accessing needs to be established.
• This can be done using the keyword CONNECT. But it has to precede with =EXEC SQLto
indicate that it is a SQL statement.
EXEC SQL CONNECT db_name;
EXEC SQL CONNECT HR_USER; //connects to DB HR_USER
• Once connection is established with DB, we can perform DB transactions.

Host variables
• Database manager cannot work directly with high level programming language
variables.
• Instead, it must be special variables known as host variables to move data between
an application and a database.

Two types of host variables.


• Input host variables: Transfer data to database.
• Output host variable :Receives data from database
Host variables are ordinary programming language., They must be defined within a special
section known as declare section.
EXEC SQL BEGIN DECLARE SECTION;
int STD_ID;
char STD_NAME [15];
char ADDRESS[20];
EXEC SQL END DECLARE SECTION;
• Each host variable must be assigned a unique name even though declared in different
declaration section.
• The following code is a simple embedded SQL program, written in C.
• The program prompts the user for an order number, retrieves the customer number, salesperson,
and status of the order, and displays the retrieved information on the
screen.

35

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

11. DYNAMIC SQL


• Static or Embedded SQL are SQL statements in an application that do not change at
runtime and, therefore, can be hard-coded into the application. Dynamic SQL is SQL
statements that are constructed at runtime; for example, the application may allow
users to enter their own queries.
• Dynamic SQL is a programming technique that enables you to build SQL statements
dynamically at runtime. You can create more general purpose, flexible applications by
using dynamic SQL

Since query needs to be prepared at run time, in addition to the structures discussed in
embedded SQL, we have three more clauses in dynamic SQL. These are mainly used to build the
query and execute them at run time.
PREPARE
Since dynamic SQL builds a query at run time, as a first step we need to capture all the inputs
from the user. It will be stored in a string variable. Depending on the inputs received from the
user, string variable is appended with inputs and SQL keywords.
These SQL like string statements are then converted into SQL query. This is done by using
PREPARE statement.
EXECUTE
This statement is used to compile and execute the SQL statements prepared in DB.
EXEC SQL EXECUTE sql_query;

EXECUTE IMMEDIATE
This statement is used to prepare SQL statement as well as execute the SQL statements in DB. It
performs the task of PREPARE and EXECUTE in a single line.
EXEC SQL EXECUTE IMMEDIATE :sql_stmt;
Example
#include stdio.h
#include conio.h
int main(){
EXEC SQL INCLUDE SQLCA;

36

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

EXEC SQL BEGIN DECLARE SECTION;


int STD_ID;
char *STD_NAME;
int CLASS_ID;
char *sql_stmt;
char *sql_query;
EXEC SQL END DECLARE SECTION;
EXEC WHENEVER NOT FOUND GOTO error_msg1;
EXEC WHENEVER SQLERROR GOTO error_msg2;

printf("Enter the Student name:");


scanf("%s", STD_Name);
printf("Enter the Class ID:");
scanf("%d", &CLASS_ID);
sql_stmt = "SELECT STD_ID FROM STUDENT ";
if (strcmp(STD_NAME, ' ') != 0)
{
sql_stmt = sql_stmt || " WHERE STD_NAME = :STD_NAME";
}
else if (CLASS_ID > 0)
{
sql_stmt = sql_stmt || " WHERE CLASS_ID = :CLASS_ID";
}
EXEC SQL PREPARE sql_queryFROM :sql_stmt;
EXEC SQL EXECUTE sql_query;
printf("STUDENT ID:%d", STD_ID);
exit(0);
Output
Assume the table
STUDENT
STD_ID STD_NAME CLASS_ID CITY CONTACT_NO
CS001 ARUN 101 NAGERCOIL XXX
CS002 ASHA 102 CHENNAI XXX
CS025 MAHESH 202 TRICHY XXX
Enter the Student name : ASHA
(STD_NAME = ASHA )

Enter the Class ID: 202


(CLASS_ID=202)
(If give one valid string as student name the query will be constructed like this:)
SELECT STD_ID FROM STUDENT WHERE STD_NAME = :STD_NAME
And the output will be
CS002
Else
Enter the Student name : PRIYA
(STD_NAME = PRIYA)
If CLASS_ID >0 the query will be framed like
37

Downloaded by Adithya K ([email protected])


lOMoARcPSD|41692702

Department of AI&DS DBMS I Unit

SELECT STD_ID FROM STUDENT WHERE CLASS_ID = :CLASS_ID


And the output will be
CS025

38

Downloaded by Adithya K ([email protected])

You might also like