0% found this document useful (0 votes)
42 views35 pages

II DCME DBMS Unit-2

Uploaded by

Thota Srinivas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views35 pages

II DCME DBMS Unit-2

Uploaded by

Thota Srinivas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

UNIT-II (DBMS)

EMBEDDED SQL AND LEXICAL CONVENTIONS


Embedded SQL is the one which combines the high-level language with the DB language like SQL. It
allows the application languages to communicate with DB and get requested result. The high-level
languages which supports embedding SQLs within I are also known as host language. host languages
support embedding SQL within it like C, C++ , ADA , Pascal, FORTRAN, Java etc. compilation takes
place in two steps one for SQL and one for application language. Hence these types of compilation
require all the query, data value etc to be known at the compilation time itself to generate the
executable code.

Lexical Conventions
SQL statements are composed of commands variables and operators which are described m detail in
this and subsequent chapters A SQL statement is constructed from
- Characters A through Z (or the equivalent from your database character ser)
- Numbers 0 through 9
- Spaces
- The following special characters : + - * = ? ! @ ( ) _ . , < > | $ #

Note : Oracle strongly discourages the use of and 5


A SQL statement can contain one or more of the following items anywhere a single space can occur . .
Tab
. Carriage return
. Multiple spaces
. Comments
Note: Certain components of SQL statements (such as variable names and strings) may contain other
characters, as long as they are enclosed in double quotes

