Rdbms File 2nd Sem

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 53

RDBMS

D.A.V INSTITUTE OF ENGINEERING &TECHNOLOGY

JALANDHAR

SESSION- 2014

RDBMS PRACTICAL FILE

Submitted By: Submitted To:


Anamika Mrs. Reeta Bhardwaj
B.tech (I.T),5Th semester
1903818

1
RDBMS

INDEX

S.NO TOPICS PAGE .NO SIGNATURE


1. CHAPTER -1 INTRODUCTION 6-13
 Introduction to Database Management System(DBMS) 7-8

 Introduction to Relational Database Management 9


System(DBMS)
 Introduction to Oracle 9-11

 Introduction to SQL 11-13

2. CHAPTER -2 SQL COMMANDS 14-26

 SQL Data Query Language 16-22


Select Query with different Clauses such as Distinct,
Where, Or /and, Like , Order by and Unique clause.
 SQL DDL Queries 23-24

Create table 23
Alter Query 23-24
Modify Query 24

 SQL DML Queries 25-26


Insert Query 25
Update Query 25-26
Delete Query 26

3. CHAPTER -3 SQL FUNCTIONS 27-45

 Single row Functions 27-28


Character Functions 29-32
Number Functions 33-34
Date Functions 35
Conversion Functions 36-42
 Group Functions 43-45
S.NO TOPICS PAGE .NO SIGNATURE

2
RDBMS

4. CHAPTER -4 SQL SUBQUERIES 46-49

 Single Row Subqueries 47-48

 Multiple Row Sub queries 49

5. CHAPTER -5 SQL JOINS 50-52

CHAPTER-1
3
RDBMS

INTRODUCTION

Topics Discussed are:

 Introduction To Database Management System (DBMS)

 Introduction To Relational Database Management System (RDBMS)

 Introduction To Oracle

 Introduction To SQL

Introduction to Database Management Systems

The database management system consists of two parts.  They are:

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.

DATABASE MANAGEMENT SYSTEM (DBMS)


The database management system (DBMS) is a computer software program that is designed as
the means of managing all databases that are currently installed on a system hard drive or
network. Different types of database management systems exist, with some of them designed for
the oversight and proper control of databases that are configured for specific purposes. Here are
some examples of the various incarnations of DBMS technology that are currently in use, and
some of the basic elements that are parts of DBMS software applications.
In database management system (DBMS), data files are the files that store the database
information, whereas other files, such as index files and data dictionaries, store administrative
information, known as metadata.

Features of DBMS

The following are main features offered by DBMS.

1. Support for large amount of data

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.

2. Data sharing, concurrency and locking

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.

5. Fault tolerance and recovery

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.

6. Support for Languages

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.

Introduction to Relational Database Management Systems

A Relational Database Management System (RDBMS) is software that:

6
RDBMS

 Enables you to implement a database with tables, columns and indexes.

 Guarantees the Referential Integrity between rows of various tables.

 Updates the indexes automatically.

 Interprets an SQL query and combines information from various tables.

RDBMS Terminology:

Before we proceed to explain MySQL database system, let's revise few definitions related to
database.

 Database: A database is a collection of tables, with related data.

 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.

 Redundancy: Storing data twice, redundantly to make the system faster.

 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.

 Index: An index in a database resembles an index at the back of a book.

 Referential Integrity: Referential Integrity makes sure that a foreign key value always
points to an existing row.

INTRODUCTION TO ORACLE

The Oracle Database (commonly referred to as Oracle RDBMS or simply as Oracle) is


an object-relational database management system [2] produced and marketed byOracle
Corporation.

7
RDBMS

 ORACLE is a fourth generation relational database management system. In general, a


database management system (DBMS) must be able to reliably manage a large amount of
data in a multi-user environment so that many users can concurrently access the same
data. All this must be accomplished while delivering high performance to the users of the
database. A DBMS must also be secure from unauthorized access and provide efficient
solutions for failure recovery. The ORACLE Server provides efficient and effective
solutions for the major database features.

 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.

 Unlike Oracle8i, which is only a database management system, Oracle9i is a collection of


