Professional Documents
Culture Documents
II Bsc Dbms Volume1
II Bsc Dbms Volume1
very Graduate should leave the College with a Degree in one hand
and a Placement order in other hand
Y Jagadeesh
Department of Computer Science
924 66 666 46
Kakinada
3rd Sem 924 66 666 46 1
DATA BASE MANAGEMENT SYSTEM BY Jagadeesh Software Solutions
Syllabus
UNIT I: Overview of Database Management System: Introduction to data, information, database, database
management systems, file-based system, Drawbacks of file-Based System, database approach, Classification of
Database Management Systems, advantages of database approach, Various Data Models, Components of
Database Management System, three schemarchitecture of data base, costs and risks of database approach.
UNIT II: Entity-Relationship Model: Introduction, the building blocks of an entity relationship diagram,
classification of entity sets, attribute classification, relationship degree, relationship classification, reducing ER
diagram to tables, enhanced entity-relationship model (EER model), generalization and specialization, IS A
relationship and attribute inheritance, multiple inheritance, constraints on specialization and generalization,
advantages of ER modeling.
UNIT III: Relational Model: Introduction, CODD Rules, relational data model, concept of key, relational
integrity, relational algebra, relational algebra operations, advantages of relational algebra, limitations of
relational algebra, relational calculus, tuple relational calculus, domain relational Calculus (DRC), Functional
dependencies and normal forms upto 3 rd normal form.
UNIT IV: Structured Query Language: Introduction, History of SQL Standard, Commands in SQL, Data Types
in SQL, Data Definition Language, Selection Operation, Projection Operation, Aggregate functions, Data
Manipulation Language, Table Modification Commands, Join Operation, Set Operations, View, Sub Query.
UNIT V :PL/SQL: Introduction, Shortcomings of SQL, Structure of PL/SQL, PL/SQL Language Elements, Data
Types, Operators Precedence, Control Structure, Steps to Create a PL/SQL, Program, Iterative Control, Procedure,
Function, Database Triggers, Types of Triggers.
UNIT - I
OVERVIEW OF DATABASE MANAGEMENT SYSTEM
INTRODUCTION:
What is a Database ?: To find out what database is, we have to start from data, which is the basic building block of
any DBMS.
Data(Attribute): Data is a piece of information or a single unit of information or any Data item or Field. That is
Facts, figures, statistics etc. having no particular meaning (e.g. 1, JACK, 19 etc).
Record ( Entity ): Record is Collection of interrelated data items or Fields, e.g. in the above example the three
data items had no meaning. But if we organize them in the following way, then they collectively represent
meaningful information.
RNO NAME AGE
1 JACK 19
Tuples or Records: The columns of this relation are called Fields, Attributes or Domains. The rows are called Tuples
or Records.
Database: Database is a collection interrelated records or Collection of related relations. Consider the following
tables:
Table T1:
RNO NAME AGE
1 JACK 19
2 ROSE 18
3 GUY 22
3rd Sem 924 66 666 46 1
DATA BASE MANAGEMENT SYSTEM BY Jagadeesh Software Solutions
Data Base Management System ( D B M S ): A Data Base Management System is a collection of Software packages
system, we have collection of application programs that perform services for the end users. Each program defines
and manages its own data.
A file-based system is a collection of data stored in an orderly manner in a file. It is a file packed with
data, with no metadata and thus no organizing structure. A database is a self-organizing collection of integrated
records, whose metadata gives it structure.
not at all.
9. Concurrent Access Anomalies: Multiple users are allowed to access data simultaneously, this is for the difficult of
better performance and faster response.
10. Security Problems: Database should be accessible to users in limited way. Each user should be allowed to
access data concerning his requirements only.
DATA AND INFORMATION: Data are simply facts or figures — bits of information, but not information itself. When
data are processed, interpreted, organized, structured or presented so as to make them meaningful or useful,
they are called Information. Information provides context for data.
For example, a list of dates — data — is meaningless without the information that makes the dates
relevant (dates of holiday).
"Data" and "information" are intricately tied together, whether one is recognizing them as two separate
words or using them interchangeably, as is common today. Whether they are used interchangeably depends
somewhat on the usage of "data" — its context and grammar.
3rd Sem 924 66 666 46 1
DATA BASE MANAGEMENT SYSTEM BY Jagadeesh Software Solutions
DATABASE: Database is collection of interrelated data where data can be easily accesses, managed and updated.
For example, consider office department in school maintains details of the student such as name of the student,
age, address, class etc. These all records are related with student stored in a database.
DATABASE MANAGEMENT SYSTEM: Database management System is collection of data and set of programs to
access the data. It allows creation, definition and manipulation of database. DBMS provides protection and
security to database. Some examples for popular DBMS are SQL, Oracle, Sybase, MS-Access and DB2.
OBJECTIVES OF DBMS: The main objectives of database management system are data availability, data integrity,
1. Data Availability: Data availability refers to the fact that the data are made available to wide variety of users in
a meaningful format at reasonable cost so that the users can easily access the data.
2. Data Integrity: Data integrity refers to the correctness of the data in the database. In other words, the data
3. Data Security: Data security refers to the fact that only authorized users can access the data. Data security can
be enforced by passwords. If two separate users are accessing a particular data at the same time, the DBMS must
not allow them to make conflicting changes.
4. Data Independence: DBMS allows the user to store, update, and retrieve data in an efficient manner. DBMS
provides an “abstract view” of how the data is stored in the database. In order to store the information efficiently,
complex data structures are used to represent the data. The system hides certain details of how the data
are stored and maintained.
EVALUATION OF DATABASE MANAGEMENT SYSTEM: The chronological order of the development of DBMS is as
ADVANTAGES OF DBMS: The following are the main advantages or characteristics of database management
system.
1. Controlling Data Redundancy: If database have more than one records of same type then it is called data
redundancy. In DBMS, all data is stored in one single database file and that recorded data is placed in the
database.
2. Data Sharing: Data can be shared by authorized users of the organization among multiple users. Many users
can be authorized to access the same data simultaneously. The remote users also can share the same data.
3. Enforcing Data Integrity: In database approach, data integrity is much easier. In database, data is stored in the
tables. A single database contains multiple tables which is easy to retrieve and update the data.
4. Data Security: Data security is the protection of the database from unauthorized access. The DBMS ensures
access of the database through authorized channel. To ensure security, DBMS provides security such as by giving
user name and passwords.
5. Ease of application development : The programmer needs to develop applications according to user specification.
The other issues such as data integrity, security etc are handled by DBMS itself which makes application
development easier.
6. Multiple user interfaces: DBMS provides different types of user interfaces such as application program
interfaces, graphical user interfaces which includes form style and menu driven interfaces. Form style interface
provides user interaction with forms and menu driven interface provides user interaction with list of options called
as menus.
7. Backup and recovery: Most of the DBMS’s provide backup and recovery subsystems which creates automatically
backup of data from hardware and software failures and restores the data if required.
8. Data Independence: Data Independence keeps data separated from all programs that make use of it. In DBMS,
database and application programs are separated from each other and we can easily change the database
structure without modifying the application program.
9. Reduced Maintenance: It can be easily maintainable due to centralized nature of the system.
DISADVANTAGES OF DBMS: The following are the main disadvantages or limitations of database management
system.
1. Cost of Data Conversion: When computer file based system replaced with database system, it must be converted
to database file. It’s difficult to convert data file into database.
2. Complexity: Database system creates additional complexity and requirements. The operation of database
system with several users and databases is quite costly and demanding.
3. Cost of Hardware and Software: To run DBMS software, we need high speed of data processor and large
memory size and DBMS software also too high.
4. Size: DBMS is large piece of software due to its complexity and functionality. It occupies large space of disk and
large memory to run the efficiently.
5. Cost of staff training: DBMS is complex database system which is required to train the users all levels including
programming, application development etc for which organization has to pay lot of amount for training staff to run
the DBMS.
6. Higher impact of failure: In most of the organizations, all data stored in a single database. Since all users and
applications rely on the availability of the DBMS. If database is damaged due to electric failure or database
corruption data may lost forever.
3rd Sem 924 66 666 46 1
DATA BASE MANAGEMENT SYSTEM BY Jagadeesh Software Solutions
DATA MODELS: Data model is collection of conceptual tools for describing data, relationship between data, and
consistency constraints. Data models help in describing the structure of data at the logical level. Data model
describe the structure of the database. A data model is the set of conceptual constructs available for defining a
schema. The data model is a language for describing the data and database.
OR
Data Model is collection of concepts that can be used to describe the structure of the database. It
describes relationship between different parts of the data. Data Models can be categorize according to types of
concepts that describe structure of the database.
DATA MODEL:
I. Conceptual Data Model II. Physical Data Model
I. Conceptual Data Model: The conceptual model is also known as the data model as data model can be used to
describe the conceptual schema when a database system is implemented. It hides the internal details of physical
storage and targets on describing entities, data types, relationships and constraints. The Object Based Logical
Model and Record Based Models are widely used Conceptual Data Models.
A. Object Based Logical Model: Object based data models are used in describing data and data relationships in
accordance with concept. In general Object based data models are gaining wide acceptance for their flexible
structuring capabilities. Various Data Integrity Constraints can be specified clearly by using the Object based data
models. The Entity-Relationship Model and Functional Data Models are widely used Object based data models.
1. Entity: Collection of interrelated attributes, which represents real world object ,such as employee or
project that is described in the database.
2. Attribute: A piece of information which represents property of the entity, such as employee name, address
or salary.
3. Relationship: It represents an association between two or more entities, for example, relationship between
with a physical independence such as person, car, employee etc or it may be an object with conceptual existence
such as company, job etc.
3rd Sem 924 66 666 46 1
DATA BASE MANAGEMENT SYSTEM BY Jagadeesh Software Solutions
Weak Entity Set: An Entity Set is called Weak Entity Set, If its existence depends on other entities (called strong
Entities). Thus a Weak Entity Set does not have sufficient attributes to form a Primary Key.
Strong Entity Set: An Entity Set which has a Primary key, is termed a Strong Entity Set.
Composite Entity: Entities participating in the many to many relationships are called composite entity. In this
case, apart from two entities that are part of relation, we will one more hidden entity in the relation. We will be
creating a new entity with the relation, and create a primary key by using the primary keys of other two entities.
Recursive Entity: If a relation exists between the same entities, then such entities are called as recursive entity.
For example, mapping between manager and employee is recursive entity. Here manager is mapped to the same
entity Employee. HOD of the department is another example of having recursive entity.
Attributes: An attribute is a piece or a small unit of information. The properties of a entity is called as attributes,
consider above example, STUDENT is an entity with properties name, student number, class and student_address.
Types of Attributes:
Simple Attribute: These kinds of attributes have values which cannot be divided further. For example,
STUDENT_ID attribute which cannot be divided further. Passport Number is unique value and it cannot be divided.
Composite Attribute: This kind of attribute can be divided further to more than one simple attribute. For example,
address of a person. Here address can be further divided as Door#, street, city, state and pin which are simple
attributes.
Derived Attribute: Derived attributes are the one whose value can be obtained from other attributes of entities in
the database. For example, Age of a person can be obtained from date of birth and current date. Average salary,
annual salary, total marks of a student etc are few examples of derived attribute.
Stored Attribute: The attribute which gives the value to get the derived attribute are called Stored Attribute. In
example above, age is derived using Date of Birth. Hence Date of Birth is a stored attribute.
Single Valued Attribute: These attributes will have only one value. For example, EMPLOYEE_ID, passport#, driving
more than one email address, and more than one house etc is the examples.
Simple Single Valued Attribute: This is the combination of above four types of attributes. An attribute can have
single value at any point of time, which cannot be divided further. For example, EMPLOYEE_ID – it is single value
as well as it cannot be divided further.
Simple Multi-Valued Attribute: Phone number of a person, which is simple as well as he can have multiple phone
only one DOB and it can be further divided into date, month and year attributes.
Composite Multi-Valued Attribute: Shop address which is located two different locations can be considered as
Descriptive Attribute: Attributes of the relationship is called descriptive attribute. For example, employee works for
department. Here ‘works for’ is the relation between employee and department entities. The relation ‘works for’
can have attribute DATE_OF_JOIN which is a descriptive attribute
Null value: An entity may not have applicable value for an attribute. For example, apartment number applies to
addresses that are in the apartment building and not to other type’s residences.
Relationship: Relationship exists between two database tables when one table has foreign key that references to
primary key of the other table and it is also associates between entities. Following are types of relationships
between tables.
1. One-to-One relationship:
In this type, a row in table A can have no more than one matching row in table B.
2. One-to-Many Relationship:
In this type, a row in table A can have more matching rows in table B but row in table B can have only
one matching row in table A.
3. Many-to-Many Relationship:
In this type, a row in table A can have many matching rows in table B and vice versa.
4. many-to-one relationship: In this type, more than one entities from table A can be associated with at
most one entity of table B but one entity from table B can be associated with more than one entity
from table
2. Object-Oriented Model:
Object-oriented modeling (OOM) is the construction of objects using a collection of objects that contain
stored values of the instance variables found within an object. Unlike models that are record-oriented, object-
oriented values are solely objects. The object-oriented model is based on a collection of objects, like the E-R
model.
B. Record Based Models: These Models are used to specify the overall logical structure of the database. The
Data Integrity Constraints can not be specified with these models. The three widely accepted Record based Data
Models are 1. Hierarchical Data Model 2. Network Data Model 3. Relational Dat Model
3rd Sem 924 66 666 46 1
DATA BASE MANAGEMENT SYSTEM BY Jagadeesh Software Solutions
1. HIERARCHICAL DATA MODEL: In this data model, the entities are represented in a hierarchical fashion. Here we
identify a parent entity, and its child entity. Again we drill down to identify next level of child entity and so on.
This model can be imagined as folders inside a folder! In our example above, it is graphically represented as
below:
2. NETWORK DATA MODEL: This is the enhanced version of hierarchical data model. It is designed to address the
drawbacks of the hierarchical model. It helps to address M:N relationship. This data model is also represented as
hierarchical, but this model will not have single parent concept. Any child in the tree can have multiple parents.
Let us consider a company example. A company has different projects and departments in the company own
those projects. Even suppliers of the company give input for the project. Here Project has multiple parents and
each department and supplier have multiple projects. This is represented as shown below.
3. RELATIONAL DATA MODEL: The relational model represents the database as collection of relations. It is most
popular data model in DBMS. In the relational model, all data must be stored in the form of tables and each
relation consists of rows and columns. When a relation is thought of set of table values, each row in the table
represents collection of related data values. In the relational model, each row in the table represents real world
entity or relationship. In this model, a row is called a tuple, a column header is called attribute and table is called
a relation. Each row contains unique value and each column contains values from a same domain.
Now, in the employee table, we have column which uniquely identifies each employee – that is employee
Id column. This column has unique value. Such column is called as primary key of the table. Similarly department
table has DEPT_ID as primary key. In the employee table, instead of storing whole information about his
department, we have DEPT_ID from department table stored. i.e.; by using the data from the department table,
we have established the relation between employee and department tables.
3rd Sem 924 66 666 46 1
DATA BASE MANAGEMENT SYSTEM BY Jagadeesh Software Solutions
Supports both one to many and Supports both one to many and
Supports One-Many Relationship
Many to Many relationship Many to Many relationship
II. PHYSICAL DATA MODEL: These models are used to have higher level description of the storage structure of the
database and their access mechanism. With the Physical Data Model it is possible to implement the Database at
the system level. A very few Physical Data Models have been proposed so for. Two of these well known models
are 1. Unifying Model 2. Frame Memory model
OR
DATA MODEL: A Database model defines the logical design of data. The model describes the relationships
between different parts of the data. Historically, in database design, three models are commonly used. They are,
1. Hierarchical Model 2. Network Model 3. Relational Model
1. HIERARCHICAL MODEL: In this model each entity has only one parent but can have several children. At the top
of hierarchy there is only one entity which is called Root.
3rd Sem 924 66 666 46 1
DATA BASE MANAGEMENT SYSTEM BY Jagadeesh Software Solutions
2. NETWORK MODEL: In the network model, entities are organized in a graph, in which some entities can be
accessed through several paths
3. RELATIONAL MODEL: In this model, data is organized in two-dimensional tables called relations. The tables or
relation are related to each other.
Database Management
Systems ( Utilities )
Data Base
Application Administrator
Developers (DBA)
COMPONENTS OF DBMS: A database management system (DBMS) consists of several components. Each
component plays very important role in the database management system environment. The major components
of database management system are:
1. Database Management Systems ( Utilities )
2. Data Base
3. Data
4. Data Dictionary / Data Directory
5. Application Developers
6. User Groups
3rd Sem 924 66 666 46 1
DATA BASE MANAGEMENT SYSTEM BY Jagadeesh Software Solutions
1. Database Management Systems (Utilities): Database Management Systems (Utilities) like Oracle, SQL, Sybase,
DB2, etc. These are the Database languages which are used to develop different Database applications.
2. Data Base: Database is collection of interrelated data where data can be easily accesses, managed and updated.
3. Data: Data is the most important component of the DBMS. Data is a piece of information. The main purpose of
DBMS is to process the data.
4. Data Dictionary / Data Directory: Data Dictionary or Data Directory is a system which maintains data about
data in the Database. This will contain information about the following.
a. Number files in the Database b. Name of the Files c. Association between the Files
d. Structure of each file, Which includes the list of fields in it, type of each field, length of each field etc .
5. Application Developers: Application Developers are developed in programming languages such as C++, Visual
Basic that are used to to access database in database management system.
6. User Groups: The users Groups are the people who manage the databases and perform different operations on
the databases in the database system. There are three kinds of people who play different roles in database
system 1. Application Programmers 2. Database Administrators 3. End-Users
1. Application Programmers: The people who write application programs in programming languages (such as
Visual Basic, Java, or C++) to interact with databases are called Application Programmers.
2. Database Administrators: A person who is responsible for managing the overall database management system
is called database administrator or simply DBA.
3. End-Users: The End-users are the people who interact with database management system to perform different
Two-tier Client / Server architecture is used for User Interface program and Application Programs that
runs on client side. An interface called ODBC (Open Database Connectivity) provides an API that allow client side
program to call the DBMS. Most DBMS vendors provide ODBC drivers. A client program may connect to several
DBMS's. In this architecture some variation of client is also possible for example in some DBMS's more
functionality is transferred to the client including data dictionary, optimization etc. Such clients are called Data
server.
3rd Sem 924 66 666 46 1
DATA BASE MANAGEMENT SYSTEM BY Jagadeesh Software Solutions
Three-tier Client / Server database architecture is commonly used architecture for web applications.
Intermediate layer called Application server or Web Server stores the web connectivity software and the business
logic(constraints) part of application used to access the right amount of data from the database server. This layer
acts like medium for sending partially processed data between the database server and the client.
defined, and not expected to change. Runtime overheads are not feasible because of real-time requirements.
Multiple accesses to data are not required.
Compared with file systems, databases have some disadvantages: 1. High cost of DBMS which includes:
a. Higher hardware costs b. Higher programming costs c. High conversion costs
1. New Specialized Personnel: Frequently, organizations that adopt the database approach need to hire or
train individuals to design & implement databases, provide database administration services and manage
a staff of new people, further, because of the rapid changes in technology these new people will have to
be retrained or upgraded on a regular basis.
2. Installation &Management Costs and complexity: A multi-user database management system is a
large and complex suite of software that has a high initial cost, requires a staff of trained personnel to
install and operate, and also has substantial annual maintenance & support costs. Installing such a system
may also require upgrades to the hardware and data communications system in the organization.
3. Conversion Costs: The cost of converting the traditional file processing systems to modern database
technology: measured in terms of money, time, and organizational commitment.
4. Need for explicit Backup & Recovery: A shared corporate database must be accurate and available at
all times. These require that comprehensive procedures be developed and used for providing backup
copies of data and for restoring a database when damage occurs.
5. Organizational Conflict: A shared database requires a consensus on data definitions and ownership as
well as responsibilities for accurate data maintenance. Experience has shown that conflicts on data
definitions, data formats, and coding, rights to update shared data are frequent and often difficult to
resolve.
UNIT-IV
STRUCTURED QUERY LANGUAGE ( S Q L )
INTRODUCTION TO S Q L : Structure Query Language(SQL) is a programming language used for storing and
managing data in RDBMS. SQL was the first commercial language introduced for E.F Codd's Relational model.
HISTORY OF SQL STANDARD: SQL was initially developed at IBM by Donald D. Chamberlin and Raymond F. Boyce in
the early 1970s. This version, initially called SEQUEL ( Structured English Query Language ), was designed to
manipulate and retrieve data stored in IBM's original quasi-relational database management System,
DATA TYPES IN SQL: SQL Data Type is an attribute that specifies the type of data of any object. Each column,
variable and expression has a related data type in SQL. We can use these data types while creating your tables.
We can choose a data type for a table column based on your requirement. SQL offers categories of data types for
your use which are listed below
1. CHAR(size): This data type specifies a fixed length character string. The default length of CHAR column
is 1 character and the maximum allowed is 255 characters The syntax is
Syntax: <name of the column> <data type>(size)
Ex: SNAME CHAR(20)
2. VARCHAR(size): This data type is Variable length character string having maximum length size or bytes.
The maximum length of VARCHAR is 2000 character and the minimum is 1 character.
Syntax: <name of the column> <data type>(size)
Ex: SNAME VARCHAR(20)
3. VARCHAR2(size): This data type is Variable length character string having maximum length size or bytes.
The maximum length of VARCHAR is 4000 character and the minimum is 1 character.
3rd Sem 924 66 666 46 1
DATA BASE MANAGEMENT SYSTEM BY Jagadeesh Software Solutions
4. NUMBER(p,s): This Number data type having precision p and scale s. The precision p can range from 1
to 38. The scale s can range from -84 to 127. The syntax is
Syntax1: <name of the column> NUMBER(P)
Ex: SNO NUMBER(5)
Syntax2: <name of the column> NUMBER(P,S)
Ex: SAVG NUMBER(5,2)
5. DATE: This data type is used to represent date and time. The valid date range from
January 1,4712 BC to December 31, 3712 AD. The standard format is DD-MON-YY.
Syntax: <name of the column> date
Ex: SDOB DATE
5. LONG: This data type is used to store Variable length character strings containing up to 2GB.
It can be used to store arrays of binary data in ASCII format. LONG Values can not be
indexed.
Syntax: <name of the column> LONG
Ex: SREMARKS LONG
6. RAW: This data type is used to store binary data that is digitalized picture or Image.
The RAW data can have maximum length of 255 bytes.
Syntax: <name of the column> RAW
Ex: SPHOTO RAW]
COMMANDS IN SQL: SQL language is divided into four types of primary language statements: DML, DDL, DCL
and TCL. Using these statements, we can define the structure of a database by creating and altering database
objects, and we can manipulate data in a table through updates or deletions. We also can control which user can
read/write data or manage transactions to create a single unit of work. The four main categories of SQL
statements are as follows:
1. DDL (Data Definition Language) 2. DML (Data Manipulation Language)
DDL statements are used to create, alter/modify, rename and delete a database or table structure and
schema. These statements handle the design and storage of database objects.
A. CREATE: This command is used to create a new Table, database or schema with or without constraints.
The general format of CREATE command is
Syntax: SQL> CREATE TABLE <TABLE_NAME>(FIELD-NAME1/COLUMN-NAME1 DATA_TYPE(SIZE), FIELD-
NAME2/COLUMN-NAME2 DATA_TYPE(SIZE),......, FIELD-NAME-N/COLUMN-NAME-N
DATA_TYPE(SIZE));
Example1: SQL> CREATE TABLE STUDENT(SNO NUMBER(3),SNAME VARCHAR2(15),GROUP VARCHAR2(15),SUB1
NUMBER(3),SUB2 NUMBER(3),SUB3 NUMBER(3), TOT NUMBER(3), AVG NUMBER(5,2), GRADE
VARCHAR2(1));
Example2: SQL> CREATE TABLE STUDENT(SNO NUMBER(3) PRIMARY KEY, SNAME VARCHAR2(15) UNIQUE, GROUP
VARCHAR2(15),SUB1 NUMBER(3), SUB2 NUMBER(3), SUB3 NUMBER(3), TOT NUMBER(3), AVG
NUMBER(5,2), GRADE VARCHAR2(1));
3rd Sem 924 66 666 46 1
DATA BASE MANAGEMENT SYSTEM BY Jagadeesh Software Solutions
B. ALTER: This command is used to add new columns in existing table or modify/change existing table,
column description. ALTER command have two options ADD and MODIFY. The general format
of ALTER command is
ALTER with ADD Option: It is used to add new fields in an existing table.
Syntax: SQL> ALTER TABLE <TABLE_NAME> ADD (FIELD-NAME1/COLUMN-NAME1 DATA_TYPE(SIZE), FIELD-
NAME2/COLUMN-NAME2 DATA_TYPE(SIZE),....,FIELD-NAME-N/COLUMN-NAME-N
DATA_TYPE(SIZE));
Example: SQL> ALTER TABLE STUDENT ADD (COLLAGE VARCHAR2(15),CITY VARCHAR2(15));
ALTER with MODIFY Option: It is used to modify or change the data type size of existing fields in a table.
Syntax: SQL> ALTER TABLE<TABLE_NAME>MODIFY FIELD-NAME1/COLUMN-NAME1 DATA_TYPE(SIZE),
FIELD-NAME2/COLUMN-NAME2DATA_TYPE(SIZE),....,FIELD-NAME-N/COLUMN-NAME-DATATYPE
(SIZE));
Example: SQL> ALTER TABLE STUDENT MODIFY (SNAME VARCHAR2(20));
ALTER with DROP COLUMN Option: It is used to drop the column or constraint in a table. The basic syntax of an
C. DROP: This command is used to delete existing tables or objects from database. The syntax is
Syntax: SQL> DROP TABLE <TABLE_NAME>;
Example: SQL> DROP TABLE STUDENT;
D. TRUNCATE: This command used to delete all the rows completely in a Table. This command first drops the
table with Records and recreates the structure of the table. The general format is
Syntax: SQL> TRUNCATE TABLE <TABLE_NAME>;
Example: SQL> TRUNCATE TABLE STUDENT;
E. RENAME: This command used to change name of an existing Table. The general format of RENAME
command is
Syntax: SQL> RENAME TABLE <TABLE_NAME1> <TABLE_NAME1>;
Example: SQL> RENAME TABLE YRL ADITYA;
2. DML (DATA MANIPULATION LANGUAGE): DML statements affect records in a table. These are basic
operations we perform on data such as selecting a few records from a table, inserting new records, deleting
unnecessary records, and updating/modifying existing records. DML statements include the following:
A. INSERT : insert new records
B. SELECT : select records from a table
C. UPDATE : update/Modify existing records
D. DELETE : delete existing records
A. INSERT: This command is used to insert new records in to database or table. This command
has various general formats.
Syntax2: This command is used to Inserting multiple records into database using substitute parameters
SQL> INSERT INTO <TABLE_NAME>VALUES( ‘&COLUMN _NAME1’,‘&COLUMN _NAME2’,‘&COLUMN
_NAME3 ’,……, ‘ &COLUMN _NAMEN ’);
Example: SQL>INSERT INTO SUPPLIER VALUES (&SNO, '&SNAME', '&SADDR', '&SCITY', '&PHNO');
Syntax4: This command is used to Inserting particular field values in to database using substitute parameters.
SQL> INSERT INTO <TABLE_NAME>( FIELD NAME1, FIELD NAME2, FIELD NAME3, . . . , FIELD NAMEN )
VALUES (&FIELD NAME1/COLUMN1, &FIELD NAME2/ COLUMN2,……, &FIELD NAMEN/ COLUMNN);
Example: SQL> INSERT INTO SUPPLIER (SNO, SNAME, SADDR) VALUES (&SNO, ’& SNAME’, ’& SADDR’ );
B. SELECT COMMAND: Select query is used to retrieve data from tables. It is the most used SQL query. This
command is used to retrieve or select records from a specific database or table. This command has various
formats.
Syntax1: SELECT WITH * OPTION: This command is used to retrieve or display the all records from given table or
data base.
SQL> SELECT * FROM <TABLE NAME>;
Example: SQL> SELECT * FROM STUDENT;
Syntax2: SELECT WITH COLUMNS LIST: This command is used to retrieve or display the specific fields of a record
from given table or data base.
SQL> SELECT <COLUMN NAME1, COLUMN NAME2, COLUMN NAME3, . . . , COLUMN NAMEN>
FROM <TABLE NAME>;
Example: SQL> SELECT SNO, SNAME, SUB1, SUB2, SUB3 FROM STUDENT;
Syntax3: SELECT WITH DISTINCT CLAUSE: We can eliminate duplicate rows by using SELECT with DISTINCT
command. It is used to eliminate duplicate records.
SQL> SELECT <DISTINCT> <*> [<COLUMN NAME1,COLUMN NAME2,COLUMN NAME3, . . . . ,
COLUMN NAMEN> ] FROM <TABLE NAME>;
Examples: SQL> SELECT DISTINCT * FROM STUDENT;
SQL> SELECT DISTINCT (SNO, SNAME, SUB1, SUB2, SUB3) FROM STUDENT;
Syntax4: SELECT WITH WHERE CLAUSE: The SELECT with WHERE Clause is used to retrieve or display the all
records or specific fields of a record or records or distinct records from given table or data base by using given
condition.
SQL> SELECT [<DISTINCT>] [ <*> ] [ <COLUMN NAME> ] [<COLUMN NAME1,COLUMN NAME2,
COLUMN NAME3, . . . . ,COLUMN NAMEN> ] FROM <TABLE NAME> [WHERE <CONDITION> ];
Examples: SQL> SELECT * FROM STUDENT WHERE SNAME=’JAGADEESH’;
SQL> SELECT SNO, SNAME, SUB1, SUB2, SUB3 FROM STUDENT STUDENT WHERE (SNO>=1 AND SNO<100);
SQL> SELECT DISTINCT (SNO, SNAME, SUB1, SUB2, SUB3 ) FROM STUDENT STUDENT WHERE
(SNO>=1 AND SNO<100);
Syntax5: SELECT WITH ORDER BY CLAUSE: Order by clause is used with Select statement for arranging retrieved
data in sorted order. The Order by clause by default sort data in ascending order. To sort data in descending
order DESC keyword is used with Order by clause.
3rd Sem 924 66 666 46 1
DATA BASE MANAGEMENT SYSTEM BY Jagadeesh Software Solutions
Syntax6: SELECT WITH GROUP BY CLAUSE: Group by clause is used to group the results of a SELECT query based
on one or more columns. It is also used with SQL functions to group the result from one or more tables. The
SELECT with GROUP BY Clause is used to group all the records in a table or database together for each and every
value of a specified field(s) and then display them for a selected set of fields or records from the table.
SQL> SELECT [<DISTINCT>] [ <*> ] [ <COLUMN NAME> ] [<COLUMN NAME1, COLUMN
NAME2, COLUMN NAME3, . . . . ,COLUMN NAMEN> ] FROM <TABLE NAME> [ <GROUP BY > <COLUMN
NAME> ] [ WHERE <CONDITION> ];
Examples: SQL> SELECT * FROM STUDENT GROUP BY SCLASS;
SQL> SELECT SNO, SNAME, SCLASS, STOT, SAVG FROM STUDENT GROUP BY SGROUP;
SQL> SELECT * FROM STUDENT GROUP BY SGROUP WHERE ( SAVG>=75 );
SQL> SELECT DISTINCT (SNO,SNAME,SUB1,SUB2,SUB3) FROM STUDENT GROUP BY SCLASS
WHERE (SNO>=1 AND SNO<1000);
Syntax7: SELECT WITH HAVING CLAUSE: SELECT with HAVING clause is used with SQL Queries to give more precise
condition for a statement. It is used to mention condition in Group based SQL functions, just like WHERE clause.
SQL> SELECT <COLUMN NAME>,< FUNCTION(COLUMN NAME) > FROM <TABLE NAME> [WHERE
<CONDITION> ] [<GROUP BY > <COLUMN NAME>] [ HAVING < FUNCTION ( COLUMN NAME ) >
<CONDITION> ];
Example: SQL> SELECT * FROM STUDENT GROUP BY SCLASS HAVING SUM(SUB1)>=75;
Syntax8: SELECT WITH LIKE CLAUSE : Like clause is used as condition in SQL query. Like clause compares data with
an expression using wildcard operators. It is used to find similar data from the table.
Syntax8: SELECT WITH WILDCARD OPERATORS : There are two wildcard operators that are used in like clause.
Percent sign % represents zero, one or more than one character. Underscore sign _ : represents only one
character.
SQL> SELECT [<DISTINCT>] [ <*> ] [ <COLUMN NAME> ] [<COLUMN NAME1, COLUMN NAME2, COLUMN
NAME3, . . , COLUMN NAMEN> ] FROM <TABLE NAME> [ WHERE < CONDITION WITH LIKE CLAUSE > ];
Examples: SQL> SELECT * FROM STUDENT WHERE SNAME LIKE ’_G%’;
SQL> SELECT SNO, SNAME, SUB1, SUB2, SUB3 FROM STUDENT WHERE SNAME LIKE ’%J’;
C. UPDATE COMMAND: Update command is used to update a row of a table. This command is used for updating or
modifying the values of columns of existing records in a table or database. Following is its general syntax
Syntax: SQL> UPDATE <TABLE NAME> SET <COLUMN NAME1 = COLUMN NAME2 / VALUE / EXP[WHERE
<CONDITION>];
Example: SQL> UPDATE STUDENT SET STOT = SUB1+SUB2+SUB3;
SQL> UPDATE STUDENT SET SAVG = AVG WHERE STOT>=750;
3rd Sem 924 66 666 46 1
DATA BASE MANAGEMENT SYSTEM BY Jagadeesh Software Solutions
D. DELETE COMMAND: Delete command is used to delete data or existing records from a table. Delete command
can also be used with condition to delete a particular row. Following is its general syntax
3. TCL (TRANSACTION CONTROL LANGUAGE) COMMANDS: Transaction Control Language ( TCL) commands are
used to manage transactions in database. These are used to manage the changes made by DML statements. It
also allows statements to be grouped together into logical transactions. the following are TCL Commands.
A. COMMIT B. ROLLBACK C. SAVEPOINT
A. COMMIT COMMAND: Commit command is used to permanently save any transaction into database. The
syntax of Commit Command is
Syntax: SQL> COMMIT;
Example: SQL> COMMIT;
B. ROLLBACK COMMAND: This command restores the database to last commited state. It is also use with
savepoint command to jump to a savepoint in a transaction. The syntax of Commit Command is
C. SAVEPOINT COMMAND: SAVEPOINT command is used to temporarily save a transaction so that you can
rollback to that point whenever necessary.
Syntax: SQL> SAVEPOINT <SAVEPOINT NAME>;
Example: SQL> SAVEPOINT JAGADEESH;
Following is the STUDENT table,
SNO SNAME
1 JAGADEESH
2 RADHIKA
4 SATYAVATHI
Example:
SQL> INSERT INTO STUDENT VALUES ( 5, ‘JACK’);
SQL> COMMIT;
SQL> UPDATE STUDENT SET SNAME= ‘ROSE’ WHERE SNO=5;
SQL> SAVEPOINT A;
SQL> INSERT INTO STUDENT VALUES ( 6, ‘GUY’);
SQL> SAVEPOINT B;
SQL> INSERT INTO STUDENT VALUES ( 7, ‘PEARL’);
SQL> SAVEPOINT C;
SQL> SELECT * FROM STUDENT;
The resultant table will look like,
SNO SNAME
1 JAGADEESH
2 RADHIKA
4 SATYAVATHI
5 JACK
6 GUY
7 PEARL
Now rollback to savepoint B
3rd Sem 924 66 666 46 1
DATA BASE MANAGEMENT SYSTEM BY Jagadeesh Software Solutions
SQL> ROLLBACK TO B;
SQL> SELECT * FROM STUDENT;
The resultant table will look like
SNO SNAME
1 JAGADEESH
2 RADHIKA
4 SATYAVATHI
5 JACK
6 GUY
Now ROLLBACK to SAVEPOINT A
SQL> ROLLBACK TO A;
SQL> SELECT * FROM STUDENT;
The resultant table will look like
SNO SNAME
1 JAGADEESH
2 RADHIKA
4 SATYAVATHI
5 JACK
4. DCL COMMANDS: Data Control Language (DCL) is used to control privilege in Database. To perform any
operation in the database, such as for creating tables, sequences or views we need privileges. Privileges are of
two types
1. System Privileges: creating session, table etc are all types of system privilege.
2. Object Privileges: any command or query to work on tables comes under object privilege.
Data Control Language (DCL) defines two types of commands,
a. GRANT : Gives user access privileges to users.
b. REVOKE : Take back permissions from user.
A. GRANT COMMAND:
Syntax4: This command is used to allow a user to create table to provide user with some space on table space to
store table
SQL> ALTER <USER NAME> QUOTA UNLIMITED ON SYSTEM;
Example: SQL> ALTER SCOTT QUOTA UNLIMITED ON SYSTEM;
B. REVOKE COMMAND:
Syntax1: This command is used to take back permissions or access privileges from users.
SQL> REVOKE <PRIVILEGE NAME> FROM <USER NAME>;
Example: SQL> REVOKE CREATE TABLE FROM SCOTT;
SQLFUNCTIONS: Oracle Built in Functions: There are two types of functions in Oracle.
1. Single Row Functions: Single row or Scalar functions return a value for every row that is processed in a query.
2. Group Functions: These functions group the rows of data based on the values returned by the query. This is
discussed in SQL GROUP Functions. The group functions are used to calculate aggregate values like total or
average, which return just one total or one average value after processing a group of rows.
1. SINGLE ROW FUNCTIONS: There are four types of single row functions. They are:
a. Numeric Functions: These are functions that accept numeric input and return numeric values.
b. Character or Text Functions: These functions that accept character input and can return both character
and number values.
c. Date Functions: These are functions that take values that are of datatype DATE as input and return values of
datatype DATE, except for the MONTHS_BETWEEN function, which returns a number.
d. Conversion Functions: These are functions that help us to convert a value in one form to another form. For
Example: a null value into an actual value, or a value from one datatype to another datatype like NVL, TO_CHAR,
TO_NUMBER, TO_DATE etc.
What is a DUAL Table in Oracle? This is a single row and single column dummy table provided by oracle. This is
DUMMY
-------
X
a. NUMERIC FUNCTIONS: Numeric functions are used to perform operations on numbers. They accept numeric
values as input and return numeric values as output. The following examples explains the usage of the numeric
functions
FUNCTION RETURN
DESCRIPTION EXAMPLES
NAME VALUE
ABS (x) Absolute value of the number 'x' ABS (1) ABS (-1) 1 -1
Integer value that is Greater than or
CEIL (x) CEIL (2.83) CEIL (2.49) CEIL (-1.6) 3 3 -1
equal to the number 'x'
Integer value that is Less than or equal FLOOR (2.83) FLOOR (2.49) FLOOR
FLOOR (x) 2 2 -2
to the number 'x' (-.6)
TRUNC (x, y) Truncates value of number 'x' up to 'y' ROUND (125.456, 1) ROUND 125.4 125
3rd Sem 924 66 666 46 1
DATA BASE MANAGEMENT SYSTEM BY Jagadeesh Software Solutions
These functions can be used on database columns. For Example: Let's consider the product table used in
SQL JOINS. We can use ROUND to round off the unit price to the nearest integer, if any product has prices in
fraction.
SQL> SELECT ROUND (UNIT_PRICE) FROM PRODUCT;
b. CHARACTER OR TEXT FUNCTIONS: Character or text functions are used to manipulate text
strings. They accept strings or characters as input and can return both character and
number values as output. Few of the character or text functions are
RETURN
FUNCTION NAME RETURN VALUE EXAMPLES
VALUE
All the letters in 'string_value'
LOWER (string_value) LOWER('Good Morning') good morning
is converted to lowercase.
All the letters in 'string_value' GOOD
UPPER (string_value) UPPER('Good Morning')
is converted to uppercase. MORNING
All the letters in 'string_value'
INITCAP (string_value) INITCAP('GOOD MORNING') Good Morning
is converted to mixed case.
All occurrences of 'trim_text'
LTRIM (string_value,
is removed from the left of LTRIM ('Good Morning', 'Good) Morning
trim_text)
'string_value'.
All occurrences of 'trim_text'
RTRIM (string_value, RTRIM ('Good Morning','
is removed from the right of Good
trim_text) Morning')
'string_value' .
Returns 'n' number of
SUBSTR (string_value, m,
characters from 'string_value' SUBSTR ('Good Morning', 6, 7) Morning
n)
starting from the 'm' position.
Number of characters in
LENGTH (string_value) LENGTH ('Good Morning') 12
'string_value' in returned.
Example: we can use the above UPPER() text function with the column value as follows.
c. DATE FUNCTIONS: These are functions that take values that are of datatype DATE as
input and return values of, except datatypes DATE for the MONTHS_BETWEEN function,
which returns a number as output. Few date functions
FUNCTION NAME RETURN VALUE
ADD_MONTHS (DATE, N) Returns a date value after adding 'n' months to the date 'x'.
MONTHS_BETWEEN (X1, X2) Returns the number of months between dates x1 and x2.
NEXT_DAY (X, WEEK_DAY) Returns the next date of the 'week_day' on or after the date 'x' occurs.
It is used to determine the number of days remaining in a month from the date 'x'
LAST_DAY (X) specified.
SYSDATE Returns the systems current date and time.
NEW_TIME(X,ZONE1,ZONE2) Returns the date and time in zone2 if date 'x' represents the time in zone1.
THE BELOW TABLE PROVIDES THE EXAMPLES FOR THE ABOVE FUNCTIONS
FUNCTION NAME EXAMPLES RETURN VALUE
3rd Sem 924 66 666 46 1
DATA BASE MANAGEMENT SYSTEM BY Jagadeesh Software Solutions
d. CONVERSION FUNCTIONS: These are functions that help us to convert a value in one form to another form.
Few of the conversion functions available in oracle are:
The below table provides the examples for the above functions
FUNCTION NAME EXAMPLES RETURN VALUE
TO_CHAR (3000, '$9999') $3000
TO_CHAR ()
TO_CHAR (SYSDATE, 'Day, Month YYYY') Monday, June 2008
TO_DATE () TO_DATE ('01-Jun-08') 01-Jun-08
Constraint is a specific rule or condition. Integrity Constraints are used to apply rules for the database
tables. Integrity constraints are used to ensure accuracy and consistency of data in a relational database. The
constraints can be defined in two ways
1. Column Level Constraints: The constraints can be specified immediately after the column definition. Column
level constraints are just imposing on a single column. Column level constraints cannot be applied if a
constraint spans more than one column in a table.
Syntax: SQL> COLUMN_NAME DATA TYPE [CONSTRAINT <NAME>] CONSTRAIN_TYPE,
Example: SQL> CREATE TABLE EMPLOYEE (ID NUMBER(5), NAME CHAR(20), CONSTRAINT JACK NOT NULL,
DEPT CHAR(10), AGE NUMBER(2), SAL NUMBER(10,2) );
2. Table Level Constraints: The constraints can be specified after all the columns are defined. Table level
constraints applied on more than one column on a table.
Syntax: SQL>[CONSTRAINT CONSTRAINT_NAME] CONSTRAIN_TYPE (COLUMN_NAME1, COLUMN_NAME2, . . .)
Example: SQL> CREATE TABLE EMPLOYEE ( ID NUMBER(5), NAME CHAR(20), DEPT CHAR(10), AGE
NUMBER(2), SAL NUMBER(10,2) CONSTRAINT JACK UNIQUE(ID, DEPT));
1. NOT NULL CONSTRAINT: This constraint ensures all rows in the table contain a definite value for the column
which is specified as not null. Which means a null value is not allowed. The NOT NULL constraint defined at
Column level only.
Syntax: SQL> COLUMN_NAME DATA TYPE [CONSTRAINT < CONSTRAINT_NAME>] NOT NULL,
Example: SQL> CREATE TABLE EMPLOYEE (ID NUMBER(5), NAME CHAR(20) CONSTRAINT JACK NOT NULL,
DEPT CHAR(10), AGE NUMBER(2), SAL NUMBER(10,2) );
3rd Sem 924 66 666 46 1
DATA BASE MANAGEMENT SYSTEM BY Jagadeesh Software Solutions
2. UNIQUE CONSTRAINT: This constraint ensures that a column or a group of columns in each row have a distinct
value. A column(s) can have a null value but the values cannot be duplicated. to Define Unique Constraint at Column
Level:
Syntax1: SQL> COLUMN_NAME DATA TYPE [CONSTRAINT < CONSTRAINT_NAME >] UNIQUE,
Example: SQL> CREATE TABLE EMPLOYEE ( ID NUMBER(5) CONSTRAINT JACK UNIQUE, NAME CHAR(20),
DEPT CHAR(10), AGE NUMBER(2), SAL NUMBER(10,2) );
3. PRIMARY KEY CONSTRAINT: This constraint defines a column or combination of columns which uniquely
identifies each row in the table. To Define Primary Key Constraint at Column Level:
Syntax: SQL> (COLUMN_NAME DATA TYPE [CONSTRAINT <CONSTRAINT_NAME>] PRIMARY KEY,
Example: SQL> CREATE TABLE EMPLOYEE ( ID NUMBER(5) CONSTRAINT JACK PRIMARY KEY, NAME
CHAR(20), DEPT CHAR(10), AGE NUMBER(2), SAL NUMBER(10,2) );
To Define Primary Key Constraint at Table Level:
Syntax: SQL>[CONSTRAINT CONSTRAINT_NAME] PRIMARY KEY (Column_Name1, Column_Name2, . . . . .)
Example: SQL>CREATE
TABLE EMPLOYEE ( ID NUMBER(5), NAME CHAR(20), , DEPT CHAR(10), AGE
NUMBER(2), SAL NUMBER(10,2) CONSTRAINT JACK PRIMARY KEY( ID, DEPT) );
This constraint identifies any column referencing the PRIMARY KEY in another table. It establishes a
relationship between two columns in the same table or between different tables. For a column to be defined as
a Foreign Key, it should be a defined as a Primary Key in the table which it is referring. One or more columns
can be defined as Foreign key. To Define Foreign Key Constraint at Column level:
Syntax: SQL> (COLUMN_NAME DATATYPE [CONSTRAINT <COLUMN_NAME>]REFERENCES
REFERENCED_TABLE_NAME (COLUMN_NAME)
Example:SQL> CREATE TABLE PRODUCT(P_ID NUMBER(5) CONSTRAINT PD_ID_PK PRIMARY KEY, P_NAME
CHAR(20), S_NAME CHAR(20), U_PRICE NUMBER(10) );
SQL> CREATE TABLE ORDER_ITEMS (O_ID NUMBER(5) CONSTRAINT OD_ID_PK PRIMARY KEY, P_ID
NUMBER(5) CONSTRAINT PD_ID_FK REFERENCES PRODUCT(P_ID, P_NAME CHAR(20),
S_NAME CHAR(20), U_PRICE NUMBER(10) );
To Define Foreign Key Constraint at Table Level:
Syntax: SQL> (COLUMN_NAME DATATYPE [CONSTRAINT <CONSTRAINT_ NAME> FOREIGN KEY
(COLUMN_NAME)] REFERENCES REFERENCED_TABLE_NAME (COLUMN_NAME)
Example: SQL> CREATE TABLE ORDER_ITEMS (O_ID NUMBER(5), P_ID NUMBER(5) , P_NAME CHAR(20),
S_NAME CHAR(20), U_PRICE NUMBER(10) CONSTRAINT OD_ID_PK PRIMARY KEY (O_ID),
CONSTRAINT P_ID_FK (P_ID) REFERENCES PRODUCT(P_ID) );
5. CHECK CONSTRAINT (BUSINESS RULE INTEGRITY CONSTRAINT):
This constraint defines a business rule on a column. All the rows must satisfy this rule. The constraint can
be applied for a single column or a group of columns. To Define Check Constraint at Column Level
Syntax1: SQL> (COLUMN_NAME DATA TYPE [CONSTRAINT <CONSTRAINT_NAME>] CHECK (<CONDITION>),
Example: SQL> CREATE TABLE EMPLOYEE ( ID NUMBER(5), NAME CHAR(20), DEPT CHAR(10), AGE
NUMBER(2), SAL NUMBER(10,2) CHECK(SAL>=5000 AND SAL<10000) );
To Define Check Constraint at Table Level:
3rd Sem 924 66 666 46 1
DATA BASE MANAGEMENT SYSTEM BY Jagadeesh Software Solutions
Example: SQL> CREATE TABLE EMPLOYEE ( ID NUMBER(5), NAME CHAR(20), , DEPT CHAR(10), AGE
NUMBER(2), SAL NUMBER(10,2) CONSTRAINT JACK CHECK (AGE>=18 AND AGE<65) );
6. DEFAULT CONSTRAINT: The Default constraint is used to insert a default value into a column. The default value
will be added to all new records. When user does not enter anything in that column then that column will have the
default value. Default constraints are ANSI -standard constraints you can assign to a column either with the
CREATE TABLE or ALTER TABLE statements. To Define Default Constraint at column level:
SQL JOINS: The SQL Joins clause is used to combine records from two or more tables in a database. A JOIN is a
means for combining fields from two tables by using values common to each. SQL Join is used to fetch data from
two or more tables, which is joined to appear as single set of data. Join Keyword is used in SQL queries for joining
two or more tables. Minimum required condition for joining table, is(n-1) where n, is number of tables.
ORDERS TABLE
OrderID CustomerID OrderDate
10308 2 2017-07-11
10309 37 2017-07-12
10310 77 2017-07-13
CUSTOMERS TABLE
CustomerID CustomerName ContactName Country
1 JAGADEESH JACK INDIA
2 RADHIKA ROSE INDIA
3 SATYAVATHI PEARL INDIA
DIFFERENT TYPES OF SQL JOINS: Here are the different types of the JOINs in SQL
1. (INNER) JOIN ( INNER JOIN or EQUI JOIN ) : Returns rows when there is a match in both tables
2. LEFT (OUTER) JOIN: Returns all rows from the left table, even if there are no matches in the right table.
3. RIGHT (OUTER) JOIN: Returns all rows from the right table, even if there are no matches in the left table.
4. FULL (OUTER) JOIN: Returns rows when there is a match in one of the tables.
3rd Sem 924 66 666 46 1
DATA BASE MANAGEMENT SYSTEM BY Jagadeesh Software Solutions
5. SELF JOIN: It is used to join a table to itself as if the table were two tables, temporarily renaming at least
one table in the SQL statement.
6. CARTESIAN JOIN(CROSS JOIN): Returns the Cartesian product of the sets of records from the two or
more joined tables.
7. NATURAL JOIN: Natural Join is a type of Inner join which is based on column having same name and same
datatype present in both the tables to be joined.
1. SQL INNER JOIN ( INNER JOIN or EQUI JOIN ): In SQL, The INNER JOIN returns rows when there is a match in
both tables. The INNER JOIN keyword selects records that have matching values in both tables.
Syntax: SQL> SELECT COLUMN_NAME(S) FROM TABLE1
INNER JOIN TABLE2 ON TABLE1.COLUMN_NAME = TABLE2.COLUMN_NAME;
Example: SQL> SELECT ORDERS.ORDERID, CUSTOMERS.CUSTOMERNAME FROM ORDERS
INNER JOIN CUSTOMERS ON ORDERS.CUSTOMERID = CUSTOMERS.CUSTOMERID;
SELECTION FROM THE "ORDERS" TABLE
OrderID CustomerID EmployeeID OrderDate ShipperID
10308 2 7 2017-07-11 3
10309 37 3 2017-07-12 1
10310 77 8 2017-07-13 2
2. SQL LEFT JOIN: In SQL, LEFT JOIN Returns all rows from the left table, even if there are no matches in the
right table. The LEFT JOIN keyword returns all records from the left table (table1), and the matched records from
the right table (table2). The result is NULL from the right side, if there is no match. In some databases LEFT JOIN
is called LEFT OUTER JOIN.
Syntax: SQL> SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.column_name =
table2.column_name;
Example: SQL> SELECT CUSTOMERS.CustomerName, ORDERS.OrderID FROM CUSTOMERS LEFT JOIN ORDERS
3. SQL RIGHT JOIN: RIGHT JOIN returns all rows from the right table, even if there are no matches in the left
table. The RIGHT JOIN keyword returns all records from the right table (table2), and the matched records from
the left table (table1). The result is NULL from the left side, when there is no match. In some databases RIGHT
JOIN is called RIGHT OUTER JOIN.
Syntax: SQL> SELECT COLUMN_NAME(S) FROM TABLE1 RIGHT JOIN TABLE2 ON
TABLE1.COLUMN_NAME = TABLE2.COLUMN_NAME ;
Example: SQL> SELECT ORDERS.ORDERID, EMPLOYEES.LASTNAME, EMPLOYEES.FIRSTNAME FROM ORDERS
RIGHT JOIN EMPLOYEES ON ORDERS.EMPLOYEEID = EMPLOYEES.EMPLOYEEID ORDER BY
ORDERS.ORDERID;
4. SQL FULL OUTER JOIN: The FULL OUTER JOIN returns rows when there is a match in one of the tables. It return
all records when there is a match in either left (table1) or right (table2) table records. FULL OUTER JOIN can
return very large result-sets
Syntax: SQL> SELECT COLUMN_NAME(S) FROM TABLE1 FULL OUTER JOIN TABLE2 ON
TABLE1.COLUMN_NAME = TABLE2.COLUMN_NAME;
Example: SQL> SELECT CUSTOMERS.CUSTOMERNAME, ORDERS.ORDERID FROM CUSTOMERS FULL OUTER JOIN
3rd Sem 924 66 666 46 1
DATA BASE MANAGEMENT SYSTEM BY Jagadeesh Software Solutions
5. SQL SELF JOIN: A table can also join to itself known as, Self Join. A self JOIN is a regular join, but the table is
joined with itself.
Syntax: SQL> SELECT COLUMN_NAME(S) FROM TABLE1 T1, TABLE1 T2 WHERE CONDITION;
6. CROSS JOIN OR CARTESIAN PRODUCT: This type of JOIN returns the cartesian product of rows from the tables in
Join. It will return a table which consists of records which combines each row from the first table with each row of
the second table.
Syntax: SQL> SELECT COLUMN-NAME-LIST FROM TABLE-NAME1 CROSS JOIN TABLE-NAME2 ;
7. NATURAL JOIN: Natural Join is a type of Inner join which is based on column having same name and same
datatype present in both the tables to be joined.
Syntax: SQL> SELECT * FROM TABLE-NAME1 NATURAL JOIN TABLE-NAME2;
3rd Sem 924 66 666 46 1
DATA BASE MANAGEMENT SYSTEM BY Jagadeesh Software Solutions
In the above example, both the tables being joined have ID column(same name and same datatype ), hence the
records for which value of ID matches in both the tables will be the result of Natural Join of these two tables
SET OPERATORS: Set operators combine the results of two component queries into a single result. Queries
containing set operators are called compound queries. The following table lists SQL set
operators. SQL supports few Set operations to be performed on
table data. These are used to get meaningful results from data,
under different special conditions.
OPERATOR RETURNS
UNION All distinct rows selected by either query
UNION ALL All rows selected by either query, including all duplicates
INTERSECT All distinct rows selected by both queries
MINUS All distinct rows selected by the first query but not the second
1. UNION: UNION is used to combine the results of two or more Select statements. However it will eliminate
duplicate rows from its result set. In case of union, number of columns and datatype must be same in both the
tables.
Example:
2. UNION ALL: This operation is similar to Union. But it also shows the duplicate rows.
Example:
THE FIRST TABLE
ID NAME
1 JAGADEESH
2 RADHIKA
Example: SQL> SELECT * FROM FIRST UNION ALL SELECT * FROM SECOND;
3. INTERSECT: Intersect operation is used to combine two SELECT statements, but it only returns the records
which are common from both SELECT statements. In case of Intersect the number of columns and datatype must
be same.
Example:
4. MINUS: Minus operation combines result of two Select statements and return only those result which belongs to
first set of result. MySQL does not support INTERSECT operator.
Example:
THE FIRST TABLE
ID NAME
1 JAGADEESH
2 RADHIKA
SQL VIEWS: The SQL VIEW is a virtual table that does not physically exist. Iit is created by a SQL statement that
joins one or more tables. A view in SQL is a logical subset of data from one or more tables. View is used to restrict
data access. A view is actually a composition of a table in the form of a predefined SQL query. A view can contain
all rows of a table or select rows from a table. which are a type of virtual tables allow users to do the following
1. Structure data in a way that users or classes of users find natural or intuitive.
2. Restrict access to the data in such a way that a user can see and (sometimes) modify exactly what they need
and no more.
3. Summarize data from various tables which can be used to generate reports.
TYPES OF VIEWS: There are two types of view,
CREATING VIEWS: Database views are created using the CREATE VIEW statement. Views can be created from a single
table, multiple tables or another view. To create a view, a user must have the appropriate system privilege
according to the specific implementation.
Syntax: SQL> CREATE OR REPLACE VIEW VIEW_NAME AS SELECT COLUMN_NAME(S) FROM TABLE_NAME
WHERE CONDITION;
Example: SQL> CREATE OR REPLACE VIEW SALE_VIEW AS SELECT * FROM SALE WHERE CUSTOMER = 'JAGADEESH';
Consider Following Sale Table
OID ORDER_NAME PREVIOUS_BALANCE CUSTOMER
11 ORD1 2000 JAGADEESH
12 ORD2 1000 RADHIKA
13 ORD3 2000 SATYA
14 ORD4 1000 RADHIKA
15 ORD5 2000 JAGADEESH
The data fetched from select statement will be stored in another object called sale_view. We can use create
separately and replace too but using both together works better.
Example: SQL> SELECT * FROM SALE_VIEW;
CREATION OF FORCE VIEW: FORCE keyword is used while creating a view. This keyword force to create View
even if the table does not exist. After creating a force View if we create the base table and enter values in it, the
view will be automatically updated.
Syntax: SQL> CREATE OR REPLACE FORCE VIEW VIEW_NAME AS SELECT COLUMN_NAME(S) FROM TABLE_NAME;
UPDATE A VIEW: Update command for view is same as for tables. If we update a view it also updates base table
data automatically.
Syntax: SQL> UPDATE VIEW-NAME SET VALUE WHERE <CONDITION>;
READ-ONLY VIEW: We can create a view with read-only option to restrict access to the view. The below syntax will
create view for read-only purpose, we cannot UPDATE or INSERT data into read-only view. It will throw an error.
Syntax: SQL> CREATE OR REPLACE FORCE VIEW VIEW_NAME AS SELECT COLUMN_NAME(S) FROM
TABLE_NAME WHERE CONDITION WITH READ-ONLY;
DROPPING VIEWS: Once a SQL VIEW has been created, you can drop it with the SQL DROP VIEW Statement.
Syntax: SQL> DROP VIEW VIEW_NAME;
Example: SQL> DROP VIEW CUSTOMERS_VIEW;
The above example drop the CUSTOMERS_VIEW from the CUSTOMERS table. ]
SQL SUBQUERY: A subquery is used to return data that will be used in the main query as a condition to further
restrict the data to be retrieved. Subquery or Inner query or Nested query is query within another SQL query and
embedded within the WHERE clause of the SQL statement. A subquery is used when you know how to search for
3rd Sem 924 66 666 46 1
DATA BASE MANAGEMENT SYSTEM BY Jagadeesh Software Solutions
a value using a SELECT statement, but do not know the exact value in the database. Subqueries are an alternate
way of returning data from multiple tables. Subqueries can be used with the following SQL statements along with
the comparision operators like =, <, >, >=, <= etc. Subqueries can be used with the SELECT, INSERT, UPDATE,
and DELETE statements along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
SUBQUERY-INSERT STATEMENT: Subquery can be used with INSERT statement to add rows of data from one
or more tables to another table. To group all the students who study Maths in a table 'maths_group'.
Example: SQL> INSERT INTO MATHS_GROUP(ID, NAME) SELECT ID,FIRST_NAME || ' ' || LAST_NAME FROM
STUDENT_DETAILS WHERE SUBJECT='MATHS';
CORRELATED SUBQUERY: A query is called correlated subquery when both the inner query and the outer query
are interdependent. For every row processed by the inner query, the outer query is processed as well. The inner
query depends on the outer query before it can be processed.
Example: SQL> SELECT P.PRODUCT_NAME PRODUCT P WHERE P.PRODUCT_ID = ( SELECT O.PRODUCT_ID
FROM ORDER_ITEMS O WHERE O.PRODUCT_ID = P.PRODUCT_ID );
NESTED SUBQUERY: We can nest as many queries but it is recommended not to nest more than 16 subqueries
in oracle.
NON-CORELATED SUBQUERY: If a subquery is not dependent on the outer query it is called a non-correlated
subquery
EMBEDDED SQL: Embedded SQL is a method of combining the computing power of a programming
language and the database manipulation capabilities of SQL. embedded SQL is the one which combines the high
level language with the DB language like SQL. It allows the application languages to communicate with DB and
get requested result. The high level languages which supports embedding SQLs within it are also known as host
language. There are different host languages which support embedding SQL within it like C, C++, ADA, Pascal,
3rd Sem 924 66 666 46 1
DATA BASE MANAGEMENT SYSTEM BY Jagadeesh Software Solutions
FORTRAN, Java etc. When SQL is embedded within C or C++, then it is known as Pro*C/C++ or simply Pro*C
language. Pro*C is the most commonly used embedded SQL
COUNT FUNCTION:
1. COUNT function is used to Count the number of rows in a database table. It can work on both numeric and
non-numeric data types.
2. COUNT function uses the COUNT(*) that returns the count of all the rows in a specified table. COUNT(*)
considers duplicate and Null.
Syntax : COUNT(*) or COUNT( [ALL|DISTINCT] expression )
Example: COUNT():SELECT COUNT(*) FROM PRODUCT_MAST;
Example: COUNT with WHERE: SELECT COUNT(*) FROM PRODUCT_MAST; WHERE RATE>=20;
Example: COUNT() with DISTINCT :SELECT COUNT(DISTINCT COMPANY) FROM PRODUCT_MAST;
Example:: COUNT() with GROUP BY:SELECT COMPANY, COUNT(*) FROM PRODUCT_MAST GROUP BY COMPANY;
Example: COUNT() with HAVING:
SELECT COMPANY, COUNT(*) FROM PRODUCT_MAST GROUP BY COMPANY HAVING COUNT(*)>2;
SUM FUNCTION: Sum function is used to calculate the sum of all selected columns. It works on numeric fields only.
Syntax: SUM() or SUM( [ALL|DISTINCT] expression )
AVG FUNCTION: The AVG function is used to calculate the average value of the numeric type. AVG function
returns the average of all non-Null values.
MAX FUNCTION: MAX function is used to find the maximum value of a certain column. This function determines
MIN FUNCTION: MIN function is used to find the minimum value of a certain column. This function determines the
smallest value of all selected values of a column.
Syntax: MIN() or MIN( [ALL|DISTINCT] expression )
Example: SELECT MIN(RATE) FROM PRODUCT_MAST;