Naming in SQL: The following rules apply to the names of schema objects in Oracle •
❖ They may comprise 1 to 30 alphanumeric characters
❖ They must begin with a letter
❖ They may include an underscore (_) They may include a dollar (5) or pound sign (#) although
Oracle discourages the use of these characters They may not be a reserved word
❖ They may not be the name of a SQL command

Oracle provides a number of utilities to facilitate your SQL development process:


.SQL*Plus: SQL*Plus is a command line SQL

• Oracle JDeveloper development environment for Java It supports editing, compiling and debugging
PL/SQL applications.
.Oracle HTML DB is used for developing and deploying database related Web applications PL/SQL:

Procedural language extension to SQL


• SQL *FORM: To design forms
.SQL *REPORT: To generate reports.
.PRO *C :Embedded SQL support.

1 | Page
UNIT-II (DBMS)

NAMING OF THE OBJECTS AND PARTS


Objects of SQL A database abject is any defined object in a database that is use to store or reference
data Anything which we make from create command is kno as Database Object. Examples of
database. objects are view sequence, indexes, etc

Table: Basic unit of storage composed rows and columns

View: Logically represents subsets of data from one or more tables

Sequence :Generates primary key values

Index :improves the performance of some queries

Synonym: Alternative name for an object

Generally, you reference schema objects in SQL statements using the following syntax
Schema object_name.object_part@dblink
These syntax elements have the following meaning

• Schema: The name of the schema that owns the object. In Oracle, a schema corresponds one-to-one
with a username if the schema is omitted from a reference to a schema object then the username that is
currently logged in a used by default.

• Object name: The name of the object being referenced, such as a table that

• Object part: The name of a part of an object for those schema objects have a part such as a column
of a table

• dblink :The name of a database link referencing a remote database

For example:
SELECT ename, empno, sal
FROM scott.emp@test
WHERE sal> 500;

LITERALS TEXT INTEGER NUMBER


Literal is fixed data value. There are four kinds of literals supported in SQL. They are ❖ Text or
character literal
❖ Bit strings
❖ Numeric literals
❖ Date and Time Literals

TEXT OR CHARACTER
Character or text literals are written as sequence of strings written as a sequence character enclosed in
single quotes
2 | Page
UNIT-II (DBMS)

Example:
❖ 'Structured Query Language'
❖ 'Jessica Pearson '
❖ '08065-CM-009'

BIT STRING
A bit string is written either as a sequence of Os and is enclosed in single quotes and preceded by the
letter ' B ' or as sequence of hexadecimal digits enclosed in single quotes and preceded by letter 'X'
Example:
❖ B '1011011'
❖ B'1'
❖ X'A5'

Numeric Literals are used to construct exact numbers and approximate number Syntax rules of
numeric literals are:
A numeric literal can be written in signed integer form, signed real numbers without exponents, or real
numbers with exponents
Examples of Numeric Literals
Quote:
❖1
❖ -22
❖ 33.3
❖ -44 .44
❖ 55.555e5

Date and Time Literals are used to construct date and time values The syntax of date and time literals
are

➢ A date literal is written in the form of


"DATE 'yyyy-mm-dd' " .
➢ A time literal is written in the form of
"TIMESTAMP 'yyyy-mm-dd hh:mm:ss' ".

DATA TYPES:

1. CHAR (Size): This data type is used to store character strings values of fixed length. The size in
brackets determines the number of characters the cell can hold. The maximum number of character is
255 characters.

2. VARCHAR (Size) / VERCHAR2 (Size): This data type is used to store variable length
alphanumeric data. The maximum character can hold is 2000 character.

3. NUMBER (P, S): The NUMBER data type is used to store number (fixed or floating point).
124
Number of virtually any magnitude may be stored up to 38 digits of precision. Number as large as 9.99 * 10 .
3 | Page
UNIT-II (DBMS)

4. DATE: This data type is used to represent date and time. The standard format is DD MM-YY as in
17-SEP-2009. To enter dates other than the standard format, use the appropriate functions. Date time
stores date in the 24-Hours format. By default the time in a date field is 12:00:00 am, if no time
portion is specified. The default date for a date field is the first day the current month.

5. LONG: This data type is used to store variable length character strings containing up to 2GB. Long
data can be used to store arrays of binary data in ASCII format. LONG values cannot be indexed, and
the normal character functions such as SUBSTR cannot be applied.
6. RAW: The RAW data type is used to store binary data, such as digitized picture or image. Data
loaded into columns of these data types are stored without any further conversion. RAW data type can
have a maximum length of 255 bytes. LONG RAW data type can contain up to 2GB.

SQL STATEMENTS:

There are five types of SQL statements. They are:


1. DATA DEFINITION LANGUAGE (DDL)
2. DATA MANIPULATION LANGUAGE (DML)
3. DATA RETRIEVAL LANGUAGE (DRL)
4. TRANSATIONAL CONTROL LANGUAGE (TCL)
5. DATA CONTROL LANGUAGE (DCL)

1. DATA DEFINITION LANGUAGE (DDL): The Data Definition Language (DDL) is used to
create and destroy databases and database objects. These commands will primarily be used by
database administrators during the setup and removal phases of a database project. Let's take a look at
the structure and usage of four basic DDL commands:
1. CREATE 2. ALTER 3. DROP 4. RENAME 1. CREATE:
(a)CREATE TABLE: This is used to create a new relation and the corresponding Syntax: CREATE
TABLE relation_name

(field_1 data_type(Size),field_2 data_type(Size), .. . );

Example:
SQL>CREATE TABLE Student (sno NUMBER(3),sname CHAR(10),class CHAR(5));

(b)CREATE TABLE..AS SELECT....: This is used to create the structure of a new relation from the
structure of an existing relation.
4 | Page
UNIT-II (DBMS)

Syntax: CREATE TABLE (relation_name_1, field_1,field_2,.....field_n)AS SELECT


field_1,field_2,...........field_n FROM relation_name_2;
Example: SQL>CREATE TABLE std(rno,sname)AS SELECT sno,sname FROM student;

2. ALTER:
(a)ALTER TABLE ...ADD...: This is used to add some extra fields into existing relation. Syntax:
ALTER TABLE relation_name ADD(new field_1 data_type(size), new field_2 data_type(size),..);

2
Example : SQL>ALTER TABLE std ADD(Address CHAR(10));

(b)ALTER TABLE...MODIFY...: This is used to change the width as well as data type of fields of
existing relations.
Syntax: ALTER TABLE relation_name MODIFY (field_1 newdata_type(Size), field_2
newdata_type(Size),....field_newdata_type(Size));
Example:SQL>ALTER TABLE student MODIFY(sname VARCHAR(10),class VARCHAR(5));
3. DROP TABLE: This is used to delete the structure of a relation. It permanently deletes the records
in the table.
Syntax: DROP TABLE relation_name;

Example: SQL>DROP TABLE std;

4. RENAME: It is used to modify the name of the existing database object. Syntax: RENAME
TABLE old_relation_name TO new_relation_name; Example: SQL>RENAME TABLE std TO std1;

5. TRUNCATE: This command will remove the data permanently. But structure will not be removed.
Syntax: TRUNCATE TABLE <Table name>

Example TRUNCATE TABLE student;

Difference between Truncate & Delete:-

5 | Page
UNIT-II (DBMS)

✓ By using truncate command data will be removed permanently & will not get back where as by
using delete command data will be removed temporally & get back by using roll back command.
✓ By using delete command data will be removed based on the condition where as by using truncate
command there is no condition.
✓ Truncate is a DDL command & delete is a DML command.

2. DATA MANIPULATION LANGUAGE (DML): The Data Manipulation Language (DML) is


used to retrieve, insert and modify database information. These commands will be used by all database
users during the routine operation of the database. Let's take a brief look at the basic DML commands:
1. INSERT 2. UPDATE 3. DELETE
1. INSERT INTO: This is used to add records into a relation. These are three type of INSERT INTO
queries which are as
a) Inserting a single record
Syntax: INSERT INTO relationname(field_1,field_2,.field_n)VALUES
(data_1,data_2,........data_n);
Example: SQL>INSERT INTO student(sno,sname,class,address)VALUES
(1,’Ravi’,’M.Tech’,’Palakol’);
b) Inserting all records from another relation
Syntax: INSERT INTO relation_name_1 SELECT Field_1,field_2,field_n FROM relation_name_2
WHERE field_x=data;
Example: SQL>INSERT INTO std SELECT sno,sname FROM student WHERE name = ‘Ramu‘;

c) Inserting multiple records


Syntax: INSERT INTO relation_name field_1,field_2,.....field_n)
VALUES(&data_1,&data_2,........&data_n);
Example: SQL>INSERT INTO student(sno,sname,class,address)
VALUES(&sno,’&sname’,’&class’,’&address’);
Enter value for sno: 101 Enter value for
name: Ravi Enter value for class:
M.Tech Enter value for name: Palakol
2. UPDATE-SET-WHERE: This is used to update the content of a record in a relation. Syntax:
SQL>UPDATE relation name SET Field_name1=data,field_name2=data, WHERE field_name=data;
Example: SQL>UPDATE student SET sname = ‘kumar’ WHERE sno=1;

6 | Page
UNIT-II (DBMS)

3. DELETE-FROM: This is used to delete all the records of a relation but it will retain the structure
of that relation.
4.
a) DELETE-FROM: This is used to delete all the records of relation. Syntax: SQL>DELETE FROM
relation_name;

