Bcom 4sem Dbms Withoracle Ok
Bcom 4sem Dbms Withoracle Ok
BCOM – 4 SEMESTER
Unit 4: BASIC SQL: SQL data types, SQL literals, operators, DDL operations
(create, alter, drop), DML operations (insert, delete, update), queries,
aggregate functions, TCL operations: commit, Rollback, Savepoint , DCL
operations: Grant, Revoke
UNIT – I
Data:
1. Data is the raw set of facts such as – customer name, phone number, date
of birth, or price of a book, etc.
2. There are various kinds of data that can be stored and processed in a
computer –
numbers, characters,
text,
images,
audio and
video.
3. The data is stored in the computer in binary form (1s or 0s), which
can be processed and stored digitally.
4. The smallest piece of data that can be recognized by the
computer is a single character. A single character requires one Byte of
memory space.
5. Data can be generated by:
Humans
Machines
Human-Machine combines.
Data processing:
1. Data Acquisition: This stage includes the methods used to collect raw
data from various sources.
2. Data Preparation: This stage involves tasks like identifying and handling
missing values, correcting inconsistencies, formatting data into a consistent
structure.
3. Data Input: The pre-processed data is loaded into a system suitable for
further processing and analysis.
4. Data Processing: The data undergoes various manipulations and
transformations to extract valuable information.
5. Data Output: The transformed data(output) is then analyzed using various
techniques to generate insights and knowledge. This could involve
statistical analysis or visualization techniques.
6. Data Storage: The processed data and the generated outputs are stored in
a secure and accessible format for future use.
The data processing cycle is iterative, meaning the output from one stage can
become the input for another.
Data processing commonly occurs in stages, and therefore the “processed data”
from one stage could also be considered as the “raw data” of subsequent stages.
Information:
Data Information
PROCESSING
(Input) (Output)
5. Examples of information:
FILE
1.Data:
DATA
2.Field:
3.Record:
4.File:
Example:
In File Processing System (FPS) the Records and the Fields in a STUDENT data file
Using the CUSTOMER data file, the data processing specialist developed
programs that produced very useful reports.
Some of the reports produced by the File processing system are given below –
FILE MANAGEMENT
PROGRAMS
FILE REPORT
PROGRAMS
FILE MANAGEMENT
PROGRAMS
AGENT FILE
FILE REPORT
PROGRAMS
As the number of files increases, a small file system is developed for the
Insurance Company. Each data file in the file system uses its own
programs to store and modify the data. In the File system, a large number
of data files are needed to perform various tasks.
1. More programming
2. File management
3. Modifications
4. Security features
5. Structural and Data dependency
6. Data sharing
7. Data Redundancy
8. Data Inconsistency
9. Data Anomalies
1.More programming :
The traditional File Processing Systems (FPS) were developed using Third
Generation Languages (3GL) like – COBOL, PASCAL, BASIC, FORTRAN, etc...
Each file in the file system uses its own programs to store and modify data. That is,
every data file has its own file management programs and file report programs.
2.File Management:
As the number of files increases the administration becomes very difficult. The file
management programs and file report programs on every data file requires a
execution procedure, which is very difficult.
3.Modifications:
Making changes in a existing file is very difficult. For example, in the Customer file,
the address of the Customer is to be modified. It may require programs to be
executed for opening the file, searching the customer address and finally to modify
the address.
4.Security features:
Security features such as pass word protection, the ability to modify and lock files
are very difficult. For giving access permissions such as – Reading the file, doing
modifications, deletions and inserting data in a data file requires implementing and
working with many programs.
CUSTOMER data file. With this change programs connected to the CUSTOMER
data file will not work.
Therefore all the file system programs must be modified according to the new file
structure. This shows structural dependency.
Every change in the properties of data such as – changing a field from integer to real
number requires changes in all the programs that access the file.
6.Data sharing:
Each application program contains its own data file. For example, the users in
Accounting department, cannot access the data in Sales and Customer departments.
In file system data management, data sharing is not possible.
7.Data Redundancy :
Data Redundancy exists when the same data is stored in different places.
That is,same information is stored in several files. For example, the AGENT phone
no and address are stored in both AGENT and CUSTOMER data files. Data
Redundancy leads to wastage of memory space.
8.Data Inconsistency:
The data inconsistency occurs because of data redundancy. For example, the
AGENT address is stored in two different files. Modifying the address in file will
cause data inconsistency.
9.Data Anomalies:
The data anomalies are commonly defined as follows –
Insert anomalies – The errors that occur when we insert a record.
Update anomalies – The errors that occur when we update an existing record.
Delete anomalies - The errors that occur when we delete an existing record.
6. Example:
Consider the following table –
EMPLOYEE
Meta data:
Data
base
END
USER
USER
8:Objectives of DBMS:
A Data Base Management System consists of –
A collection of interrelated and persistent data (data base).
A set of programs used to access, update and manage data.
1. Data availability
2. Data integrity
3. Data security
4. Data independence.
5. Data backup and recovery
1.Data availability:
The database contains large amounts of data. The DBMS provides facilities for
the end users to access data in the database very easily.
A query is the request to the DBMS for data retrieval. For example, to read or
update the data.
2.Data integrity:
DBMS supports data integrity. Data Integrity means that the data contained in the
database is both accurate and consistent.
3.Data security:
LOGIN
USER NAME :
PASS WORD :
OK CANCEL
Data security rules provides the users to access the data base and which data
base operations (add, read, modify, or delete) the user can perform.
The DBMS provides a strong security system for users data security. The data base
users are identified to the DBMS through a user name and pass word.
4.Data independence:
The DBMS provides an abstract view of the data stored in the database. The
separation of data descriptions (Meta data) from application programs is called Data
Independence.
Data Independence helps to change the data without changing the application
programs that process the data.
5. Data Backup and recovery:
The DBMS should provide a backup facility to restore the database. The backup
facility produces a copy of the entire database in another location. Sometimes
database failure occurs, and then the backup copy is used to restore (recover)
the database.
classification of DBMS:
1. Number of users
2. Data base location
3. Data usage
Number of users:-
A Single user database supports only one user at a time. If user ‘A’, is
the using the data base, users B and C must wait until the user A
completes the work.
Multi-user database:
A Multi-User Database supports multiple users at the same time.
The Multi-User Database is divided into two types. They are –
Work group database:
When the multiuser database supports a small number of users
(group) then the database is called “workgroup” database.
enterprise database:
When the database is used by the entire organization and
supports many users then the database is called “enterprise”
database.
Distributed networks are normally used in the networks like Internet or any
other network.
Distributed database
Data usage:
Operational database:
Datawarehouse:
LOGIN
USER NAME :
PASS WORD :
OK CANCEL
The DBMS provides a strong security system for user’s data security. The data
base users are identified to the DBMS through a user name and pass word.
5.Multi-user access control:
UNIT -2
1. Advantages of DBMS:
The Data Base Management System is a collection of programs that
manages the database structure and controls access to the data stored in the
data base.
The Data Base Management System presents the end user with a single
(or) integrated view of the data in the data base.
The following are the advantages of DBMS -
1. Improved data access.
2. Improved data security
3. Program-Data Independence.
4. Data-Integration
5. Improved Data sharing
6. Minimized data Inconsistency
7. Improved decision making
1.Improved data access:
The database contains large amount of data. The DBMS provides facilities for the
end user to access data in the database very easily.
A Query is the request for the DBMS for data retrieval. For example, to read or
update the data.
2.Improved data security:
Data security rules provides the users to access the data base and which data
base operations (add, read, modify, or delete) the user can perform.
LOGIN
USER NAME :
PASS WORD :
OK CANCEL
The DBMS provides a strong security system for users data security. The data
base users are identified to the DBMS through a user name and pass word.
3.Program - Data independence:
The DBMS provides an abstract view of the data stored in the database. The
separation of data descriptions (Meta data) from application programs is called
Data Independence.
Data Independence helps to change the data without changing the application
programs that process the data.
4.Data-Integration:
Data Base Management System provides an integral view of the organization’s
operations. It becomes much easier to see how actions in one department of the
organization influence other departments.
FINANCE
DEPARTMENT
MARKETING
DEPARTMENT DATA Integral
INTEGRATION END
USER
view of the
SALES
DEPARTMENT data base
There are three types of Software’s are needed in data base environment they
are
3.Database users:
Database users are categorized based up on their interaction with the
database. The various types of database users in DBMS -
Data base
Administrator
(DBA)
Installing and
Design and Backup & data base
upgrading the Documenation
implementation Recovery Security
DBMS services
DBA is the one having privileges to perform DCL (Data Control Language)
operations such as GRANT and REVOKE, to allow/restrict a particular user
from accessing the database.
2,System Analyst:
System Analyst is a user who analyses the requirements of the end users.
They check whether all the requirements of end users are satisfied.
3.Database Designers: Data Base Designers are the users who design
the structure of database which includes tables, indexes, views, triggers,
stored procedures and constraints which are usually enforced before the
database is created or populated with data.
It is responsibility of Database Designers to understand the requirements of
different user groups and then create a design which satisfies the need of
all the user groups.
4.Application Programmers: Application Programmers also referred as
System Analysts or simply Software Engineers, are the back-end
programmers who writes the code for the application programs. They are
the computer professionals. These programs could be written in
Programming languages such as Visual Basic, C, C++ , java , PHP, python
etc.
A table is a two dimensional structure contains rows & columns. The data is
stored in these rows and columns. A table is also called relation.
Example: consider the following STUDENT table
Field
are attributes
2) Relational db Schema: A database schema is the logical
representation of a database, which shows how the data is stored
logically in the entire database.
Example:
Schema of STUDENT table(relation) -
8) Relation Key: These are basically the keys that are used to identify
the rows uniquely or also help in identifying data in the tables.
o Primary Key
o Candidate Key
o Super Key
o Foreign Key
o Alternate Key
o Composite Key
5. Codd’s Rules:
Dr.E.F.Codd’s defined a list of 12 rules to define a Relational data base
System. Any Data base system that follows these rules can be called as Relational data
base system.
The following are the 12 rules proposed by Dr.E.F.Codd –
1. Information
2. Guaranteed access
3. Systematic treatment of Nulls
4. Usage of meta data
5. Data sublanguage
6. View updating
7. High level insert, update and delete
8. Physical data independence
9. Logical data independence
10. Integrity independence
11. Distributed database
12. Non-sub version
Rule :1 : Information:
Null values are supported in relational data base management system. Nulls
must be represented and treated in a systematic way.
Metadata means data about data. The meta data must be stored and
managed. The metadata must be available to the authorized users.
The relational data base may support many languages. It must support one
well defined language for –
The database must support insertion, deletion, and updation at the table
level.
Application programs are unaffected when changes are made to the storage
structures. That is, The changes to the physical level (how the data is stored)
must not require a change in programs.
Rule :9 : Logical data Independence:
Application programs are unaffected when changes are made to the table
structures . For example, changing the order of the column or inserting
columns.That is, changes to the logical level (adding columns, changing
column lengths etc.) must not require a change in programs.
The end users and application programs are unaware and unaffected by the
data location.
If the system supports low-level access to the data, there must not be a way
to bypass the integrity rules of the data.
1.Super Key
1. The set of attributes that can uniquely identify a tuple is known as Super
Key.
2. Example:
STUD_NO, (STUD_NO, STUD_NAME), etc.
3. A super key is a group of single or multiple keys that identifies rows in a
table. It supports NULL values.
4. Adding zero or more attributes to the candidate key generates the super
key. A candidate key is a super key but vice versa is not true.
5. Super Key values may also be NULL.
Example:
Table STUDENT
STUD_NO SNAME ADDRESS PHONE
3.Primary Key
There can be more than one candidate key in relation out of which one can be
chosen as the primary key. For Example, STUD_NO, as well as STUD_PHONE,
are candidate keys for relation STUDENT but STUD_NO can be chosen as
the primary key (only one out of many candidate keys).
It is a unique key.
It can identify only one tuple (a record) at a time.
It has no duplicate values, it has unique values.
It cannot be NULL.
Primary keys are not necessarily to be a single column; more than one
column can also be a primary key for a table.
Example:
STUDENT table Student(STUD_NO, SNAME, ADDRESS, PHONE)
STUD_NO is a primary key
Table STUDENT
PK
STUD_N SNAM ADDRES
O E S PHONE
998855221
1000 Teju Nellore
1
959565656
1001 Arun Gudur
5
969669696
1002 Venu Kavali
9
949401010
1003 Anil nellore
1
4.Alternate Key
The candidate key other than the primary key is called an alternate key.
All the keys which are not primary keys are called alternate keys.
It is a secondary key.
It contains two or more fields to identify two or more records.
These values are repeated.
Example: SNAME, and ADDRESS are Alternate keys
Example:
Consider the table shown above.STUD_NO, as well as PHONE both, are
candidate keys for relation STUDENT but PHONE will be an alternate key (only
one out of many candidate keys).
5.Foreign Key
If an attribute can only take the values which are present as values of some other
attribute, it will be a foreign key to the attribute to which it refers. The relation
which is being referenced is called referenced relation and the corresponding
attribute is called referenced attribute. The referenced attribute of the referenced
relation should be the primary key to it.
It is a key it acts as a primary key in one table and it acts as
secondary key in another table.
It combines two or more relations (tables) at a time.
They act as a cross-reference between the tables.
Example:
TABLE : DEPARTMENT
PRIMARY KEY : DEPT ID
PK
DEPTID DNAME HOD
10 MCA SUNDER
20 MSC MADHU
30 MBA UDAY
40 MCOM SINGH
TABLE : STUDENT
PRIMARY KEY : STUD_NO
FOREIGN KEY : DEPTID
PK FK
The primary key –deptid in the DEPARTMENT table, appears as foreign key in
the related table STUDENT.
6.Composite Key:
Sometimes, a table might not have a single column/attribute that uniquely
identifies all the records of a table. To uniquely identify rows of a table, a
combination of two or more columns/attributes can be used. Sometimes it may
contain duplicate values also. So, we need to find the optimal set of attributes
that can uniquely identify rows in a table.
7.Integrity Constraints:
An integrity constraint is a rule that cannot be violated by the user. The
constraints are used to prevent invalid data entry into the table. It enforces rules
for the columns in a table. In SQL the integrity constraints are classified into 3
types. They are
1) Domain integrity constraints
2) Referential integrity constraints
3) Entity Integrity constraints
Domain integrity constraints:-
A domain is a set of values, that may be assigned to a column. The domain
integrity constraints enforces valid entries for a given column from the set of
possible values. The domain constraints are of 2 types. They are
i) NOT NULL constraints
ii) CHECK constraints
NOT NULL:-
The value which is absent is called NULL. This constraint is used to avoid the
NULL values in a column of a table. i.e if any column is specified as NOT NULL,
then we must have to enter a value for the NOT NULL constraint allows the
duplicate(redundant) values.
Ex:- 1 Create table student(htno number(5) not null, sname varchar(20), address
varchar(20));
In the above example the column htno does not allow NULL values. But other
sname, address is allows NULL values. Suppose we can add the NOT NULL
constraint after creating the table then we can use Alter table command i.e
Alter table student modify sname not null;
CHECK:-
The check constraint is used to specify a condition that should satisfy for each
row in a table before it is stored.
Ex:- create table student(htno number(5), sname varchar(20), fee number(7,3)
check(fee>0)); Suppose we can add the Check constraint after creating the table
then we can use Alter table command i.e
Ex:- alter table student add check(sname like ‘s%’);
Entity integrity constraints:-
These are also used to prevent invalid data into a column of a table. Mainly
entity integrity constraints are divided into 2 types. They are
i) Unique constraint
ii) Primary Key constraint
Unique Constraint:-
It is used to prevent duplicate values. Any column declared with “unique”
constraint in that column does not allow duplicate values. how ever it allows null
values into the column
Ex:- Create table student(htno number(8) unique, sname varchar(10),address
varchar(20));
Suppose we can add the Unique constraint after creating the table then we can
use Alter table command i.e
Alter table student add unique(fee);
Primary Key:-
A field or combination of fields used for identifying a single record will be
called as “Primary key”.
The primary key constraint does not allow duplicate and NULL values.
Only one primary key constraint can be created for each table.
The key word primary key is used to define a primary key.
Example:-1
Create table student(htno number(5) primary key, sname varchar(15), address
varchar(20));
Example:2:-
Example:-
DEPARTMENT TABLE
Create table deptartment(deptid number(5) primary key, dname varchar(10), hod
varchar(15));
STUDENT TABLE
Create table student (studno number(5) primary key, sname varchar(15),
phone number(10), deptid number(5) references dept(deptid));
TABLE : DEPARTMENT
PRIMARY KEY : DEPTID
PK
DEPTID DNAME HOD
10 MCA SUNDER
20 MSC MADHU
30 MBA UDAY
40 MCOM SINGH
TABLE : STUDENT
PRIMARY KEY : STUDNO
FOREIGN KEY : DEPTID
PK FK
SNAM
STUDNO E PHONE DEPTID
The primary key –deptid in the DEPARTMENT table, appears as foreign key in
the related table STUDENT.
The records from the Master table will not be deleted until the corresponding
records are deleted from the detail table. Similarly new records can not be
inserted into the detail table, until the corresponding values are inserted in the
master table.
UNIT - 3
ENTITY-RELATIONSHIP MODEL(ER-MODEL)
1.INTRODUCTION TO ER-MODEL:
1. Peter Chen developed the ER diagram in 1976.
2. The ER model was created to provide a simple and understandable
model for representing the structure and logic of databases.
3. The Entity Relationship Diagram explains the relationship among the
entities present in the database.
4. ER diagrams provides the real-world modeling of objects.
5. ER- Diagram contains three basic components – Entity, attributes,
Relationships.
symbols used in ER Diagrams:
1. Entity:
An entity is a thing, a person or an event about which data is to be
collected and stored.
An entity represents a particular type of object in the real world.
Entities are distinguishable i.e., each entity occurrence is unique and
distinct.
An entity is represented by a Rectangle symbol.
STUDENT
2.Attributes:
An attribute is a characteristic of an entity.
In chen notation the attributes are represented by a oval symbol and are
connected to the rectangle.
Example:
Consider the student entity with the following attributes –
Rollno nameutes
course
STUDENT
3. Single-valued attribute
4. Multi-valued attribute
5. Derived attribute
3.Relationships:
A Relationship is an association between the entities.
A Relationship is denoted by a diamond symbol.
Example:
generates
CUSTOMER ORDERS
2.ATTRIBUTE CLASSIFICATION:
Simple attribute
Composite attribute
Single-valued attribute
Multi-valued attribute
Derived attribute
1.Simple Attribute:-
A Simple attribute is an attribute that cannot be subdivided into smaller
components. It is denoted by “Ellipse Symbol (oval symbol)”.
For example- age, marriage status can be considered as “simple attributes”.
2.Composite Attribute:
A Composite attribute is an attribute that can be sub-divided into additional
attributes.
The most common example, composite attribute is address, which can be
divided into components like Dno, Street, City, Pincode etc.
In the above ER-diagram mob_no and email_id are the multi-valued attributes.
Example:
4.Relationship Degree:
A Relationship degree indicates the number of entities associated with in a
Relationship.
The ER-Model supports three types of relationship degree –
1. Unary Relationship
2. Binary Relationship
3. Ternary Relationship
1.Unary Relationship:
A Unary Relationship exists when an association is maintained within a single
entity.
Example:
“ An Employee manages another Employee”. That is, an employee has
relationship with itself. Such a relationship is known as Recursive Relationship.
2.Binary Relationship:
A Binary Relationship exists when two entities are associated in a
relationship.
Binary relationships are most common.
Example:
1. “An EMPLOYEE works in a DEPARTMENT”
3.Ternary Relationships:
A Ternary Relationship exists when three entities are associated in a
Relationship.
Example:
5.Relationship Classification:
1 1
ENTITY relationship
ENTITY
Example:
Each EMPLOYEE is allotted with only one PARKING PLACE (or) each
PARKING PLACE Must be given to one EMPLOYEE.
1 1
EMPLOYEE has PARKING PLACE
1 M
ENTITY relationship
ENTITY
Example:
A PAINTER paints many PAINTINGS but each of them is painted by only
one PAINTER.
has
1 M
EMPLOYEE PARKING PLACE
M M
ENTITY relationship
ENTITY
Example:
“ An EMPLOYEE can learn many COURSES , a COURSE can be learned by
many EMPLOYEES.”
M M
EMPLOYEE learns COURSES
1. Introduction-Commands in SQL:
Introduction to SQL:- (Q: What is SQL ? )
4. Delete
3) Data Control Language(DCL):
1. Grant
2. Revoke
4)Transaction Control Language (TCL):
1. Commit
2. Rollback
3. Savepoint
2.SQL Literals :
Literals are explicit representations of data in expressions. They are used in SQL
statements to represent data that does not change.
The following literals are used in SQL –
1. Numeric literals
2. Boolean literals
3. Date literals
4. String literals
1. Numeric Literals:
Both integer and floating-point numbers are represented by numerals.
These numerals may be preceded by either a plus character (+) or a minus
character (–) to denote sign.
Floating-point values use a period to separate the whole number part from the
decimal part. We cannot use a comma as a decimal point.
The following values are examples of numeric literals:
1000
10.0
-3456.43
3454324.9378
Example:
The following is an example of a query with a Numeric literal:
update student set course=’B.Sc’ where sno=101;
2. Boolean Literals:
The Boolean value True is represented as 1 and a Boolean False is
represented as 0.
We can use the keywords TRUE instead of 1 and FALSE instead of 0.
3. String Literals
A string literal is a sequence of one or more characters enclosed in single
quotation marks.
Any printable character can appear in a string literal.
The following are examples of string literals:
'india’
‘university’
Example:
The following is an example of a query with a string literal:
SELECT "Customer ID" FROM CUSTOMER WHERE State = 'ANDHRA PRADESH';
This query selects the Customer ID field from the CUSTOMER table for all
customers whose State field contains an exact match to the characters ANDHRA
PRADESH.
4.Date Literals :
Literal date values are enclosed in single quotes, and use the current date
format setting.
Example:
'04/15/2017'
Here ‘l’ specifies the length and ‘d’ specifies the no of decimal places with in the
length. The length should be in the range from 1 to 38. The default length is ‘38’
digits.
Ex:- rollno number(5)
price number(8,5)
2) Char:- The Char data type is used to store fixed length character data.
Syntax: char (size);
Here size indicates the maximum no of characters
Ex: name char(10)
3) Varchar2:- The “Varchar2” data type is similar to “Char” data type. It is used
to store variable length strings. The maximum no of characters that can be
entered is 4000 bytes.
Syntax:- Varchar2(size)
Here size indicates the maximum no of characters.
Ex: name varchar(10)
Example:
1. name char(10)
I N D I A
10 Memory locations are allocated for the fixed length character data.
2. name varchar2(10)
I N D I A
6) Large Objects :- This data type occupies 4GB memory. These objects are
used to store the binary data and character data. These are two types -
1) BLOB- Binary Large Objects
2) CLOB - Character Large Objects
Example: using SQL DATA TYPES :
In a table each column is identified by a column name and a given data type with
specified width. Data types are used to define columns in a table.
1.Student table:
Create table student(htno number(8) primary key,
name varchar2(15),
course varchar2(6),
phno number(10));
2. Customer table:
4.Operators in SQL
SQL supports following types of operators -
1. Arithmetic operators
2. Relational operators (comparison)
3. Logical operators
4. Special operators
1.Arithmetic operators:-
In sql the arithmetic operators are used to perform various arithmetic operators
on the data. The different types of arithmetic operators are –
OPERATOR MEANING
+ Addition
- Subtraction
* Multiplication
/ Division
^ (OR) ** Raise to the power of
Example:-
SQL query to display employee salaries increased by 10%.
select eno,ename, sal+(sal*10/100) from empolye;
2.Relational Operators:-
Relational operators are used to compare two values. The operators are also
called as comparison operators. The relational operators supported by SQL are -
OPERATOR MEANING
= Equal to
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
<> (or) != Not Equal to
Example:
Logical Operators:-
The Logical Operators are used to combine two or more relational expressions.
These operators are also called as “compound operators”.
The logical operators supported in SQL are –
1. AND.
2. OR.
3. NOT.
Example:-
select * from employe where sal>=2000 and job=‘MANAGER’;
The above example retrieve the data from the emp table by using where clause
i.e sal>=2000 and job= ‘MANAGER’;
Special Operators:-
The SQL allows special operators can be used with “where” clause of select
command.
The special operators supported by SQL are -
1. Between
2. Is null
3. Like
4. In
1) Between:-
Between operator is used to check whether a column value is with in a range.
Example:-
Select *from emp where sal between 2000 and 5000;
The above example retrieve the data from emp table, whose salary are between
2000 and 5000.
2) Is Null :-
IS NULL operator is used to check for the Null values in a column.
Example:-
select eno,ename,comm from empolye where comm is null;
3) Like:-
Like operator is used to check whether a column value matches a given
character string. It is only used for character pattern.
%(any character)
_ (underscore) (one character)
Ex:-1) Select *from emp where ename like ‘A%’;
This example displays the ‘ename’ whose employee name must be starts
with A and remaining letters should be any.
Ex:-2) select *from emp where ename like ‘_S%’;
This example displays the ‘ename’ values second character should be ‘S’
and remaining letter should be of any.
3) In:-
In operator is used to check whether a column value matches any value with in
specified list of values.
Ex:- 1) select *from emp where job in (‘manager’, ‘clerk’);
2) select *from emp where sal in (2000,3000,5000);
3. Truncate
4. Drop
1. Create :-
In SQL the database primary object is “table”.
The table contains rows and columns in which the data is stored.
In a table each column is identified by a column name and a given data type
with specified width.
COLUMNS
Syntax:
Create table <table-name> (Columnname1 data-type(width),
Columnname2 data type (width),….);
Example:
Create table student(htno number(8),
name varchar2(15),
phno number(10));
2.Alter:-
The alter command is used to modify the structure of the existing table. By using
the alter command we can do the following-
We can add new columns to an existing table.
We can remove the columns from an existing table
We can add and drop constraints
Adding a column:
The following command is used to add a new column to the existing table.
Syntax:-
Alter table <table-name> ADD(<column-name> data-type(width));
Example:
Alter table student add(dob date);
The above command adds new column “dob” to the Student table.
This command is used to remove the all the data permanently from the table and
free the memory space containing in the table.
Syntax:- Truncate table <table name>;
Ex:- Truncate table student;
The above command removes all the data permanently from the table “student”
but it does not remove the structure of “Student ” table.
4.Drop:-
A table can be deleted from the data base using the drop table command. All the
rows in the table are deleted and the structure is removed from the database.
Syntax:-
Drop table <table name>;
Example:- Drop table student;
The above command removes the table “Student”.
The following form of Insert command is used for inserting values into particular
columns of the table.
Syntax: insert into <table name> (field1,field2,……..) values (val1,val2……);
Example:
insert into student (sno, sname) values (1002,’rajesh’);
The above insert command is inserts only “sno, sname” values to “student” table.
Syntax for inserting Multiple rows:
The following form of Insert command can be used to enter any number of rows
into the table.
Syntax:
insert into <table name> values (‘&field1’,’&field2’,……..);
Ex:- insert into student values(‘&sno’,’&sname’,’&course’);
The above insert command takes the values for Sno, Sname, course.
2.Select :
The select command is used to retrieve (or) display the data from the
table.
we can select all columns (or) specific columns from the table.
Syntax:
select <column-list> from <table name>
[Where <condition>]
[group by <column-name>]
[having <condition>]
[order by <expression>];
Example:
1.Select *from student;
The above command displays all columns and all rows from the “student” table.
2. Select sno, sname from student;
The above command displays specific columns i.e., sno, sname and all rows
from the table “student”
3. select * from student where sno=101;
The above command displays all columns and specific rows that will satisfy the
condition sno=101;
4.Select * from student order by sname;
The above command displays all the rows from the student table in sorted order
based on column – sname.
3.Update:-
The update command is used to modify the data in a table. This command uses
“Set” clause.
Syntax :
update <table-name> set <column-name>=<value>,
[<column-name>=<value>…]
[where <condition> ];
The where condition is optional. If we don’t specify the where condition, the
update command will apply the changes to all the rows in the table.
Example:
1. Update student set course=’B.Com’;
The above update command modifies the all records(rows) in the student
table.
For modifying only the specified records(rows),
we have to use “where” clause.
2. update student set course=’B.Sc’ where sno=101;
The above command modifies only particular records that will satisfy the
condition sno=101 from the table “student”.
The above command updates HRA column of employee table with 20% of
salary.
The above command updates salary column of employee table with 20000,
for all rows where job matches with ‘MANAGER’.
4.Delete:
The delete command is used to delete the specific records (or) all records from
the table. For deleting a particular record in the table, we have to use “Where”
clause.
Syntax:
delete from <table name> [where <condition>];
Example:
1. delete from student;
The above command deletes all rows from the table
2. delete from student where sno=101;
The above command deletes specific rows that will satisfy the condition sno=101
from the table “student”.
Student table:
1. Create table student(rollno number(4) primary key,
name varchar2(15),
dob date,
city varchar2(15));
2. insert into student values(&rollno,’&name’,’&dob’,’&city’);
3. select * from student;
4. select name,dob from student;
employee table:
1. Create table employe(eno number(4) primary key,
1. ename varchar2(20),
2. sal numbe(8,2),
3. comm number(8,2));
2. insert into employe values(&eno,’&ename’,&sal,&comm.);
3. select * from employe;
4. select eno,ename,comm from empolye where comm is null;
5. write a SQL query to display employee salaries increased by 10%.
6. select eno,ename, sal+(sal*10/100) from empolye;
7. Aggregate functions:
Aggregate functions provide a single value for an entire group of table
entries.
The Aggregate functions are also known as Group functions.
The Aggregate functions available in SQL are as follows -
1. Max()
2. Min( )
3. Sum( )
4. Avg( )
5. Count( )
1) Max( ):
This function is used to find the maximum or highest value of the specified
column in a table.
Syntax:
Select max(column-name) from table-name;
Example:
select max(sal) from emp;
2) Min( ):
This function is used to find the minimum or lowest value of the specified column
in a table.
Syntax:
Select min(column-name) from table-name;
Example:
select min(sal) from emp;
3) Sum():
This function is used to find the total or sum of values in a specified column in a
table.
Syntax:
Select sum(column-name) from table-name;
Example:
select sum(sal)from emp;
4) Avg():
This function is used to find the average of specified column in a table
Syntax:
Select avg(column-name) from table-name;
Example:
Select avg(sal) from emp;
5) Count():
This function is used to count the number of rows or values.
The count( ) function can be used in three ways-
count (*):
The count(*) function counts the nulls and duplicate values. That is it counts the
number of rows.
Syntax:
Select count(*) from table-name;
Example:
select count(*) from emp;
count(<column name>):
The count(<column name>) counts the number of not null values in a column.
Syntax:
Select count(column-name) from table-name;
Example:
8.QUERIES:
Q: What is a query? Explain SQL queries in detail with examples.
(or)
Explain select command with examples.
(or)
How to retrieve data from a data base table ?
Query:
1. The query is a process that retrieves required information from the
database.
2. The SELECT command is used to query the database.
Order by:
The order by clause is used to display rows either in ascending or descending
order based on the specified columns.
Example:
Having:
Having clause is used to specify which groups are to be displayed . That is ,
restrict the groups that we want to return on the basis of aggregate functions.
Example:
Select deptno,max(sal) from emp group by deptno having max(sal) > 5000;
9: TRANSCATION CONTROL LANGUAGE(TCL):
Transaction Control Language(TCL) commands are used to
manage transactions in the database.
These are used to manage the changes made to the data in a
table by DML statements.
The following are the TCL commands -
1. Commit
2. Rollback
3. Savepoint
COMMIT:
This command is used to permanently save any transaction into the
database.
Syntax -COMMIT;
ROLLBACK:
● The ROLLBACK command to rollback those changes, if
they were not committed using the COMMIT command
Rollback;
SAVEPOINT:
Using the SAVEPOINT command in SQL, we can save the different parts
of the same transaction using different names.
EXAMPLE:
Savepoint created.
1 row deleted.
Rollback complete.
SQL> commit;
SQL> update student set deptid=10 where htno=1003;
1 row updated.
Rollback complete.
DCL commands are used to ensure security and integrity of the data stored in the
data base.
DCL commands are primarily used to implement access control on the data
stored in the database. It is implemented along the DML (Data Manipulation
Language) and DDL (Data Definition Language) commands.
Two types of DCL commands can be used by the user in SQL. These commands
are useful, especially when several users access the database. It enables the
administrator to manage access control.
1. GRANT
2. REVOKE
GRANT Command:
The GRANT command allows the user to implement other SQL commands on
the database or its objects. The primary function of the GRANT command in SQL
is to provide administrators the ability to ensure the security and integrity of the
data is maintained in the database.
EXAMPLE:
This command will allow Amar to implement the SELECT queries on the student
table. This will enable the user to read or retrieve information from the student
table.
Implementing the above statement will also limit Amar's operations. Amar won't
be able to modify the data stored in the table. It will prevent the user from user to
insert, to update, or deleting the data in the student table in the database.
REVOKE Command:
In simple language, the REVOKE command terminates the ability of the user to
perform the mentioned SQL command in the REVOKE query on the database or
its component. The primary reason for implementing the REVOKE query in the
database is to ensure the data's security and integrity.
EXAMPLE:
In the above implementation of the GRANT command, the user Amar was
provided permission to implement a SELECT query on the student table that
allowed Amar to read or retrieve the data from the table. Due to certain
circumstances, the administrator wants to revoke the above mentioned
permission.
Unit-V: PL/SQL
1. Introduction,
2. Structure of PL/SQL program
3. PL/SQL Data Types
4. PL/SQL Operators
5. Steps to create a PL/SQL Program
6. Conditional Control Statements
7. Iterative Control Statements
Introduction: -
PL/SQL is Oracle’s procedural language. It is the extension of SQL.
PL/SQL stands for procedural Language/Structured Query language.
By using PL/SQL user can pass set of SQL statements to oracle engine.
SQL
PL / SQL
Table Database User
Advantages of PL/SQL:-
Declare
Begin
Executable Section
Exception Section
End;
Declaration Block: -
Declare is a key word. In this section we declare PL/SQL variables, cursors and
local procedures.
Begin Block: -
In this block all the executable statements processing statements and control
statements will be used.
Exception Block: -
This is optional block. This block can be used when ever user wants to handle
the errors and its messages. This block starts with exception keyword.
End: -
PL/SQL program ends with a keyword called end.
Comment lines :
1) Single comment lines: ‘ –‘
2) Multiple comment lines: /*…………………….*/
Example
program: Program to find sum of two numbers.
Declare
a number;
b number;
sum number;
begin
a:=100;
b:=300;
sum:=a+b;
dbms_output.put-line(‘ The sum of a and b is ’ ||sum);
end;
Q: 3: Explain the PL/SQL data types.
PL/SQL data types:
Data type specifies the type of the data which can be stored in the specified
variable. PL/SQL supports all the data types of SQL. It supports some other data
types.
They are -
1. Boolean
2. %type
3. %rowtype
4. number
5. date
6. char
7. varchar2
1. Boolean:-
Boolean data type stores logical values. The Boolean data type can hold only
True or False. A Boolean data type doesn’t take any parameters.
Program:
begin
a:=&a;
b:=&b;
x:=(a>b);
if (x) then
dbms_output.put_line('TRUE');
else
dbms_output.put_line('FALSE');
end if;
end;
INPUT:
Enter value for a: 200
Enter value for b: 100
OUTPUT:
TRUE
2. %type:-
This data type is used to store value of column in a table. Column is identified
by %type data type.
Syntax:
VaraibleName TableName.ColumnName%Type;
Example:
heno emp.empno%type
heno is the variable name,
emp is table name,
empno is a column
%Type is data type to hold the value.
3. %rowtype:-
The %rowtype data type is used to inherit the datatype from a record type that
presents a row in a table.
Syntax:
Variablename Tablename%rowtype;
Example:
e1 emp%rowtype;
Program:
declare
salary emp.sal%type;
no number;
begin
no:=&no;
select sal into salary from emp where empno=no;
if salary>3000 then
update emp set sal=sal+100 where empno=no;
else
update emp set sal=sal+200 where empno=no;
end if;
commit;
end;
PL/SQL OPERATORS:
Arithmetic Operators:
The arithmetic operators supported by PL/SQL are as follows –
Let us assume variable A holds 10 and variable B holds 5, then –
result, that is, true or false.Following table shows all the relational operators
supported by PL/SQL.-
Operator Description
Checks if the values of two operands are equal or not, if yes then
=
condition becomes true.
Checks if the values of two operands are equal or not, if values are not
equal then condition becomes true.
<>
Checks if the value of left operand is greater than the value of right
>
operand, if yes then condition becomes true.
Checks if the value of left operand is less than the value of right
<
operand, if yes then condition becomes true.
Checks if the value of left operand is greater than or equal to the value
>=
of right operand, if yes then condition becomes true.
Checks if the value of left operand is less than or equal to the value of
<=
right operand, if yes then condition becomes true.
Comparison Operators:
Comparison operators are used for comparing one expression to another. The
result is always TRUE, FALSE or NULL.
LIKE
BETWEEN
IN
IS NULL
Logical Operators:
Logical operators work on Boolean operands and produce Boolean results.
Following table shows the Logical operators supported by PL/SQL.
Operator Description
Called the logical AND operator. If both the operands are true then
and
condition becomes true.
Called the logical OR Operator. If any of the two operands is true then
or
condition becomes true.
Called the logical NOT Operator. Used to reverse the logical state of
Not its operand. If a condition is true then Logical NOT operator will make
it false.
1. Simple if
2. If…else
3. Elsif
1) Simple if :
If the condition is true, then the statement block will be executed.
Syntax:
if <condition> then
statements;
end if;
Example:
if(marks>=35) then
dbms_output.put_line(‘PASS’);
End if;
2) if then else:-
Program :
Write a PL/SQL program to find Largest of two numbers.
Declare
a number;
b number;
begin
a:=&a;
b:=&b;
if a>b then
dbms_output.put_line(‘a is big’);
else
dbms_output.put_line(‘b is big’);
end if;
end;
2) if then elsif:
If the condition1 is “true”, the statement block-1 will be executed. When the
conditition1 is false , then condition2 is tested. if the condition2 is “true”, the
statement block-2 will be executed.
If all conditions are false then the statements belongs to the else part will be
executed.
Syntax:
if <condition1> then
statement block1;
elsif<condition2> then
statement block2;
----------
----------
else
statement n;
end if;
Program:
Declare
a number;
b number;
c number;
begin
a:=&a;
b:=&b;
c:=&c;
The sequence of statements can be executed any number of times using looping
statements.
The different types of loops in pl/sql are –
1) simple loop
2) while loop
3) for loop
Simple loop:-
Simple loop is a unconditional iterative statement. To terminate this looping
statement we must use ‘exit’ or exit when statements.
Syntax:
Loop
Statements
Exit when <condition>;
End loop;
Program :
Declare
i number;
begin
i:=1;
loop
dbms_output.put_line(i);
i:=i+1;
exit when(i>10);
End loop;
end;
While loop:-
While loop is a entry controlled loop which is used to check the condition and
executes the block of statements repeatedly until the condition is true.
Syntax :
while <condition>
Loop
Statements
End loop;
Program :
Write a PL/SQL program to print numbers upto 100.
Declare
i integer;
begin
i:=1;
while (i<=100)
loop
dbms_output.put_line(i);
i:=i+1;
end loop;
end;
For loop:-
The no of iterations for a while loop is un known until the loop terminates. The no
of iterations in a for loop is known before the loop gets executed.
Syntax:
for variable name in lower limit……..upper limit
Loop
Statements
End loop;
Program :
Write a PL/SQL program to generate mathematical table.
Declare
n number(2);
begin
n:=&n;
for i in 1..10
loop
end loop;
end;