Rdbms File 2nd Sem
Rdbms File 2nd Sem
JALANDHAR
SESSION- 2014
1
RDBMS
INDEX
Create table 23
Alter Query 23-24
Modify Query 24
2
RDBMS
CHAPTER-1
3
RDBMS
INTRODUCTION
Introduction To Oracle
Introduction To SQL
4
RDBMS
Database and
Management System
DATABASE
A database is a collection of information that is organized so that it can easily be accessed,
managed, and updated. In one view, databases can be classified according to types of content:
bibliographic, full-text, numeric, and images.
In computing, databases are sometimes classified according to their organizational approaches.
The most prevalent approach is the relational database, a tabular database in which data is
defined so that it can be reorganized and accessed in a number of different ways.
Features of DBMS
Each DBMS is designed to support large amount of data. They provide special ways and means
to store and manipulate large amount of data. Companies are trying to store more and more
amount of data. Some of this data will have to be online (available every time).For example,
Oracle can store terabytes of data.
DBMS also allows data to be shared by two or more users. The same data can be accessed by
multiple users at the same time – data concurrency .However when same data is being
manipulated at the same time by multiple users certain problems arise. To avoid these problems,
DBMS locks data that is being manipulated to avoid two users from modifying the same data at
the same time.
3. Data Security
5
RDBMS
While DBMS allowing data to be shared, it also ensures that data in only accessed by authorized
users. DBMS provides features needed to implement security at the enterprise level. By default,
the data of a user cannot be accessed by other users unless the owner gives explicit permissions
to other users to do so.
4. Data Integrity
Maintaining integrity of the data is an import process. If data loses integrity, it becomes unusable
and garbage. DBMS provides means to implement rules to maintain integrity of the data. Once
we specify which rules are to be implemented, then DBMS can make sure that these rules are
implemented always.
DBMS provides great deal of fault tolerance. They continue to run in spite of errors, if possible,
allowing users to rectify the mistake in the mean time. DBMS also allows recovery in the event
of failure. For instance, if data on the disk is completely lost due to disk failure then also data can
be recovered to the point of failure if proper back up of the data is available.
DBMS supports a data access and manipulation language. The most widely used data access
language for RDBMS (relational database management systems) is SQL. DBMS implementation
of SQL will be compliant with SQL standards set by ANSI. Apart from supporting a non-
procedural language like SQL to access and manipulate data DBMS now a day’s also provides a
procedural language for data processing. Oracle supports PL/SQL and SQL Server provides T-
SQL.
6
RDBMS
RDBMS Terminology:
Before we proceed to explain MySQL database system, let's revise few definitions related to
database.
Table: A table is a matrix with data. A table in a database looks like a simple
spreadsheet.
Column: One column (data element) contains data of one and the same kind, for
example the column postcode.
Row: A row (tuple, entry or record) is a group of related data, for example the data of
one subscription.
Primary Key: A primary key is unique. A key value cannot occur twice in one table.
With a key, you can find at most one row.
Foreign Key: A foreign key is the linking pin between two tables.
Compound Key: A compound key (composite key) is a key that consists of multiple
columns, because one column is not sufficiently unique.
Referential Integrity: Referential Integrity makes sure that a foreign key value always
points to an existing row.
INTRODUCTION TO ORACLE
7
RDBMS
ORACLE consists of many tools that allow you to create an application with ease and
flexibility. You must determine how to implement your requirements using the features
available in ORACLE, along with its tools. The features and tools that you choose to use
to implement your application can significantly affect the performance of your
application.
The suffixes "i", "g" and "c" do not actually represent a low-order part of the version number, as
letters typically represent in software industry version numbering; that is, there is no predecessor
version of Oracle 10g called Oracle 10f. Instead, the letters stand for "internet", "grid" and
"cloud", respectively.[53] Consequently many simply drop the "g" or "i" suffix when referring to
specific versions of an Oracle product.
8
RDBMS
System
Oracle v5
Oracle v6
Oracle7: 7.0.16–7.3.4
Oracle8 Database: 8.0.3–8.0.6
Oracle8i Database Release 1: 8.1.5.0–8.1.5.1
Oracle8i Database Release 2: 8.1.6.0–8.1.6.3
Oracle8i Database Release 3: 8.1.7.0–8.1.7.4
Oracle9i Database Release 1: 9.0.1.0–9.0.1.5
Oracle9i Database Release 2: 9.2.0.1–9.2.0.8
Oracle Database 10g Release 1: 10.1.0.2–10.1.0.5
Oracle Database 10g Release 2: 10.2.0.1–10.2.0.5
Oracle Database 11g Release 1: 11.1.0.6–11.1.0.7
Oracle Database 11g Release 2: 11.2.0.1–11.2.0.3
Oracle Database 12c Release 1: 12.1
Introduction to SQL
Structured Query Language (SQL) is the set of statements with which all programs and users
access data in an Oracle database. Application programs and Oracle tools often allow users
access to the database without using SQL directly, but these applications in turn must use SQL
when executing the user's request. This chapter provides background information on SQL as
used by most database systems.
History of SQL
Dr. E. F. Codd published the paper, "A Relational Model of Data for Large Shared Data Banks",
in June 1970 in the Association of Computer Machinery (ACM) journal, Communications of the
ACM. Codd's model is now accepted as the definitive model for relational database management
systems (RDBMS). The language, Structured English Query Language ("SEQUEL") was
developed by IBM Corporation, Inc., to use Codd's model. SEQUEL later became SQL (still
pronounced "sequel"). In 1979, Relational Software, Inc. (now Oracle Corporation) introduced
the first commercially available implementation of SQL. Today, SQL is accepted as the standard
RDBMS language.
purpose programming languages like C and BASIC. Among the features of SQL are the
following:
Essentially, SQL lets you work with data at the logical level. You need to be concerned with the
implementation details only when you want to manipulate the data. For example, to retrieve a set
of rows from a table, you define a condition used to filter the rows. All rows satisfying the
condition are retrieved in a single step and can be passed as a unit to the user, to another SQL
statement, or to an application. You need not deal with the rows one by one, nor do you have to
worry about how they are physically stored or retrieved. All SQL statements use the optimizer, a
part of Oracle that determines the most efficient means of accessing the specified data. Oracle
also provides techniques that you can use to make the optimizer perform its job better.
Querying data
Inserting, updating, and deleting rows in a table
Creating, replacing, altering, and dropping objects
Controlling access to the database and its objects
Guaranteeing database consistency and integrity
Instructions are given in the form of statements, consisting of a specific SQL statement and
additional parameters and operands that apply to that statement. SQL statements and their
modifiers are based upon official SQL standards and certain extensions to that each database
provider implements.
10
RDBMS
CREATE - Used to create a new table, a view of a table, or other object in database.
ALTER - Used to modify an existing database object, such as a table.
DROP - Used to delete an entire table, a view of a table or other object in the database.
DATA TYPE
Data type is here a type of values known by the system which would be filled into the specified
database table column.
11
RDBMS
CHAPTER-2
SQL COMMANDS
Distinct clause
Where clause
Or/And clause
Like clause
Order by clause
Unique clause
12
RDBMS
Insert query
Update query
Delete query
To perform the SQL queries, we have taken the following table structure:
1. emp
2. dept
Dept table represents department table.
13
RDBMS
The SQL SELECT statement queries data from tables in the database. The statement begins with
the SELECT keyword. The basic SELECT statement has 3 clauses:
SELECT
FROM
WHERE
The SELECT clause specifies the table columns that are retrieved.
The FROM clause specifies the tables accessed.
The WHERE clause specifies which table rows are used. The WHERE clause is optional; if
missing, all table rows are used.
We can use the SELECT statement to retrieve more than one column. Syntax is:-
For Eg: We want to retrieve the records of empno, ename, sal from emp table
14
RDBMS
There are two ways to select all columns from a table. The first is to list the column name of
each column. The second, and the easier, way is to use the symbol *. Syntax is:-
For eg: We want to retrieve all the records for all columns.
15
RDBMS
The SELECT keyword allows us to grab all information from a column (or columns) on a table.
This, of course, necessarily means that there will be redundancies. What if we only want to select
each DISTINCT element? This is easy to accomplish in SQL. All we need to do is to
add DISTINCT after SELECT. The syntax is as follows:
For eg:- We want to retrieve the distinct deptno from emp table.
The WHERE clause is used to extract only those records that fulfill a specified criterion. It
filters the result set based on certain conditions.
For Eg:-We want to retrieve all the records from the columns where deptno=20.
16
RDBMS
simple conditions connected by AND or OR. There is no limit to the number of simple
conditions that can be present in a single SQL statement.Its syntax is:-
For eg:-We want to retrieve the records for empno,ename from table emp where deptno=20 and sal>300.
For eg:-We want to extract the records for empno,ename,job from emp table where deptno=20 or
sal>300.
SQL IN CLAUSE
It is used when we know exactly the value of the returned values we want to see for at least one
of the columns. Its Syntax is:-
17
RDBMS
For eg:-We want to retrieve the records for empno,ename from emp table where deptno in 10,20
For eg:-We want to retrieve the records from emp table where ename is like ‘S%’
18
RDBMS
For eg:-We want to retrieve the records for ename,job from emp table where deptno=20 and ename is in
descending order or ascending order.
For Eg:-We want to retrieve the unique deptno from emp table.
19
RDBMS
20
RDBMS
CREATE TABLE statement is used to create a table in a database. Tables are organized into
rows and columns; and each table must have a name. SQL CREATE TABLE Syntax
TABLE table_name
(column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
....);
The column_name parameters specify the names of the columns of the table.
The data_type parameter specifies what type of data the column can hold (e.g. varchar, integer,
decimal, date, etc.).
The size parameter specifies the maximum length of the column of the table.
For eg:-We want to create a table mca2 with attributes such as name,rollno and subject.
ALTER TABLE
Once a table is created in the database, there are many occasions where one may wish to change
the structure of the table. In general, the SQL syntax for ALTER TABLE is,
21
RDBMS
[alter specification] is dependent on the type of alteration we wish to perform. We list a number
of common changes below:
1.ADD COLOUMN
Sometimes we wish to add a column to a table. This can be achieved in SQL. To do this, we
specify that we want to change the table structure via the ALTER TABLE command, followed
by the ADD command to tell the RDBMS that we want to add a column.
2. MODIFY COLUMN
Sometimes we need to change the data type of a column. To do this, we use the ALTER
TABLE Modify Column command. For Oracle and MySQL, the SQL syntax for ALTER
TABLE Modify Column is,
22
RDBMS
The SQL INSERT INTO Statement is used to add new rows of data to a table in the database.
In SQL, there are basically two ways to INSERT data into a table: One is to insert it one row at a
time, the other is to insert multiple rows at a time. In this section, we'll take a look at the first
case:
23
RDBMS
UPDATE QUERY
Once there's data in the table, we might find that there is a need to modify the data. To do so, we can
use the UPDATE command. You can use WHERE clause with UPDATE query to update selected
rows otherwise all the rows would be affected.
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
2.SQL DELETE QUERY
Sometimes we may wish to use a query to remove records from a table. To do so, we can use the
DELETE FROM command. If we leave out the WHERE clause in a DELETE FROM command, we
will remove all rows from the table. The syntax for this is:
For eg:We want to delete a record from mca2 table where name=’preeti’.
24
RDBMS
CHAPTER-3
SQL FUNCTIONS
Number Functions
Character functions
Date Functions
Conversion Functions
Group Functions
25
RDBMS
1.Single-Row Functions
2.Group Functions
SQL language like all the other computer languages comes with many pre-built functions. These
functions can be categorized into two major groups. One is called “Single Row” functions and
the other one is called “Group” functions. Single Row function as the name says gets
implemented on single records whereas Group functions get implemented on the multiple
records.
DUAL is a table automatically created by Oracle Database along with the data dictionary. DUAL is
in the schema of the user SYS but is accessible by the name DUAL to all users. It has one column,
DUMMY, defined to be VARCHAR2(1), and contains one row with a value X. Selecting from the
DUAL table is useful for computing a constant expression with the SELECT statement.
Character Functions: Character functions accept character inputs and can return either
character or number values as output.
Number Functions: Number functions accepts numeric inputs and returns only numeric
values as output.
26
RDBMS
Date Functions: Date functions operate on date data type and returns a date value or
numeric value.
Conversions Functions: Converts from one data type to another data type.
Character Functions
1. LOWER
The Lower function converts the character values into lowercase letters. Its syntax is:
For Eg:-We want to convert the characters to lower of all records of ename from emp table .
27
RDBMS
2. UPPER
The Upper function converts the character values into uppercase letters. Its syntax is:
For Eg:-We want to convert the characters to upper of a string name’abc’ from dual table .
For Eg:-We want to convert the characters to uppercase of all records of ename from emp table .
3. INITCAP
The Initcap function coverts the first character of each word into uppercase and the remaining
characters into lowercase. Its syntax is:
For Eg:-We want to convert only the first character of string ’abc’ into uppercase from dual table.
28
RDBMS
For Eg:-We want to convert only the first character of a string ’ABC’ into uppercase from dual table.
For Eg:-We want to convert only the first character of a string ’aBC’ into uppercase from dual table.
5. SUBSTR
The Substr function returns specified characters from character value starting at position m and n
characters long. If you omit n, all characters starting from position m to the end are returned.Its
syntax is:
m is the starting postion of substring and optional n is the number of characters to return .
m can be positive or negative. If it is negative it counts backwards from the end of the string.
29
RDBMS
For Eg: The following output shows the various formats regarding substr function.
30
RDBMS
Number Functions
1. ROUND
The Round function rounds the value to the n decimal values. If n is not specified, there won't be
any decimal places. If n is negative, numbers to the left of the decimal point are rounded. Its
syntax is:
Here , m is the number which is to be rounded either to left or right of decimal point.
For Eg:
31
RDBMS
2.TRUNC
This function drops all digits of number m either to left or right of the decimal point depending
on sign of n. The Trunc function truncates the value to the n decimal places. If n is omitted, then
n defaults to zero.
For Eg:
32
RDBMS
3. MOD
4. SQRT
The Sqrt function returns the square root of n.where n is greater than equal to 0.
Date Functions
1. SYSDATE
The Sysdate function returns the current oracle database server date and time.
33
RDBMS
2.. ROUND
The Round function returns the date rounded to the specified format. The Syntax is:
Conversion Functions
The conversion function convert a value from one data type to another. These functions just
return the converted value and does not make any changes in the database. The data type
conversion can be done automatically or implicitly done by the oracle or explicitly done by the
user.
1.) Implicit Data Type Conversion :- The oracle automatically converts one data type into
another when used in the assignments.
To have oracle automatically convert one data type to another the source data type must already
look like the target data type it is being converted to. The following guidelines describe the
34
RDBMS
automatic conversion of data from one data type to another based on the function that will use
the data.
Any number or date can be converted to a character string.
A char or varchar2 will be converted to a number if it contains only numbers,a decimal point or
minus sign on the left.
A char or varchar2 will be converted to date only if it is in the format DD-MON-YY.
A date will not be converted to a number to a number and vice-versa.
(2) Explicit Data Type Conversion :- The following are the list of conversion functions
which are done explicitly done by the user.
(1) TO_CHAR (date conversion):-This date based function is used for transforming a DATE
value into a VARCHAR2 value,optionally using a specified date format.
Where date format is optional if it is omitted the date is converted to a varchar2 value in the
default date format. Some of the formatting options are:
Here it is showing the system date, when we are writing MONTH in syntax then it will
show thw month in characters.
35
RDBMS
Here it is showing the month in characters and also the TH with date.
36
RDBMS
(2) TO_CHAR (number conversion):-This number based function is used for transforming
numeric value into varchar2 value optionally using a specified number format.
SYNTAX:- TO_CHAR(N[,NUM_FORMAT])
Here it is showing the ##### symbol because we are giving here less 9’s then the original
number.
Here it is showing simply the number 1234 even we are giving more 9’s then the original
number.
Here it is showing simply 1234 number without $ sign because we are not giving the $ sign
even in the given format which is in single quotes.
37
RDBMS
Here it is showing the number 1234 with using commas with given specified format.
Here it is showing the number in same way either we use format as zeros, its just including
zero in empty space.
Here it is showing the zero at starting of the number as per the specified format.
38
RDBMS
(3) TO_DATE:- This TO_DATE function is used for converting a character string to its date
equivalent. A date format string can be provided to tell oracle how to interpret a character string.
SYNTAX:- TO_DATE(char_value[,for_string])
Where ‘for_string’ is same as that used for Date formats. Here ‘char_value’ may be a literal
string, a literal number or a database column containing a string or a number. In every case, the
format must correspond to that which is described by the format. Only if a ‘char_value’ is in the
format ‘DD-MON-YY’, the format can be omitted.
39
RDBMS
Here it is showing simply the number which is already given in number form.
Here we are creating a table in which we are inserted values as a date and timestamp data
type:
40
RDBMS
GROUP FUNCTIONS
SQL GROUP BY CLAUSE
The GROUP BY keyword is used when we are selecting multiple columns from a table (or tables) and at
least one arithmetic operator appears in the SELECT statement. Such operators include COUNT, SUM,
MAX, MIN, and AVG. When that happens, we need to GROUP BY all the other selected columns, i.e.,
all columns except the one(s) operated on by the arithmetic operator. As such, it is important to note that
we may have two columns or more associated with GROUP BY. The general syntax is as follows:
SELECT (column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name;
For Eg:
41
RDBMS
AGGREGATE FUNCTIONS
AVG FUNCTION
42
RDBMS
SQL uses the AVG( ) function to calculate the average of a column. The syntax for using this function is:
FROM table_name ;
COUNT FUNCTION
Another arithmetic function is COUNT. This allows us to COUNT up the number of row in a certain
table. The syntax is:
SELECT COUNT(column_name)
FROM table_name;
SUM FUNCTION
The SUM function is used to calculate the total for a column. The syntax is,
SELECT SUM(column_name)
FROM table_name;
MAX FUNCTION
SQL uses the MAX function to find the maximum value in a column. The syntax for using the
MAX function is,
MIN FUNCTION
SQL uses the MIN function to find the maximum value in a column. The syntax for using the
MIN function is,
43
RDBMS
CHAPTER- 4
SUBQUERIES
Single-Row Subqueries
44
RDBMS
IN operator
ANY operator
ALL operator
SUB QUERIES
A Subquery or Inner query or Nested query is a query within another SQL query and embedded
within the WHERE clause.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.Subqueries can be used with the
SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <, >,
>=, <=, IN, BETWEEN etc.
Single-Row Subquery
The operators that can be used with single-row subqueries are =, >, >=, <, <=, and < >.
SELECT "column_name1"
FROM "table_name1"
WHERE "column_name2" [Comparison Operator]
45
RDBMS
(SELECT "column_name3"
FROM "table_name2"
WHERE "condition");
Multiple-Row Subquery
Multiple row subquery returns one or more rows to the outer SQL statement. You may use the
IN, ANY, or ALL operator in outer query to handle a subquery that returns multiple rows.
IN operator
The IN operator compares a value with every value returned from the subquery. The IN operaor
is equivalent to(=ANY).
46
RDBMS
ANY operator
The ANY operator compares a value to each value returned by a subquery.It is evaluates to
TRUE if there exists atleast one row selected selected by subquery for which the comparisons
holds.It evaluates to FALSE if the query returns no rows.
For eg:
ALL operator
The ALL operator compares a value to every value returned by a query.It evaluates TRUE for all
rows selected by subquery ,the comparison holds.Also, the condition evaluates to TRUE if
subquery does not yield any any row or the value.
For eg: We want to retrieve all employees ename, deptno, empno, sal from emp table who are
not working in deptno=30 and who earn more than all employees working in deptno=30.
47
RDBMS
CHAPTER 5
SQL JOINS
Equi Join
48
RDBMS
Outer Join
Self Join
Cartesian Join
The most frequently used and important of the joins is the INNER JOIN. They are also referred
to as an EQUIJOIN.
The INNER JOIN creates a new result table by combining column values of two tables (table1
and table2) based upon the join-predicate. The query compares each row of table1 with each row
of table2 to find all pairs of rows which satisfy the join-predicate. When the join-predicate is
satisfied, column values for each matched pair of rows of A and B are combined into a result
row. Syntax:
49
RDBMS
Foe eg:We want to retrieve records for empno,ename,deptno from two different tables such as
emp and dept tables.
Previously, we had looked at left join, or inner join, where we select rows common to the
participating tables to a join. What about the cases where we are interested in selecting elements
in a table regardless of whether they are present in the second table? We will now need to use the
SQL OUTER JOIN command. The syntax for performing an outer join in SQL is database-
dependent. For example, in Oracle, we will place an "(+)" in the WHERE clause on the other
side of the table for which we want to include all the rows.
For eg: We want to retrieve the records for empno,ename,deptno from two different tables such
as emp and dept tables
50
RDBMS
The SQL SELF JOIN 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.The basic syntax of SELF JOIN is as follows:
Here, WHERE clause could be any given expression based on your requirement.
51
RDBMS
A cross join (also called a Cartesian join) is a join of tables without specifying the join condition.
In this scenario, the query would return all possible combination of the tables in the SQL query.
The CARTESIAN JOIN or CROSS JOIN returns the Cartesian product of the sets of records
from the two or more joined tables. Thus, it equates to an inner join where the join-condition
always evaluates to True or where the join-condition is absent from the statement. The basic
syntax of INNER JOIN is as follows:
52
RDBMS
For Eg:-
We want to retrieve all the possible values for empno, ename, deptno and deptname from the two
tables emp and dept without specifying the join condition.
53