Example: SQL>DELETE FROM std;

b) DELETE -FROM-WHERE: This is used to delete a selected record from a relation. Syntax:
SQL>DELETE FROM relation_name WHERE condition; Example: SQL>DELETE FROM student
WHERE sno = 2;

3. DQL(DATA QUERY LANGUAGE): Retrieves data from one or more tables.

1. SELECT FROM: To display all fields for all


records. Syntax : SELECT * FROM
relation_name; Example : SQL> select * from
dept;
DEPTNO DNAME LOC
-------- ----------- ----------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

2. SELECT FROM: To display a set of fields for all records of relation. Syntax: SELECT a set of
fields FROM relation_name;
Example: SQL> select deptno, dname from dept; DEPTNO
DNAME
------- ----------
10 ACCOUNTING
20 RESEARCH
30 SALES

7 | Page
UNIT-II (DBMS)

3. SELECT - FROM -WHERE: This query is used to display a selected set of fields for a selected
set of records of a relation.
Syntax: SELECT a set of fields FROMrelation_name WHERE condition; Example: SQL> select *
FROM dept WHERE deptno<=20;
DEPTNO DNAME LOC
------ ----------- ------------
5
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS

4. SELECT - FROM -GROUP BY: This query is used to group to all the records in a relation
together for each and every value of a specific key(s) and then display them for a selected set of fields
the relation.
Syntax: SELECT a set of fields FROM relation_name GROUP BY field_name;
Example: SQL> SELECT EMPNO, SUM (SALARY) FROM EMP GROUP BY EMPNO; EMPNO
SUM (SALARY)
------ ---------- 1
3000
2 4000
3 5000
4 6000
4 rows selected.

5. SELECT - FROM -ORDER BY: This query is used to display a selected set of fields from a
relation in an ordered manner base on some field.
Syntax: SELECT a set of fields FROM relation_name ORDER
BY field_name;

Example: SQL> SELECT empno,ename,job FROM emp ORDER BY job; EMPNO ENAME JOB
----- --------- --------

4 RAVI MANAG
ER
8 | Page
UNIT-II (DBMS)

2 aravind Manager
1 Sagar clerk
3 Laki clerk
4rows selected.

6. JOIN using SELECT - FROM - ORDER BY: This query is used to display a set of fields from
two relations by matching a common field in them in an ordered manner based on some fields.
Syntax: SELECT a set of fields from both relations FROM relation_1, relation_2 WHERE
relation_1.field_x = relation_2.field_y ORDER BY field_z;
6 Example: SQL>SELECT empno,ename,job,dname FROM emp,dept WHERE emp.deptno = 20
ORDER BY job;
EMPNO ENAME JOB DNAME
------ ------ ------- ----------
7788 SCOTT ANALYST ACCOUNTI
NG
7902 FORD ANALYST ACCOUNTI
NG
------
7566 JONES MANAGE R OPERATION S
7566 JONES MANAGE R SALES
20 rows selected.

7. JOIN using SELECT - FROM - GROUP BY:


This query is used to display a set of fields from two relations by matching a common field in
them and also group the corresponding records for each and every value of a specified key(s)
while displaying.
Syntax:
SELECT a set of fields from both relations FROM relation_1,relation_2 WHERE
relation_1.field-x=relation_2.field- y GROUP BY field-z;
Example: SQL> SELECT empno,SUM(SALARY) FROM emp,dept WHERE emp.deptno =20
GROUP BY empno;
EMPNO SUM(SALARY)
------- --------
7369 3200
7566 11900
7788 12000

9 | Page
UNIT-II (DBMS)

7876 4400

8.HAVING:

This will work as where clause which can be used only with group by because of
absence of where clause in group by.

Ex:

SQL> select deptno,job,sum(sal) tsal from emp group by deptno,job having sum(sal) > 3000;

SQL> select deptno,job,sum(sal) tsal from emp group by deptno,job having sum(sal) > 3000

order by job;

3. TRANSATIONAL CONTROL LANGUAGE (T.C.L):

A transaction is a logical unit of work. All changes made to the database can be referred
to as a transaction. Transaction changes can be made permanent to the database only if they are
committed a transaction begins with an executable SQL statement & ends explicitly with either
role back or commit statement.

1. COMMIT: This command is used to end a transaction only with the help of the commit
command transaction changes can be made permanent to the database.

Syntax: SQL>COMMIT;

Example: SQL>COMMIT

2. SAVE POINT: Save points are like marks to divide a very lengthy transaction to smaller
once. They are used to identify a point in a transaction to which we can latter role back.
Thus, save point is used in conjunction with role back.

Syntax: SQL>SAVE POINT ID;

Example: SQL>SAVE POINT xyz;

10 | Page
UNIT-II (DBMS)

8
3. ROLE BACK: A role back command is used to undo the current transactions. We can
role back the entire transaction so that all changes made by SQL statements are undo (or)
role back a transaction to a save point so that the SQL statements after the save point are role
back.

Syntax: ROLE BACK( current transaction can be role back) ROLE BACK to save point ID;

Example: SQL>ROLE BACK;

SQL>ROLE BACK TO SAVE POINT xyz;

4. DATA CONTROL LANGUAGE (D.C.L):


DCL provides uses with privilege commands the owner of database objects (tables),
has the soul authority ollas them. The owner (data base administrators) can allow other data
base uses to access the objects as per their requirement