Following software:

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.

Major database-related products and some of their versions include:

 Oracle Application Server 10g (also known as "Oracle AS 10g"): a middleware product;


 Oracle Applications Release 11i (aka Oracle e-Business Suite, Oracle Financials or
Oracle 11i): a suite of business applications;
 Oracle Developer Suite 10g (9.0.4);
 Oracle JDeveloper 10g: a Java integrated development environment;

Unlike Oracle8i, which is only a database management system, Oracle9i is a collection of


Following software:

Oracle9i Application Server – Oracle9iAS


Oracle9i Database Server – Oracle9iDB
Oracle9i Developer Suite – Oracle9iDS

In simple words Oracle9i is a platform and not a simple database management

8
RDBMS

System

Since version 5, Oracle's RDBMS release numbering has used the following codes:

 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.

How SQL Works


The strengths of SQL provide benefits for all types of users, including application programmers,
database administrators, managers, and end users. Technically speaking, SQL is a data
sublanguage. The purpose of SQL is to provide an interface to a relational database such as
Oracle, and all SQL statements are instructions to the database. In this SQL differs from general-
9
RDBMS

purpose programming languages like C and BASIC. Among the features of SQL are the
following:

 It processes sets of data as groups rather than as individual units.


 It provides automatic navigation to the data.
 It uses statements that are complex and powerful individually, and that therefore stand
alone. Flow-control statements were not part of SQL originally, but they are found in the
recently accepted optional part of SQL, ISO/IEC 9075-5: 1996. Flow-control statements
are commonly known as "persistent stored modules" (PSM), and Oracle's PL/SQL
extension to SQL is similar to PSM.

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.

SQL provides statements for a variety of tasks, including:

 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.

Commonly used statements are grouped into the following categories:

Data Query Language

 SELECT - Used to retrieve certain records from one or more tables.

Data Manipulation Language

 INSERT - Used to create a record.


 UPDATE - Used to change certain records.
 DELETE - Used to delete certain records.

10
RDBMS

Data Definition Language

 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 Control Language

 GRANT - Used to give a privilege to someone.


 REVOKE - Used to take back privileges granted to someone.

DATA TYPE

Data type is here a type of values known by the system which would be filled into the specified
database table column.

Text data types:

 CHARAKTER - text fields


CHAR - same as CHARAKTER

 Numeric data types (exact numeric):

 DECIMAL - a number with decimals


DEC - same as DECIMAL
NUMERIC - same as DECIMAL, but the number of decimals is ...
INTEGER - number without decimals (plain numbers), is used without specifying a field
size
because it is defined by the database system
INT - same as INTEGER
SMALLINT - number without decimals (plain numbers), is used without specifying a
field size
because it is defined by the database system and uses probably less space than
INTEGER, because is designed for small numbers. The format depends on DBMS.

 Numeric data types (approximate numeric):

 FLOAT - numbers in exponential form


REAL - such as FLOAT, but is used without specifying the field size, because it is
defined by the database system.
DOUBLE PRECISION - such as REAL, but probably with doppelten precision
DOUBLE - same as DOUBLE PRECISION

11
RDBMS

Other data types, not defined in the standard SQL:

 DATE - date value, in most European implementations in the following format:


dd.mm.yyyy
TIME - time value, in most European implementations in the following format: hh-mm-
ss
VARCHAR - string with variable length, depending on the implementation maximal 254
to 2048 characters.
LONG VARCHAR - sting with variable length, depending on the implementation
maximal 16 kilobytes.

CHAPTER-2

SQL COMMANDS

Topics Discussed are:

 SQL Data Query Language

 SQL Select query

SQL Select query with different clauses such as:

 Distinct clause
 Where clause
 Or/And clause
 Like clause
 Order by clause
 Unique clause

 SQL DDL Queries

 Create table query.


 Alter query
 Modify query

12
RDBMS

 SQL DML Queries

 Insert query
 Update query
 Delete query

To perform the SQL queries, we have taken the following table structure:

1. emp

Emp table represents employees table.

2. dept
Dept table represents department table.

