DBMS
DBMS
Some DBMS examples include MySQL, PostgreSQL, Microsoft Access, SQL Server,
FileMaker, Oracle, RDBMS, dBASE, Clipper, and FoxPro.
SQL Languages:
This includes changes to the structure of the table like creation of table, altering table,
deleting a table etc.All DDL commands are auto-committed. That means it saves all the
changes permanently in the database.
1
Command Description
create to create new table or database
alter for alteration
truncate delete data from table
drop to drop a table
rename to rename a table
Table1(a)
DML commands are used for manipulating the data stored in the table and not the table itself.
DML commands are not auto-committed. It means changes are not permanent to database,
they can be rolled back.
Command Description
insert to insert a new row
update to update existing row
delete to delete a row
merge merging two rows or two tables
Table1(b)
These commands are to keep a check on other commands and their affect on the database.
These commands can annul changes made by other commands by rolling the data back to its
original state. It can also make any temporary change permanent.
Command Description
commit to permanently save
rollback to undo change
savepoint to save temporarily
Table1(c)
Data control language are the commands to grant and take back authority from any database
user.
2
Command Description
grant grant permission of right
revoke take back permission.
Table1(d)
Data query language is used to fetch data from tables based on conditions that can easily
apply.
Command Description
select retrieve records from one or more table
Table1(e)
3
Figure 1.1 Welcome window.
6. In the Oracle Database 10g Express Edition - Install Wizard welcome window, click
Next.
7. In the License Agreement window, select I accept and then click Next.
8. In the Choose Destination Location window, either accept the default or click Browse
to select a different installation directory. (Do not select a directory that has spaces in
its name.) Then click Next.
4
2030: Oracle Services for Microsoft Transaction Server
8080: HTTP port for the Oracle Database XE graphical user interface
If these port numbers are not currently used, then the installation uses them automatically
without prompting you. If they are in use, then you will be prompted to enter an available
port number.
10. In the Specify Database Passwords window, enter and confirm the password to use
for the SYS and SYSTEM database accounts. Then click Next.
11. In the Summary window, review the installation settings, and if you are satisfied,
click Install. Otherwise, click Back and modify the settings as necessary.
5
Figure 1.4 InstallShield Wizard Summary window.
12. In the InstallShield Wizard Complete window, to display the Database Home Page,
click Launch the Database homepage. Then click Finish.
6
PRACTICAL NO. 2
AIM: Datatype, creating tables, retrieval of rows using select statement, conditional
retrieval of rows, alter and drop statement.
Definition of Data Type: 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. Data types
define what type of data a column can contain.
Numeric Datatypes
Character Datatypes
LONG and ROW Datatypes
ROWID Datatypes
Datetime Datatypes
Large Object Datatypes
1. Number Datatypes
Datatype Description
NUMBER data type use to store numeric data.
NUMBER [ ( precision [, NUMBER data type have precision and scale.
scale ] ) Storage Range: Precision range(p) : 1 to 38 and Scale range(s) : -
84 to 127
Table 2.1
2. Character Datatypes
Character Data type use to store alphabetic/alphanumeric, following are character data types
in Oracle SQL.
7
Datatype Description Storage(Maximum)
CHAR data type use to store character data within
CHAR [ (size) ] 2000 bytes
predefined length.
NCHAR data type use to store national character
NCHAR [ (size) ] 2000 bytes
data within predefined length.
VARCHAR2 data type use to store variable strings
VARCHAR2(size) 4000 bytes
data within predefined length.
Table 2.2
LONG and ROW data type store variable strings data within predefined length, This
datatypes use for backward compatibility. Following are LONG and ROW datatypes in
Oracle SQL.
RAW(size) RAW data type use to store binary data i.e. image, graphics etc. 2000 bytes
Table2.3
4. Date/Time Datatypes
Variable that has date/time data type hold value call datetimes. Oracle SQL automatically
converts character value in to default date format ('DD-MON-YY') TO_DATE values.
Following are Date/Time data types in Oracle SQL.
8
Datatype Description Range
DATE data type to store valid date-time format with fixed
Jan1,4712BCtoDec
DATE length. Starting date from Jan1,4712 BC to
31, 9999 AD
Dec31,9999AD.
Table 2.4
LOB data types use to store large object such as image, video, graphics, text, audio.
Maximum size up to 4 Gigabytes. Following are LOB data types in SQL.
Table 2.5
9
DDL COMMANDS
Example :
Alter: This command is used to add, change, or remove columns and/or fields in the table.
Syntax: alter table table_name add column datatype;Or
alter table table_name modify column datatype;
10
Example:
11
Rename: Rename table allows you to rename an existing table in any schema.
Syntax: rename old_table_name to new_table_name;
Example:
12
Table 2.4.2 Selecting a table after dropping
Example:
13
Table 2.5.2 Selecting a table after inserting data
Update:The SQL UPDATE Query is used to modify the existing records in a table.
Syntax: update table_name set column_name=value; Or
update table_nameset column1 = value1, column2 = value2...., columnn = valuen
where [condition];
Example:
14
Table 2.6.2 Updating a particular row
Delete: The SQL DELETE Query is used to delete the existing records from a table.
15
Example:
16
DQL(DATA QUERY LANGUAGE)
Select : The Oracle SELECT statement is used to retrieve data from one or more than one
tables, object tables, views, object views etc.
Syntax: SELECT expressions FROM tables WHERE conditions;
Example:
17
Describe:DESCRIBE is most often used to view the definition of a table or a view.
Syntax: describe table_name;
Example:
18
PRACTICAL NO. 3
3.1CONSTRAINTS :Constraints are the rules that restrict the data values inserted in
columns of a table.it helps in maintaining integrity of table at database level instead of
application level. A constraint can constrain single column or group of column in a table.
Syntax:
2. Table level constraints: table constrain is specified at end of create table statement to
constraint more than one column.
Types Of Constraints:
1. Not Null
2.Unique
3.Primary Key
4.Foreign Key
5.Check
6.Default
1. Null/Not Null: Not Null specifies that all row in the table to have value for specified
column. All not null columns are mandatory fields. NULL columns might not contains any
data and can be left empty.
19
Table 3.3.1 Creating table with not null constraint
20
Table 3.1.2.2 Altering the existing table by adding unique constraint
3. Primary Key: Primary key refers to one or more column values in a table that can
uniquely identify each row in a table. A primary key column cannot contain nulls value.
21
Table 3.1.4 Creating table with foreign key constraint
22
6. Default
The DEFAULT constraint is used to provide a default value for a column. The default
value will be added to all new records IF no other value is specified.
Example:
LIKE OPERATOR : The LIKE operator is used in a WHERE clause to search for a
specified pattern in a column.
There are two wildcards used in conjunction with the LIKE operator:
23
Syntax: SELECT column1,column2….. From table_nameWHERE column LIKE pattern;
Example
ORDER BY CLAUSE
The SQL ORDER BY clause is used to sort the data in ascending or descending order, based
on one or more columns.
24
3.3.1ORDER BY DESC:
1. Count:
The count() function returns the number of rows that matches a specified criteria.
25
Table 3.4.1 Using count() function
2. Avg:
3. Sum:
26
Table3.4.3 Using sum()function
4. MIN:
The MIN() function returns the smallest value of the selected column.
27
5. MAX:
The MAX() function returns the largest value of the selected column.
1. GROUP BY Statement
The GROUP BY statement is often used with aggregate functions (COUNT, MAX,
MIN, SUM, AVG) to group the result-set by one or more columns.
Syntax:
28
Example:
2. HAVING Clause:The HAVING clause was added to SQL because the WHERE keyword
could not be use withaggregate functions.
Syntax:
Example:
29
PRACTICAL NO. 04
SET OPERATORS
Set operators combine the results of two component queries into a single result. Queries
containing set operators are called compound queries. SQL supports few Set operations
which can be performed on the table data. These are used to get meaningful results from data
stored in the table, under different special conditions.
1. UNION
2. UNION ALL
3. INTERSECT
4. MINUS
30
Table named anchal:
1. UNION
UNION is used to combine the results of two or more SELECT statements. However it will
eliminate duplicate rows from its resultset. In case of union, number of columns and datatype
must be same in both the tables, on which UNION operation is being applied.
Syntax:
31
Example:
2. UNION ALL
This operation is similar to Union. But it also shows the duplicate rows.
Syntax:
32
Example:
3. INTERSECT
Intersect operation is used to combine two SELECT statements, but it only retuns the records
which are common from both SELECT statements. In case of Intersect the number of
columns and datatype must be same.
33
Syntax:
Example:
4. MINUS
The Minus operation combines results of two SELECT statements and return only those in
the final result, which belongs to the first set of the result.
Syntax:
34
Example:
Example:
35
NESTED QUERIES
A nested query is also called sub query. It is a SELECT statement that is embedded in a
clause of another SELECT statement. A subquery is also called an inner query or inner select,
while the statement containing a subquery is also called an outer query or outer select.The
inner query executes first before its parent query so that the results of an inner query can be
passed to the outer query.
WHERE clause
HAVING clause
FROM clause
Syntax:
SELECT select_list FROM table WHERE expr operator(SELECT select_list FROM table);
Types of sub-queries:
36
1. SINGLE ROW SUB-QUERY
Queries that return only one row from the inner select statement. This type of sub-query uses
a single-row operator.
Example:
Sub-queries that return more than one row are called multi row sub-queries. We use a
multiple-row operator, instead of single-row operator, with a multi-row sub-query. The
multiple-row expects one or more values.
a) IN
b) ANY
c) ALL
37
Example:.
The ANY operator (and its synonym SOME operator) compares a value to each value
returned by the sub-query.
38
Table 4.2.2.(b).(b) ANY operator in multi-row sub-query(MAX(salary))
Example:
39
Table 4.2.2.(c).(b) ALL operator in multi-row sub-query(MAX(salary))
3. MULTIPLE-COLUMN SUB-QUERY
40
JOINS
SQL JOIN is a method to retrieve data from two or more database tables.
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.
1. CROSS JOIN
2. INNER JOIN
3. NATURAL JOIN
4. LEFT OUTER JOIN
5. RIGHT OUTER JOIN
6. FULL OUTER JOIN
1. CROSS JOIN
The SQL CROSS JOIN produces a result set which is the number of rows in the first table
multiplied by the number of rows in the second table if no WHERE clause is used along with
CROSS JOIN. This kind of result is called as Cartesian Product.
If WHERE clause is used with CROSS JOIN, it functions like an INNER JOIN.
An alternative way of achieving the same result is to use column names separated by commas
after SELECT and mentioning the table names involved, after a FROM clause.
41
Syntax:
Example:
2. INNER JOIN
The INNER JOIN selects all rows from both participating tables as long as there is a match
between the columns. An SQL INNER JOIN is same as JOIN clause, combining rows from
two or more tables.
Syntax:
or
42
Example:
3. NATURAL JOIN
The SQL NATURAL JOIN is a type of EQUI JOIN and is structured in such a way that,
columns with the same name of associated tables will appear once only.
The associated tables have one or more pairs of identically named columns.
Syntax:
43
Example:
The SQL LEFT JOIN (specified with the keywords LEFT JOIN and ON) joins two tables and
fetches all matching rows of two tables for which the SQL-expression is true, plus rows from
the first table that do not match any row in the second table.
Syntax:
Example:
44
5. RIGHT OUTER JOIN
The SQL RIGHT JOIN, joins two tables and fetches rows based on a condition, which is
matching in both the tables and the unmatched rows will also be available from the table
written after the JOIN clause
Syntax:
Example:
In SQL the FULL OUTER JOIN combines the results of both left and right outer joins and
returns all (matched or unmatched) rows from the tables on both sides of the join clause.
Syntax:
45
Example:
46
SEQUENCE
increment by increment-value
maximum maximum-value
cycle | nocycle;
47
Example:
Whenever a sequence is created, then the next work is to create a table and inserting the
values.
Syntax:
Examples:
48
Table 4.3.3.1 Inserting first value to created table to increment roll no.
automatically
After inserting the values, to check out the created sequence we can see the data
entered into the table by using the SELECT query/statement. The attribute on which
sequence is applied is automatically incremented by the mentioned value and reaches
to the maximum value by following the sequence.
49
Example:
50
PRACTICAL NO.05
VIEWS
Views in SQL are kind of virtual tables. A view also has rows and columns as they are in a
real table in the database. We can create a view by selecting fields from one or more tables
present in the database. A View can either have all the rows of a table or specific rows based
on certain condition.
To, the user the view appears like a table with rows and columns. But, in reality the view
does not exist in the database as a stored set of values. The rows and columns that we find
inside a view are actually the results generated by the query that defines the view.
CREATE A VIEW
Views are created using VIEW command. Once a view is created it can be treated just as you
treat any other table. A View can be created from a single table or multiple tables.
Syntax:
51
TO SELECT A VIEW
View can be selected using the SELECT statement. This will provide us with the values
present in the created view.
Syntax:
DESCRIBE A VIEW
The view can be described using the DESCRIBE statement. This will provide the entire
information of the view i.e., attributes along with their datatypes and described details.
Syntax:
describe view_name;
52
Example:
Syntax:
insert view_name(column1, column,2,….) values (value1,value2,…);
Example:
When we insert the data in the view it will automatically update the data in table which we
have selected to create a view.
53
Example:
54
INDEXES
Indexes are used to retrieve data from the database very fast. The users cannot see the
indexes, they are just used to speed up searches/queries. Index is a way to store and search
records in a table.
By ROWID
By full_table scan
TYPES OF INDEXES:
1. Duplicate Indexes
2. Unique Indexes
We can create an index for a previous present table but it can have duplicate values.
Syntax:
Example:
55
DATABASE SECURITY AND PRIVILEGES
TO CREATE A USER
We can create different users in the oracle by providing the accessibility to other users and
can also access data from other columns.
Syntax:
PRIVILEGES
System: This includes permissions for creating session, table, etc and all types of other
system privileges.
Object: This includes permissions for any command or query to perform any operation
on the database tables.
56
Example:
1. GRANT:
Used to provide any user access privileges or other privileges for the database.
Syntax:
57
Example:
2. REVOKE:
Syntax:
Example:
58
CREATING A TABLE IN USER
To create a table in the another user same procedure is followed. Each user can create his/her
own databases to access the data easily from the different tables.
COMMIT COMMAND
The COMMIT command is the transactional command used to save changes invoked by a
transaction to the database.
The COMMIT command is the transactional command used to save changes invoked by a
transaction to the database. The COMMIT command saves all the transactions to the
database since the last COMMIT or ROLLBACK command.
Syntax:
COMMIT;
Example:
Consider the CUSTOMERS table having the following records –
59
Following is an example which would delete those records from the table which have age =
25 and then COMMIT the changes in the database.
Syntax:
Delete from customers where age=25;
COMMIT;
Thus, two rows from the table would be deleted and the SELECT statement would produce
the following result.
ROLLBACK COMMAND
The ROLLBACK command is the transactional command used to undo transactions that
have not already been saved to the database. This command can only be used to undo
transactions since the last COMMIT or ROLLBACK command was issued.
Syntax:
ROLLBACK;
60
Example:
Consider the CUSTOMERS table having the following records –
Following is an example, which would delete those records from the table which have the
age = 25 and then ROLLBACK the changes in the database.
Syntax:
Delete from customers where age =25;
ROLLBACK;
Thus, the delete operation would not impact the table and the SELECT statement would
produce the following result.
61
PRACTICAL NO. 06
INRODUCTION TO PL/SQL
ARCHITECTURE OF PL/SQL
The PL/SQL engine executes the PL/SQL blocks. The PL/SQL engine executes only the
procedural statements and sends the SQL statements to the SQL statement executer in the
Oracle Server. The PL/SQL engine resides in the Oracle Server. The call to the Oracle engine
needs to be made only once to execute any number of SQL statements, if these SQL
sentences are bundle inside a PL/SQL block. Since the oracle engine is called only once for
each block, resulting increased speed of processing as compared to call for SQL sentence.
PL/SQL is a block structured language with procedural techniques with features like logic
building, looping, error-handling mechanisms, data types, variables, sub-routines, procedural
constructs. Block is the smallest piece of PL/SQL code which groups logically related
62
declarations and statements. Declarations are local to the blocks and cease to exist when
block completes.
1. Declare
Used to declare variables and constants.
Is an optional section.
It is used to declare type declarations, PL/SQL procedures nad functions, which are
local to module.
2. Begin
Is the executable section containing their code, which is executed when block is run.
Is compulsory.
3. Exception
Handles exceptions occurring during processing.
Used to place predefined Error-handlers or user defined exceptions.
Code contained in this section is executed only when an error occurs.
Is an optional section.
DECLARE
Variable definition
BEGIN
Program execution
EXCEPTION
Exception handling
END;
63
Examples:
a) To print ‘Hello’
BASIC VARIABLES
PL/SQL programming language allows to define various types of variables, such as date time
data types, records, collections, etc. By default, variable names are not case sensitive.
64
Variable declaration in PL/SQL:
PL/SQL variables should be defined in a declaration section as a global variable. The syntax
for defining a variable is :
PL/SQL allows the nesting of blocks. If a variable is declared within an inner block, it is not
accessible to outer block. However, if a variable is declared and accessible to an outer block,
it is also accessible to all inner blocks.
a) Local Variables:- Variables are declared in an inner block and not accessible to outer
blocks.
b) Global Variables:- Variables are declared in the outermost block.
Example:
65
PRACTICAL NO. 07
STORED PROCEDURES
A stored procedure or function is a named PL/SQL module, which contain it. They can be
compiled and stored in one of the Oracle engine’s system tables. Stored Procedures and
Functions are stored in the Oracle database. They are invoked or called by any the PL/SQL
block that appears within an application. Before the procedure or function is stored, the
Oracle engine parses and compiles the procedure or function. The Oracle engine compiles the
PL/SQL block.
If an error occurs during the compilation of the procedure, an invalid procedure is created.
The Oracle engine displays a message after creation that the procedure was created with
compilation errors. It does not display the errors. These can be viewed using select statement
or with show command as below:
Or
Show errors;
PARTS OF PROCEDURES
A declarative part
An executable part
An optional exception-handling part
Declarative Part: The declarative part is used to declare constants, variables, exceptions and
subprograms. The objects are local to the procedure or function. The objects become invalid
once the user exits from the procedure or function.
Executable Part: It is compulsory part, which is used to perform actions. Variables declared
are put into this block. The executable part in PL/SQL block consisting of SQL and PL/SQL
statements that assign values control execution and manipulate data. The data that is to be
returned back to the calling environment is also returned from here.
66
Exception Handling Part: It is optional part to handle the errors raised during the execution
of code in the executable part. We cannot transfer the flow or execution from the Exception
Handling part to the Executable part.
Argument modes are used to define the behaviour of formal parameters. There are three
argument modes INT, OUT and IN OUT to be used with any subprograms.
To create procedures and store them permanently in an Oracle database, we use the CREATE
PROCEDURE statement, which we can use interactively from SQL * Plus.
Syntax:
IS
Declaration Section
BEGIN
Execution Section
EXCEPTION
Exception Section
END;
67
Description:
procedure_name: It is the procedure name used to identify the procedures when it is called
in a program.
Example:
CALLING A PROCEDURE
A stored procedure is called as a PL/SQL statement. A stored procedure can be called from
any PL/SQL program by giving their names followed by parameters.
68
Example:
We can change the logical flow of statements within the PL/SQL block with the number of
control structures.
IF-THEN STATEMENT
IF-THEN-ELSE STATEMENT
IF-THEN-ELSEIF STATEMENT(LADDER)
Below is an example where we will declare, create and call a procedure in a single code. In
this we have declared three variables a, b and c with number as a data type. After that we
have created a procedure in which we have declared 3 variables X, Y, and Z where in X and
Y we will pass the values and at the end it will help to find the minimum value which will be
stored in the variable Z.
69
Example:
DROPPING A PROCEDURE
To drop a Procedure, DROP PROCEDURE command is used. For this user must either own
the procedure or have DROP ANY PROCEDURE system privilege.
Syntax
70
Example:
71
EXCEPTION HANDLING
When an error occurs, an exception is raised; normal exception is stopped and control is
transferred to exception-handling section of PL/SQL program. A specific section can be
defined in a program to handle exceptions. Separate sub-routines called exception handlers
can be created to perform all exception processing. Once an exception is raised and control is
transferred to the exception part of a program, it cannot return to the exception part of the
program.
HANDLING OF ERRORS
Errors are handled in two ways, one is to trap the error and other is to propagate to the calling
environment.
EXCEPTION TYPES
Implicit raised exceptions: PL/SQL provides a predefined set of exceptions that are
implicitly raised(automatically raised) by the system at run time in case an error is
encountered in PL/SQL.
72
There are two types of implicitly raised exceptions:
Explicitly raised exceptions: User can also define their own set of user-defined exceptions
and explicitly raise them on encountering an error condition.
Example:
73
PRACTICAL NO. 08
TRIGGERS IN PL/SQL
A database trigger is a stored procedure that is fired when an INSERT, UPDATE or DELETE
statements is issued against the associate table. The name trigger is appropriate, as these are
triggered(fired) whenever the mentioned commands are executed. A trigger defines an action
the database should take when some database related event occurs.
A trigger is automatically executed without any action required by the user. A stored
procedure on the other hand needs to be explicitly invoked.
PARTS OF A TRIGGER
Triggering Event or Statement:- It is the SQL statement that causes a trigger to be fired. A
triggering event can be INSERT,UPDATE or DELETE statement for a specific table.
Trigger action:- A trigger action is a procedure(PL/SQL block) that contains the SQL
statements and PL/SQL code to be executed when a triggering statement is issued and the
trigger restriction evaluates to TRUE.
Triggers are written to be executed in response to DML, DDL and data operation. Triggers
can be defined on table, view, schema or database with which an event is associated.
74
SYNTAX FOR CREATING A TRIGGER
{BEFORE|AFTER}
ON table_name
DECLARE
Variable declaration;
Constant
declaration;
BEGIN
[EXCEPTION
END;
TYPES OF TRIGGERS
A trigger’s type is defined by the type of triggering transaction and by the level at which the
trigger is executed.
75
Oracle has following types of triggers depending on the different applications:
Row Level Triggers:- They execute once for each row in a transaction. The commands of
this triggers are executed on all rows that are affected by command that enables the trigger.
Statement Level Triggers:- Statement Level triggers are triggered only once for each
transaction. These are default types of triggers created by CREATE TRIGGER command.
Before and After Trigger:- Since triggers are executed by events, they may be set to occur
immediately before or after those events.
BEFORE triggers execute the trigger action before the triggering statement.
AFTER trigger executes the trigger action after the triggering statement is executed.
These are used when you want the triggering statement to complete before executing
the triggering action.
Examples:
76
Figure 8.2 Creating a Trigger (after an updation on employee_name)
Triggers may be dropped via the drop rigger command. In order to drop a trigger, one must
either own the trigger or have DROP ANY TRIGGER system privilege.
Example:
77
CURSOR MANAGEMENT IN PL/SQL
A cursor is a temporary work area created in system area when SQL statement is executed. It
contains information on select statement and row of data access by it. The Oracle Engine uses
a work area to execute SQL area to execute SQL statements and store information. A cursor
is a PL/SQL construct that allows us to name these work areas, ad to access their stored
information. The data stored in the cursor is called Active Data Set.
TYPES OF CURSORS:
Implicit Cursors
Explicit Cursors
Implicit Cursors
Implicit cursors are created by default when DML statement is executed. Implicit cursors are
declared by PL/SQL implicitly for all SQL statements. They are opened and managed by
Oracle engine internally. So there is no need to open and manage by the uses, these are
operations that are performed automatically.
Explicit Cursors
Explicit cursor is created by user when executing select statement. Explicit cursors are user-
defined cursors for processing of multiple records returned by a query. Explicit cursors are
declared explicitly, along with other identifiers actions. These are defined in the DECLARE
section of PL/SQL block.
Whenever any cursor is opened and used, the oracle engine creates a set of four system
variables, which keeps track of the current status of the cursor. These variables can be
accessed and used in PL/SQL block. Both implicit and explicit cursor has four attributes.
78
The attributes are described as:
Example
79