1. GRANT: The GRANT command allows granting various privileges to other users and
allowing them to perform operations with in their privileges
For Example, if a uses is granted as „SELECT‟ privilege then he/she can only view data but
cannot perform any other DML operations on the data base object GRANTED privileges can
also be withdrawn by the DBA at any time

Syntax: SQL>GRANT PRIVILEGES on object_name To user_name;


Example: SQL>GRANT SELECT, UPDATE on emp To hemanth;

2. REVOKE: To with draw the privileges that has been GRANTED to a uses, we use the
REVOKE command.

Syntax: SQL>REVOKE PRIVILEGES ON object-name FROM user_name; Example:


SQL>REVOKE SELECT, UPDATE ON emp FROM ravi;

11 | Page
UNIT-II (DBMS)

INTEGRITY CONSTRAINTS IN CREATING A TABLE AND ALTERING A TABLE:

1. NOT NULL: When a column is defined as NOTNULL, then that column becomes a
mandatory column. It implies that a value must be entered into the column if the record is to
be accepted for storage in the table.
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) NOT NULL, );

Example:
CREATE TABLE student (sno NUMBER(3)NOT NULL, name CHAR(10));

2. UNIQUE: The purpose of a unique key is to ensure that information in the column(s) is
unique i.e. a value entered in column(s) defined in the unique constraint must not be repeated
across the column(s). A table may have many unique keys.
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) UNIQUE, ….);

Example:
CREATE TABLE student (sno NUMBER(3) UNIQUE, name CHAR(10));

3. CHECK: Specifies a condition that each row in the table must satisfy. To satisfy the
constraint, each row in the table must make the condition either TRUE or unknown (due to a
null).
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) CHECK(logical
expression), ….);

Example: CREATE TABLE student (sno NUMBER (3), name CHAR(10),class


CHAR(5),CHECK(class IN(‘CSE’,’CAD’,’VLSI’));

4. PRIMARY KEY: A field which is used to identify a record uniquely. A column or


combination of columns can be created as primary key, which can be used as a reference
from other tables. A table contains primary key is known as Master Table.

12 | Page
UNIT-II (DBMS)

10
✓ It must uniquely identify each record in a table.
✓ It must contain unique values.
✓ It cannot be a null field.
✓ It cannot be multi port field.
✓ It should contain a minimum no. of fields necessary to be called unique. Syntax:
CREATE TABLE Table_Name(column_name data_type(size) PRIMARY KEY, ….);

Example:
CREATE TABLE faculty (fcode NUMBER(3) PRIMARY KEY, fname CHAR(10));

5. FOREIGN KEY: It is a table level constraint. We cannot add this at column level. To
reference any primary key column from other table this constraint can be used. The table in
which the foreign key is defined is called a detail table. The table that defines the primary
key and is referenced by the foreign key is called the master table.
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) FOREIGN
KEY(column_name) REFERENCES table_name);

13 | Page
UNIT-II (DBMS)

DEFINING INTEGRITY CONSTRAINTS IN THE ALTER TABLE: Syntax:

ALTER TABLE Table_Name ADD PRIMARY KEY (column_name); Example:

ALTER TABLE student ADD PRIMARY KEY (sno);

(Or)
Syntax: ALTER TABLE table_name ADD CONSTRAINT constraint_name

PRIMARY KEY(colname)

Example: ALTER TABLE student ADD CONSTRAINT SN PRIMARY


KEY(SNO)

Dropping integrity constraints in the alter table


command: Syntax: ALTER TABLE Table_Name
DROP constraint_name; Example: ALTER
TABLE student DROP PRIMARY KEY;

(or)
Syntax: ALTER TABLE student DROP CONSTRAINT constraint_name;

Example: ALTER TABLE student DROP CONSTRAINT SN; SQL

OPERATORS:

Operators :-
An operator manipulates individual data items and returns a result. The data items
are called operands or arguments.
Operators are represented by special characters or by keywords. These can be
divided into 4 types.
1) Arithmetic operators
2) Comparison operators
3) Logical operators
4) Set operators

Arithmeticoperators :-

+, -, *, /

14 | Page
UNIT-II (DBMS)
12
Comparison operators:-

= =, !=, >, <, >=, <=,

Logical operators: -

AND , OR , NOT

Set Operators: -
Set operators combine the results of two component queries into a single result.
Queries containing set operators are called compound queries.

OPERATORS RETURNS
UNION All rows selected by either query.
UNION ALL rows selected by either query, including all duplicates.
INTERSECT All distinct rows selected by both queries.
MINUS All distinct rows selected by the first query but not the second.

1.Arithmetic Operators
Arithmetic operators can perform arithmetical operations on numeric operands
involved. Arithmetic operators are
addition(+),
subtraction(-),
multiplication(*)
and division(/).
The + and - operators can also be used in date arithmetic.

SELECT <Expression>[arithmetic operator]<expression>... FROM [table_name]


WHERE [expression];

Comparison operators:-

a) USING =, >, <, >=, <=, !=,

Ex:=

SQL> select * from student where no = 2;

<

15 | Page
UNIT-II (DBMS)
SQL> select * from student where no < 2;

14
>

SQL> select * from student where no > 2;

<=

SQL> select * from student where no <= 2;

>=

SQL> select * from student where no >= 2;

!=

SQL> select * from student where no != 2;

Logical operators: -

AND : -This will gives the output when all the conditions become true. Syntax:

select * from <table name> where <condition1> and <condition2> and .. <conditionn>;

Ex:SQL> select * from student where no = 2 and marks >= 200;