13
RDBMS

SQL DATA QUERY LANGUAGE

SQL SELECT SATEMENT

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.

There are three ways we can retrieve data from a table:

 Retrieve multiple columns


 Retrieve all columns

Select Multiple Columns

We can use the SELECT statement to retrieve more than one column. Syntax is:-

SELECT  column_name ,column_name FROM  table_name;

For Eg: We want to retrieve the records of empno, ename, sal from emp table

14
RDBMS

Select All Columns

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:-

SELECT * FROM  table_name;

For eg: We want to retrieve all the records for all columns.

SELECT DISTINCT CLAUSE

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:

SELECT  DISTINCT column_name , column_name FROM  table_name;

For eg:- We want to retrieve the distinct deptno from emp table.

SQL WHERE CLAUSE 

The WHERE clause is used to extract only those records that fulfill a specified criterion. It
filters the result set based on certain conditions.

SELECT column1, column2....columnN


FROM table_name
WHERE CONDITION;

For Eg:-We want to retrieve all the records from the columns where deptno=20.

SQL AND/OR CLAUSE 


In the above, we have seen that the WHERE keyword can be used to conditionally select data
from a table. This condition can be a simple condition (like the one presented in the previous
section), or it can be a compound condition.Compound conditions are made up of multiple

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:-

SELECT column1, column2....columnN


FROM table_name
WHERE CONDITION 1 {AND|OR} CONDITION2;

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

SELECT column1, column2....columnN


FROM table_name
WHERE column_name IN (val 1, val 2,...val N);

For eg:-We want to retrieve the records for empno,ename from emp table where deptno in 10,20

SQL LIKE CLAUSE 


LIKE is another keyword that is used in the WHERE clause. Basically, LIKE allows you to do
a search based on a pattern rather than specifying exactly what is desired (as in IN) or spell out a
range (as in BETWEEN). The syntax is as follows:

SELECT column1, column2....columnN


FROM table_name
WHERE column_name LIKE { PATTERN };

For eg:-We want to retrieve the records from emp table where ename is like ‘S%’

18
RDBMS

SQL ORDER BYCLAUSE 


So far, we have seen how to get data out of a table using SELECT and WHERE commands.
Often, however, we need to list the output in a particular order. This could be in ascending order,
in descending order, or could be based on either numerical value or text value. In such cases, we
can use the ORDER BY keyword to achieve our goal. ASC means that the results will be shown
in ascending order, and DESC means that the results will be shown in descending order. If
neither is specified, the default is ASC.

SELECT column1, column2....columnN


FROM table_name
WHERE CONDITION
ORDER BY column_name {ASC|DESC};

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.

SQL UNIQUE CLAUSE

The SELECT UNIQUE term is an Oracle-only SQL statement. It is equivalent to SELECT


DISTINCT. The syntax for SELECT UNIQUE is as follows:

SELECT UNIQUE "column_name"


FROM "table_name";

For Eg:-We want to retrieve the unique deptno from emp table.

19
RDBMS

CREATING ALIAS OF A COLUMN

20
RDBMS

SQL DDL QUERIES


SQL CREATE TABLE QUERY

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.

ALTER TABLE table_name ADD column_name datatype;

For eg:We want to add a nw column named marks in mca2 table.

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,

ALTER TABLE table_name MODIFY COLUMN column_name datatype;

For eg: We want to alter the attribute rollno.

22
RDBMS

SQL INSERT QUERY

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:

INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);

For eg:We want to insert values in the table mca2.

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];

For eg:- We want the name where rollno=125.

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:

DELETE FROM table_name


WHERE {CONDITION};

For eg:We want to delete a record from mca2 table where name=’preeti’.

24
RDBMS

CHAPTER-3

SQL FUNCTIONS

Topics Discussed are:

 Single Row Functions

 Number Functions
 Character functions
 Date Functions
 Conversion Functions

 Group Functions

25
RDBMS

SQL BUILT-IN FUNCTIONS


Oracle provides an extensive set of built in functions and operators for conversion and manipulating the
strings,dates and numbers.Functions are similar to to operators in that they manipulate data items and
return a result.