OR:-This will give the output when either of the conditions becomes true. Syntax: select *

from <table_name> where <condition1> and <condition2> or .. <condition>; Ex:SQL>

select * from student where no = 2 or marks >= 200;

BETWEEN:-

This will gives the output based on the column and its lower bound, upperbound.

Syntax: select * from <table_name> where <col> between <lower bound> and <upper
bound>;
Ex:SQL> select * from student where marks between 200 and 400;

NOT BETWEEN:-This will gives the output based on the column which values are not in
its lower bound,upperbound.

16 | Page
UNIT-II (DBMS)
Syntax: select * from <table_name> where <col> not between <lower bound> and <upper
bound>;

Ex: SQL> select * from student where marks not between 200 and 400; IN:-This will gives

the output based on the column and its list of values specified. Syntax: select * from

<table_name> where <col> in ( value1, value2, value3 … valuen); Ex: SQL> select * from

student where no in (1, 2, 3);

NOT IN:- This will gives the output based on the column which values are not in the list of
valuesspecified.

Syntax: select * from <table_name> where <col> not in ( value1, value2, value3 … valuen);

Ex: SQL> select * from student where no not in (1, 2, 3);

NULL:-

This will gives the output based on the null values in the specified column. Syntax: select *

from <table_name> where <col> is null;

Ex: SQL> select * from student where marks is null;

NOT NULL:- This will gives the output based on the not null values in the specified
column.

Syntax: select * from <table_name> where <col name> is not null;

Ex: SQL> select * from student where marks is not null;

UNION:-

This will combine the records of multiple tables having the same structure. Ex: SQL> select

* from student1 union select * from student2;

UNION ALL:-

This will combine the records of multiple tables having the same structure but
includingduplicates.

Ex: SQL> select * from student1 union all select * from student2;

INTERSECT :-

17 | Page
UNIT-II (DBMS)
This will give the common records of multiple tables having the same structure. Ex: SQL>

select * from student1 intersect select * from student2;

MINUS :-

This will give the records of a table whose records are not in other tables having the
samestructure.

Ex: SQL> select * from student1 minus select * from student2;

FUNCTIONS

Functions can be categorized as follows.

• Single row functions


• Group functions
SINGLE ROW FUNCTIONS:-
Single row functions can be categorized into five. These will be applied for each row and

produces individual output for each row.

• Numeric functions
• String functions
• Date functions
• Conversion functions

NUMERIC FUNCTIONS

Abs,Sqrt, Mod, Power, Ceil,Floor,Round,Greatest,Least


a) ABS

Absolute value is the measure of the magnitude of value.Absolute value is always a


positive number.

Syntax: abs (value)

Ex: SQL> select abs(5), abs(-5), abs(0), abs(null) from dual;

SQL>select abs(sno) from student;

18 | Page
UNIT-II (DBMS)
SQL> update Mahesh set sno=abs(sno);

b) SQRT:This will give the square root of the given value.

Syntax: sqrt (value) -- here value must be positive.

Ex:SQL> select sqrt(4), sqrt(0), sqrt(null), sqrt(1) from dual;

c) MOD:This will give the remainder.

Syntax: mod (value, divisor)

Ex:SQL> select mod(7,4), mod(1,5), mod(null,null), mod(0,0), mod(-7,4) from dual; d)

POWER:-

Power is the ability to raise a value to a given exponent.

Syntax: power (value, exponent)

Ex:SQL> select power(2,5), power(0,0), power(1,1), power(null,null), power(2,-5) from

dual;

e) CEIL: This will produce a whole number that is greater than or equal to the specified
value.

Syntax: ceil (value)

Ex: SQL> select ceil(5), ceil(5.1), ceil(-5), ceil( -5.1), ceil(0), ceil(null) from dual;

f) FLOOR

This will produce a whole number that is less than or equal to the specified value.

Syntax: floor (value)

Ex:
SQL> select floor(5), floor(5.1), floor(-5), floor( -5.1), floor(0), floor(null) from dual;

g) ROUND

This will rounds numbers to a given number of digits of precision.


Syntax: round (value, precision)

Ex:SQL> select round(123.2345), round(123.2345,2), round(123.2354,2) from dual;

19 | Page
UNIT-II (DBMS)
h) GREATEST

This will give the greatest number.

Syntax: greatest (value1, value2, value3 … valuen)

Ex:SQL> select greatest(1, 2, 3), greatest(-1, -2, -3) from dual;

i) LEAST

This will give the least number.

Syntax: least (value1, value2, value3 … valuen)

Ex: SQL> select least(1, 2, 3), least(-1, -2, -3) from dual;

j) COALESCE

This will return first non-null value.

Syntax: coalesce (value1, value2, value3 … valuen)

Ex:SQL> select coalesce(1,2,3), coalesce(null,2,null,5) from dual; STRING

FUNCTIONS
Initcap
Upper
Lower
Length
Rpad
Lpad
Ltrim
Rtrim
Trim
Translate
Replace
Soundex
Concat (‘ || ‘ Concatenation operator)
Ascii

20 | Page
UNIT-II (DBMS)
Chr
Substr
Instr
Decode
Greatest
Least
Coalesce

a) INITCAP

This will capitalize the initial letter of the string.

Syntax: initcap (string)

Ex:

SQL> select initcap('computer') from dual;

SQL> select initcap(sname) from students;

SQL>update students set student_name=initcap(student_name);

b) UPPER

This will convert the string into uppercase. Syntax: upper (string)

Ex:SQL> select upper('computer') from dual;

SQL> select upper(sname) from students;

SQL>update students set student_name=upper(student_name);

c) LOWER

This will convert the string into lowercase. Syntax: lower (string)

Ex:SQL> select lower('COMPUTER') from dual;

21 | Page
UNIT-II (DBMS)
SQL> select lower(sname) from students;

SQL>update students set student_name=lower(student_name);

d) LENGTH

This will give length of the string.

Syntax: length (string)

Ex:SQL> select length('computer') from dual;

SQL> select length(sname) from students;

e) RPAD

This will allows you to pad the right side of a column with any set of characters. Syntax:

rpad (string, length [, padding_char])

Ex:SQL> select rpad('computer',15,'*'), rpad('computer',15,'*#') from dual; f) LPADThis

will allows you to pad the left side of a column with any set of characters. Syntax: lpad

(string, length [, padding_char])

Ex:SQL> select lpad('computer',15,'*'), lpad('computer',15,'*#') from dual; -- Default

padding character was blank space.

g) LTRIM

This will trim off unwanted characters from the left end of string. Syntax: ltrim (string

[,unwanted_chars])

Ex:SQL> select ltrim('computer','co'), ltrim('computer','com') from dual; SQL> select

ltrim('computer','puter'), ltrim('computer','omputer') from dual; SQL>update students set

student_name=ltrim(student_name,’s’);

h) RTRIM

22 | Page
UNIT-II (DBMS)
This will trim off unwanted characters from the right end of string. Syntax: rtrim (string [,

unwanted_chars])

Ex:SQL> select rtrim('computer','er'), rtrim('computer','ter') from dual; SQL> select

rtrim('computer','comput’), rtrim('computer','compute') from dual; SQL>update students set

student_name=rtrim(student_name,’s’);

i) TRIM

This will trim off unwanted characters from the both sides of string. Syntax: trim

(unwanted_chars from string)

Ex:SQL> select trim( 'i' from 'indiani') from dual;

SQL> select trim( leading'i' from 'indiani') from dual; -- this will work as LTRIM SQL>

select trim( trailing'i' from 'indiani') from dual; -- this will work as RTRIM sQL>update

students set student_name=trim('A' from student_name)

j) TRANSLATE

This will replace the set of characters, character by character. Syntax: translate (string,

old_chars, new_chars)

Ex:SQL> select translate('india','in','xy') from dual;

k) REPLACE

This will replace the set of characters, string by string. Syntax: replace (string, old_chars [,

new_chars])

Ex:SQL> select replace('india','in','xy'), replace(‘india’,’in’) from dual; SQL>update

students set student_name=replace(student_name,'h','o')

l) SOUNDEX
This will be used to find words that sound like other words, exclusively used in where
clause.

23 | Page
UNIT-II (DBMS)
Syntax: soundex (string)

Ex:SQL> select * from emp where soundex(ename) = soundex('SMIT');

m) CONCAT

This will be used to combine two strings only.

Syntax: concat (string1, string2)

Ex:SQL> select concat('computer',' operator') from dual;

SQL>update students set student_name=concat(student_name,’ hai’) where sno=100;

n) ASCII

This will return the decimal representation in the database character set of the
firstcharacter of the string.

Syntax: ascii (string)

Ex:
22
SQL> select ascii('a'), ascii('apple') from dual;

o) CHR

This will return the character having the binary equivalent to the string in either thedatabase
character set or the national character set.

Syntax: chr (number)

Ex:SQL> select chr(97) from dual;

p) SUBSTR

This will be used to extract substrings.

Syntax: substr (string, start_chr_count [, no_of_chars])

Ex:SQL> select substr('computer',2), substr('computer',2,5), substr('computer',3,7) from

dual;

12345678

24 | Page
UNIT-II (DBMS)
COMPUTER

-8 -7 -6 -5 -4 -3 -2 -1

q) INSTR

This will allows you for searching through a string for set of characters. Syntax: instr

(string, search_str [, start_chr_count [, occurrence] ])

Ex:SQL> select instr('information','o',4,1), instr('information','o',4,2) from dual; r) DECODE

will act as value by value substitution.

For every value of field, it will checks for a match in a series of if/then tests. Syntax: decode

(value, if1, then1, if2, then2, ……. else);

Ex:SQL> select sal, decode(sal,500,'Low',5000,'High','Medium') from emp;

s) GREATEST
This will give the greatest string.

Syntax: greatest (strng1, string2, string3 … stringn)

Ex:SQL> select greatest('a', 'b', 'c'), greatest('satish','srinu','saketh') from dual;

t) LEAST
This will give the least string.

Syntax: greatest (strng1, string2, string3 … stringn)


Ex:SQL> select least('a', 'b', 'c'), least('satish','srinu','saketh') from dual;
u) COALESCE

This will gives the first non-null string.

Syntax: coalesce (strng1, string2, string3 … stringn)

Ex:SQL> select coalesce('a','b','c'), coalesce(null,'a',null,'b') from dual;

DATE FUNCTIONS

Sysdate

25 | Page
UNIT-II (DBMS)
Current_date

Current_timestamp

Systimestamp

Localtimestamp

Dbtimezone

Sessiontimezone

To_char

To_date

Add_months

Months_between

Next_day

Last_day

Extract

Greatest

Least

Round

Trunc

New_time
Coalesce
Oracle default date format is DD-MON-YY.We can change the default format to our
desired format by using the following command.
SQL> alter session set nls_date_format = ‘DD-MONTH-YYYY’;
But this will expire once the session was closed.