Oracle functions are divided into two categories:-

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.

Single Row Functions:

The single row functions are categorized into

 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:

SELECT LOWER (‘string’) FROM DUAL;

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:

SELECT UPPER (‘string’) FROM DUAL;

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:

SELECT INITCAP (‘string’) FROM DUAL;

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

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:

SELECT SUBSTR (string,m,[n]) FROM DUAL;

Here, string is the string expression.

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:

SELECT ROUND (m,n) FROM DUAL;

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.

SELECT TRUNC(m,n) FROM DUAL;

For Eg:

32
RDBMS

3. MOD

The Mod function returns the remainder of m divided by n.

SELECT MOD(m,n) FROM DUAL;

4. SQRT

The Sqrt function returns the square root of n.where n is greater than equal to 0.

SELECT SQRT(n) FROM DUAL;

Date Functions
1. SYSDATE

The Sysdate function returns the current oracle database server date and time.

SELECT SYSDATE FROM DUAL;

33
RDBMS

2.. ROUND

The Round function returns the date rounded to the specified format. The Syntax is:

SELECT ROUND(date,[format]) FROM DUAL;

Format is specified like MON,MM,MONTH

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.

FUNCTION NAME PURPOSE


TO_CHAR(date conversion) Transform a date value to varcahr2 value

TO_CHAR(number conversion) Transform a numeric value to varchar2


TO_DATE Converts a character string to its date
equivalent.
TO_NUMBER To convert a character value to a numeric
value.
Some other conversion functions include convert, RAWTOHEX, HEXTORAW,
CHARTOROWID, TO_LOB etc.

(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.

SYNTAX:- TO_CHAR(date_value [, 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 both the MONTH and YEAR in characters.

Here it is showing DAY, MONTH and YEAR in characters.

Here it is showing simply the day of today.

Here it is showing the month in characters and also the TH with date.

Here it is showing the date in proper format.

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])

Where ‘num_format’ is optional, it can be 9,999. (places a comma in designated position),


999.99 (places a decimal point in required position), $9999(returns the numeric value proceeded
by a dollar sign.

Here it is showing simply the number 1234 with $(dollar) sign.

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 commas in number as per 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.

Here it is showing the number with including zeros at empty spaces.

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.

Here it is showing the date as per given format.

Here it is showing month in character form as per given format.

Here it is showing the month in character form.

39
RDBMS

(4) TO_NUMBER:- The TO_NUMBER is used to convert a character value to a number


value.

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

Now Here we are inserting values in specified fields:

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

Combination of Where condition and Group by clause:

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:

SELECT AVG( column_name)

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,

SELECT MAX (column_name)


FROM table_name;

MIN FUNCTION

SQL uses the MIN function to find the maximum value in a column. The syntax for using the
MIN function is,

SELECT MIN (column_name)


FROM table_name;

43
RDBMS

CHAPTER- 4

SUBQUERIES

Topics Discussed are:

 Single-Row Subqueries

44
RDBMS

 Multiple Row Subqueries using :-

 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

Topics Discussed are:

 Introduction to SQL Joins

 Equi Join

48
RDBMS

 Outer Join

 Self Join

 Cartesian Join

INTRODUCTION TO SQL JOINS


The SQL Joins clause is used to combine records from two or more tables in a database. A JOIN
is a means for combining fields from two tables by using values common to each.

SQL EQUI JOINS

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:

SELECT table1.column1, table2.column2...


FROM table1

49
RDBMS

INNER JOIN table2


ON table1.common_field = table2.common_field;

Foe eg:We want to retrieve records for empno,ename,deptno from two different tables such as
emp and dept tables.

SQL OUTER JOINS

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

SQL SELF JOINS

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:

SELECT a.column_name, b.column_name...


FROM table1 a, table1 b
WHERE a.common_field = b.common_field;

Here, WHERE clause could be any given expression based on your requirement.

51
RDBMS

SQL CARTESIAN JOINS

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:

SELECT table1.column1, table2.column2...

FROM table1, table2 [, table3 ]

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

You might also like