a) SYSDATE

This will give the current date and time.

26 | Page
UNIT-II (DBMS)
Ex:

SQL> select sysdate from dual;

b) CURRENT_DATE

This will returns the current date in the session’s timezone.

Ex:SQL> select current_date from dual;

c) CURRENT_TIMESTAMP

This will returns the current timestamp with the active time zone information. Ex:SQL>

select current_timestamp from dual;

d) SYSTIMESTAMP
This will returns the system date, including fractional seconds and time zone of the

database.

Ex:SQL> select systimestamp from dual;

e) LOCALTIMESTAMP

This will returns local timestamp in the active time zone information, with no time
zoneinformation shown.
Ex:SQL> select localtimestamp from dual;

f) DBTIMEZONE

This will returns the current database time zone in UTC format. (Coordinated Universal
Time)

Ex:SQL> select dbtimezone from dual;

g) SESSIONTIMEZONE

This will returns the value of the current session’s time zone.

Ex:QL> select sessiontimezone from dual;


DATE FORMATS
• D -- No of days in week
• DD -- No of days in month
• DDD -- No of days in year
• MM -- No of month
• MON -- Three letter abbreviation of month

27 | Page
UNIT-II (DBMS)
• MONTH -- Fully spelled out month
• RM -- Roman numeral month
• DY -- Three letter abbreviated day
• DAY -- Fully spelled out day
• Y -- Last one digit of the year
• YY -- Last two digits of the year
• YYY -- Last three digits of the year
• YYYY -- Full four digit year

h) TO_CHAR
This will be used to extract various date formats.The available date formats as follows.

Syntax: to_char (date, format)

Ex:
SQL> select to_char(sysdate,'dd month yyyy hh:mi:ss am dy') from dual; SQL> select

to_char(sysdate,'dd month year') from dual;

SQL> select to_char(sysdate,'dd fmmonth year') from dual;

SQL> select to_char(sysdate,'ddth DDTH') from dual;


SQL> select to_char(sysdate,'ddspth DDSPTH') from dual;
SQL> select to_char(sysdate,'ddsp Ddsp DDSP ') from dual;

i) TO_DATE

This will be used to convert the string into date format.

Syntax: to_date (date)

Ex:SQL> select to_char(to_date('24/dec/2006','dd/mon/yyyy'), 'dd * month * day') from


dual;

If you are not using to_char oracle will display output in default date format.

j) ADD_MONTHS

This will add the specified months to the given date.

Syntax: add_months (date, no_of_months)

Ex:SQL> select add_months(to_date('11-jan-1990','dd-mon-yyyy'), 5) from dual; SQL>

select add_months(to_date('11-jan-1990','dd-mon-yyyy'), -5) from dual; If

28 | Page
UNIT-II (DBMS)
no_of_months is zero then it will display the same date.

If no_of_months is null then it will display nothing.


k) MONTHS_BETWEEN

This will give difference of months between two dates. Syntax: months_between (date1,

date2)

Ex:SQL> select months_between(to_date('11-aug-1990','dd-mon-yyyy'), to_date('11-jan

1990','dd-mon-yyyy')) from dual;

SQL> select months_between(to_date('11-jan-1990','dd-mon-yyyy'), to_date('11-aug

1990','dd-mon-yyyy')) from dual;

l) NEXT_DAY
This will produce next day of the given day from the specified date. Syntax: next_day (date,

day)

Ex:

SQL> select next_day(to_date('24-dec-2006','dd-mon-yyyy'),'sun') from dual; -- If the day

parameter is null then it will display nothing.

m) LAST_DAY

This will produce last day of the given date.

Syntax: last_day (date)

Ex:
SQL> select last_day(to_date('24-dec-2006','dd-mon-yyyy'),'sun') from dual;

n) EXTRACT

This is used to extract a portion of the date value.

Syntax: extract ((year | month | day | hour | minute | second), date) Ex:

SQL> select extract(year from sysdate) from dual;

-- You can extract only one value at a time.

29 | Page
UNIT-II (DBMS)
o) GREATEST

This will give the greatest date.

Syntax: greatest (date1, date2, date3 … daten)

Ex:

SQL> select greatest(to_date('11-jan-90','dd-mon-yy'),to_date('11-mar-90','dd-mon


yy'),to_date('11-apr-90','dd-mon-yy')) from dual;

p) LEAST

This will give the least date.

Syntax: least (date1, date2, date3 … daten)


Ex:

SQL> select least(to_date('11-jan-90','dd-mon-yy'),to_date('11-mar-90','dd-mon


yy'),to_date('11-apr-90','dd-mon-yy')) from dual;

q) ROUND
Round will rounds the date to which it was equal to or greater than the given date. Syntax:

round (date, (day | month | year))

SQL> select round(to_date('24-dec-04','dd-mon-yy'),'year'), round(to_date('11-mar

06','dd-mon-yy'),'year') from dual;

SQL> select round(to_date('11-jan-04','dd-mon-yy'),'month'), round(to_date('18-jan

04','dd-mon-yy'),'month') from dual;

SQL> select round(to_date('26-dec-06','dd-mon-yy'),'day'), round(to_date('29-dec

06','dd-mon-yy'),'day') from dual;

SQL> select to_char(round(to_date('24-dec-06','dd-mon-yy')), 'dd mon yyyy hh:mi:ss am')

from dual;

s) NEW_TIME

This will give the desired timezone’s date and time.

Syntax: new_time (date, current_timezone, desired_timezone)


Available timezones are as follows.

30 | Page
UNIT-II (DBMS)
TIMEZONES

• AST/ADT -- Atlantic standard/day light time


• BST/BDT -- Bering standard/day light time
• CST/CDT -- Central standard/day light time
• EST/EDT -- Eastern standard/day light time
• GMT -- Greenwich mean time
• HST/HDT -- Alaska-Hawaii standard/day light time

• MST/MDT -- Mountain standard/day light time


• NST -- Newfoundland standard time
• PST/PDT -- Pacific standard/day light time
• YST/YDT -- Yukon standard/day light time
Ex:
SQL> select to_char(new_time(sysdate,'gmt','yst'),'dd mon yyyy hh:mi:ss am') from dual;
SQL> select to_char(new_time(sysdate,'gmt','est'),'dd mon yyyy hh:mi:ss am') from dual;

t) COALESCE

This will give the first non-null date.

Syntax: coalesce (date1, date2, date3 … daten)

Ex:

SQL> select coalesce('12-jan-90','13-jan-99'),


coalesce(null,'12-jan-90','23-mar-98',null) from dual;

CONVERSION FUNCTIONS:-
Bin_to_num

Chartorowid

Rowidtochar

To_number

To_char

To_date

a) BIN_TO_NUM

This will convert the binary value to its numerical equivalent.

31 | Page
UNIT-II (DBMS)
Syntax: bin_to_num( binary_bits)

Ex:
SQL> select bin_to_num(1,1,0) from dual;

b) CHARTOROWID

This will convert a character string to act like an internal oracle row identifier or rowid.

c) ROWIDTOCHAR
This will convert an internal oracle row identifier or rowid to character string.

d) TO_NUMBER

This will convert a char or varchar to number.


SQL> select to_number('26') from dual;

e) TO_CHAR
This will convert a number or date to character string.
SQL> select to_char(sysdate,'d') from dual;

f) TO_DATE
This will convert a number, char or varchar to a date.
SQL> select to_date('26-dec-06','dd-mon-yy') from dual;

GROUP FUNCTIONS:

• Sum
• Avg
• Max
• Min
• Count
Group functions will be applied on all the rows but produces single output. a) SUM

This will give the sum of the values of the specified column. Syntax: sum (column)

Ex: SQL> select sum(sal) from emp;

b) AVG

This will give the average of the values of the specified column. Syntax: avg (column)

Ex:SQL> select avg(sal) from emp;

c) MAX

32 | Page
UNIT-II (DBMS)
This will give the maximum of the values of the specified column. Syntax: max (column)

Ex:SQL> select max(sal) from emp;

d) MIN

This will give the minimum of the values of the specified column. Syntax: min (column)

Ex: SQL> select min(sal) from emp;

e) COUNT

This will give the count of the values of the specified column.

Syntax: count (column)

Ex: SQL> select count(sal),count(*) from emp;

JOINS

The purpose of a join is to combine the data across tables.

A join is actually performed by the where clause which combines the specified rows of
tables.

If a join involves in more than two tables then oracle joins first two tables based on the
joins condition and then compares the result with the next table and so on.

TYPES

Equi join
Non-equi join
Self join
Cross join
Outer join
Left outer
Right outer
Full outer
Inner join

Assume that we have the following tables.

1.SQL> select * from dept;

2.SQL> select * from emp;

EQUI JOIN

33 | Page
UNIT-II (DBMS)
A join which contains an ‘=’ operator in the joins condition.

Ex: SQL> select empno,ename,job,dname,loc from emp e,dept d where e.deptno=d.deptno;


USING CLAUSE

SQL> select empno,ename,job ,dname,loc from emp e join dept d using(deptno); ON

CLAUSE

SQL> select empno,ename,job,dname,loc from emp e join dept d on(e.deptno=d.deptno);

NON-EQUI JOIN

A join which contains an operator other than ‘=’ in the joins condition. Ex:

SQL> select empno,ename,job,dname,loc from emp e,dept d where e.deptno > d.deptno;

SELF JOIN

Joining the table itself is called self join.

Ex:

SQL> select e1.empno,e2.ename,e1.job,e2.deptno from emp e1,emp e2 where

e1.empno=e2.mgr;

CROSS JOIN

This will gives the cross product.

Ex:

SQL> select empno,ename,job,dname,loc from emp cross join dept;

OUTER JOIN

Outer join gives the non-matching records along with matching records.

LEFT OUTER JOIN

This will display the all matching records and the records which are in left hand side table
those that are not in right hand side table.

Ex:

34 | Page
UNIT-II (DBMS)
SQL> select empno,ename,job,dname,loc from emp e left outer join dept d
on(e.deptno=d.deptno);

RIGHT OUTER JOIN

This will display the all matching records and the records which are in right hand side table
those that are not in left hand side table.

Ex:

SQL> select empno,ename,job,dname,loc from emp e right outer join dept d

on(e.deptno=d.deptno);

Or

SQL> select empno,ename,job,dname,loc from emp e,dept d where e.deptno(+) =


d.deptno;

FULL OUTER JOIN

This will display the all matching records and the non-matching records from both tables.

Ex:

SQL> select empno,ename,job,dname,loc from emp e full outer join dept d

on(e.deptno=d.deptno);

INNER JOIN
This will display all the records that have matched.
Ex: SQL> select empno,ename,job,dname,loc from emp inner join dept using(deptno);

35 | Page

You might also like