0% found this document useful (0 votes)
321 views

SQL Notes by Krishna Reddy

Uploaded by

JP
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
321 views

SQL Notes by Krishna Reddy

Uploaded by

JP
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 49

What is data actually?

Data:
 It is stored representation of OBJECTS and EVENTS that have meaning and importance in user’s environment.
 Data can be structure or unstructured.
o StructuredàEmpName, address.
o UnstructuredàEmpPhoto, AddrMap.
Representation of data:
KING 10 5000 15-02-08
JONES 10 4500 02-03-06
BLAKE 20 3500 15-06-05
SCOTT 20 2000 12-05-02
FORD 30 1100 13-04-00
MILLER 10 1200 14-07-99

What is Information Actually?


Information:
It is data that is processed form, such that it increases the knowledge of the person who uses the data.
Representation of Information:
Employees Information
Organization: Date: 21-Aug 2012
Durga Soft Place: Hyderabad
Name Department Salary DOJ
KING 10 5000 15-02-08
JONES 10 4500 02-03-06
BLAKE 20 3500 15-06-05
SCOTT 20 2000 12-05-02
FORD 30 1100 13-04-00
MILLER 10 1200 14-07-99
What is Metadata Actually?
 It is the data which describes the properties or characteristics of end users data and the Context of the data.
 Metadata properties can include information
Such as: Data name, Definitions, Length of size, Values allowed, Source of data
Ownership
 Metadata and data are always separate.
 Metadata enables the database designers and programmers to understand exactly in which form the data should
exist within the system.
Metadata for employees Information
Data Item Specification
Field Name Type Length Min Max
Empname Alpha numeric 30
Deptno Integer 2 10 90
Empsal Decimal 7 1500 50000
Hiredate Date

Database Management system


 Database management system is software that is used to create, maintain and provide controlled access to user databases.
 Database management systems should provide systematic method of
àCreating the Database.
àUpdating the Database.
àStoring the Database
àRetrieving of data from Database.
Expected features of DBMS software
 Enable end user and application programmers to share the data.
 Enable data shared among multiple applications.
 Should not propagate and store data in new files for every new application.
 Should provide facility for…..
o Controlling data access.
o Enforce data integrity.
o Manage concurrency control.
o Restoring the data in system failures.
Database Management system evolution
 First time introduced during 1960’s
 Relational model first defined by E.F codd (IBM) in 1970.
Objectives behind Evolution
 Reduce the maintenance cost of software.
 Manage complex data types.
 Provider easier and faster access to data even for novice user.
Different database Models
 Flat file DBMS
 Hierarchical DBMS
 Network DBMS
 Relational DBMS
 Object-Relational DBMS
Database models and their timelines
 Flat file 1960
 Hierarchical 1970
 Network 1980
 Relational 1990
 Object-oriented 2000

Database as per oracle


 As per oracle database is a collection of data in one more number of files.
 The database is a collection of logical structures and physical structures which are integrated and configured for the integrity of the system.

Logical Structures
 In design state the system is represented in the form of Entity relationship model.
 In the database state it is representation of the actual metadata of the database management system software which will be in the form of tablespaces , data dictionary
objects etc.

Physical structures
 In this the system is represented in the form of tables, indexes etc.
 Database should have the ability to provide access to external tables for files outside the database, as if the rows in the files were rows in the table.
 Creating structures (Tables & Indexes)
 With in the oracle database, the basic structure is a table used to store data.

Let us understand the Oracle style for data storage


 All the logical structures in the database must be stored with in the database only.
 Oracle maintains a data dictionary , which records metadata about all the database objects.
 The database objects which need physical storages space on the computer system, are allocated space within a table space.

Table space:
 It is logical storage unit within oracle database and is not visible in the file system of the machine on which the database resides.

 The table space builds the bridge between the oracle database and the file system in which the table’s or index data is stored.
 A data file can be part of one and only one table space.

 There are three types of table spaces in oracle.

o Permanent table space.


o Undo table spaces.
o Temporary tables spaces.

 Each table or index stored in an oracle database belongs to a table space.


 In 10g a big file table space can be created , which can grow to the size of Tera bytes of space on disk.

System and data modeling importance

Data models:
 Data models helps in exploring ideas and improve the understanding the database design for both developers
and system designers.
Purpose of data models

 Communicate
 Describe
 Investigate
 Analyze
 Categories

Relation database properties

 Should be accessed and modified by executing


 need to identified how the data is arranged physically. structured Query language(SQL) statement only.
 Should use set of operator .
 Need not specify the access route to the tables and data.

Page5 to page 20

To Create Table:
Syntax:.

Sql>Create Table <Table Name>


(<Column1><Type>,<Column1><Type>,…..);
Note:
The character ‘;’ is the terminator for SQL statement.

Example:

Sql>Create Table Emp_det


(
Empno Number(4), Ename Varchar2(15),
Job Varchar(15), Mgr Number(4),
Hiredate Timestamp, Sal Number(6,2),
Comm Number(6,2), Ephoto BLOB,
Deptno Number(2)
);
…………………………………………
Sql>Create Table Student_Det
(
StudNo Number(4), Fname Varchar2(15),
Lname Varchar2(15), DOB Date,
DOJ Date, Fees Number(6,2),
Gender Char
);
…………………………………………
Inserting Data in Table:

A row is inserted into a table by using INSERT command.


Rows can insert into a Table
Views Base Table.
A partition of a Table.
A Sub Partition of a Composite Partition Table.
An Object Table.
An Object View’s Base Table.

Inserting of data into a table can be executed in two ways.

Conventional INSERT.
Direct-Path INSERT.

In conventional Insert statement, Oracle reuses free space in the table into which the data in being insert and maintains Referential Integrity Constraints.
In Direct-Path Insert, Oracle append the insert data after existing data in the Table, the free space is not reused.
Syntax:

Sql> INSERT INTO <table name> [list of columns] VALUES (list of values);

EX:
Sql> INSERT Into Student_Det Values
(
1001,
‘THOMAS’,
‘SIEBEL’,
’30-DEC-81’
’02-JAN-91’,
30000,
‘M’
);

In this case the values should be provided to all the columns that exist inside the table.

The order of values declared in the Values clause should follow the original order of the columns in the table.

The Character Date type data should be declared in single Quotes. ‘ ‘

Number Data type data can be declared normally. Like (122333 )

Inserting Data into Required Columns:

Sql>Insert Into Student_Det( StudNo, Fname, Lname , DOJ )


Values ( 1002, ‘JAN’, ‘SMITH’, ’12-JAN-09’ );

In this case the Order of columns declared in insert need not be the same as that of the original table order.
The data values in the values caluse should match with that of INSERT list of columns.

The columns not supplied with data are filled with NULL values, Until the NOT NULL constraint is declared.

Inserting NULL values into Table:

Null representation is not available.


Null Value is
Unknown value
Undefined value
Not equal to 0
Blank space represented with ‘NULL’ keyword.
Not allowed arithmetic, relational operation on Null, if performed it return Null only.
Ex: null+10=null
20+null=null
RDBMS must support NULL Values.
NULL values can be inserted in two ways.
ImplicitOmit the columns from list oracle supplies NULL values.
ExplicitSpecify the NULL keyword.
Sql>Insert Into Student_Det
(
StudNo, Fname, Lname, DOB, DOJ, Fees, Gender )
Values ( 1003, ‘RAMA’, NULL, ’12-JAN-81’, NULL, 30000,‘M’
);

Inserting special Values into Table:

‘SYSDATE’ FUNCTION
SYSDATE is Pseudo-column.
This function return the current date& time.

USER FUNCTION:

This function returns the user name of the user who has logged in.

Example:

>CREATE TABLE Student


(
Stuid Number(4),
Name Clob,
DOB Date,
DOJ Date,
Fees Number(8,2),
Gender char
);

Example:

Sql>INSERT INTO student VALUES (1001, user,'01-JAN-


85', sysdate, 2000,'M');

Substitution Variables:

These variables are used to stored values temporarily


The values can be stored temporarily through
Single Ampersand (&)
Double Ampersand (&&)
DEFINE and ACCEPT Commands
The Single Ampersand substitution variable applies for each instance when the SQL statement is create or execute.
The Double Ampersand substitution variable applies for all instances until that SQL statement is existing.

USING SINGLE AMPERSAND SUBSTITUTION VARIABLE:

Sql> INSERT INTO dept VALUES (&Dno,’&Dname’,’&Loc’);

Sql> INSERT INTO EMP (Empno, Ename, Hiredate, Deptno)


VALUES(&Eno,'&Ename','&Hiredate',&dno);

Note: To run command is used for executing a previous command…


>run
or
>/

USING DOUBLE AMPERSAND SUBSTITUTION VARIABLE:

Sql>INSERT INTO student


VALUES (&Sid,’&Name’,'&Dob', &Doj, &&fee,’&Gender’);

DEFINING CUSTOMIED PROMPTS:

Sql>ACCEPT Deptno prompt 'Please Enter the deptnumber:'


Sql>ACCEPT Dname prompt 'Please Enter the Deptname:'

Sql>ACCEPT Location prompt 'Please Enter the Location:'

Sql> INSERT INTO dept VALUES(&Deptno,&Dname,&Location);

CREATING AN .LST FILE:

The List file is used to save all information which performed in SQL *Plus .

1)In SQL * Plus


Navigation:
FileSpoolSpool File
2) Give the file name
3) Performed all tasks.
4) Now Spool Off.

CREATING AN SQL SCRIPT FILE:

The SAVE Command is used to store the current contents of the SQL Buffer.
Steps:
1)At SQL prompt type the full name of the path where the file has to be created.
2)Give the name of the file with .sql extension.
3)If the has to be replaced with the same existing name then use
REPLACE ALL clause.

Example:
Sql>SAVE E:\nitdir\ins
Sql> SAVE E:\nitdir\ins REPLACE
To Get Script:

Get used to display the script file .

Sql>Get E:\nitdir\ins
To Run Script:
Run is used to display the script and run the file.

Sql>RUN E:\nitdir\ins To simple the script file.

Sql>@ E:\nitdir\ins

To Open the Script file in editor.

Sql>ed E:\nitdir\ins

Data Retrieval Languages(DQL/DRL):

QUERY: It is an operation that retrieves data from one or more table or


view.
SELECT Statement:

Select used to retrieve data from one or more than table ,view, object tables.
It is for read only purpose.
The select is the most frequently used command as access to information is needed all the time.

PREREQUISTIES:

The user must have the SELECT privileges on the specified object.

CAPABILITES OF SQL SELECT STATEMENT:

The different types SELECT criteria.


SELECT:
It chooses the rows in a table that are expected to return by a query.

PROJECTION:
It chooses the columns in a table that are expected to return by a query.
JOIN :
It chooses the data in from one or more numbers of tables.

Data Retrieving Language:

Syntax:

Sql>SELECT *|{[DISTINCT/UNIQUE] column | expression


[Alias],…..} FROM table.

SELECT identifies what columns, specifies a list of


column(one/more)

FROM identifies which table


DISTINCE Suppress Duplicates.
* Select all Columns
Columns/ Expression Select the Named Columns or the expression.
Alias Gives select columns different headings

WRITING SQL STATEMENTS TO SELECT DATA FROM TABLES.

The sample table.

1)DEPT
Column Name Data Type
------------------------------- ------ ------
DEPTNO NUMBER(2)
DNAME VARCHAR2(14)
LOC VARCHAR2(13)

2)EMP

Column Name Data Type


1------------------------------- ------- ------
EMPNO NUMBER(4)
ENAME VARCHAR2(10)
JOB VARCHAR2(9)
MGR NUMBER(4)
HIREDATE DATE
SAL NUMBER(7,2)
COMM NUMBER(7,2)
DEPTNO NUMBER(2)

3)SALGRADE

Column Name Data Type


------------------------------- -------- -------
GRADE NUMBER
LOSAL NUMBER
HISAL NUMBER

Dept:

SQL> Select *From Dept;

DEPTNO DNAME LOC


------- ---------- ---------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

SQL> SELECT * FROM MY_EMP;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


----- --------- --------- ------ --------- --------- --------- ------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 09-DEC-82 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 12-JAN-83 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10

14 rows selected.

SQL> Select *From Salgrade;

GRADE LOSAL HISAL


--------- --------- ---------
1 700 1200
2 1201 1400
3 1401 2000
4 2001 3000
5 3001 9999

Retrieving Data from All Columns:


Sql>SELECT *FROM Emp;

Sql>SELECT *FROM Dept;

Sql>SELECT *FROM Salgrade;

In this the ‘*’ is a projection operator.


It project data from all the columns existing in the table with all records.
The data is displayed in a table format.

Retrieving Data from Specific Columns:

Sql> SELECT empno, ename, job, sal FROM Emp;


Sql>SELECT loc, dname, deptno FROM Dept;
Sql> SELECT Hisal,Losal,Grade FROM Salgrade;
The columns names need not be in the same order as table.
The columns should be separated using comma.
The column names can be separated into different lines within the SQL Buffer.
The casing of column names is not important.

Column Heading Default:


The default justification of the data after it is retrieved from the table is…

LEFT Date and Character


RIGHT Number Data
The default Columns Heading display in UPPER case.

Applying Arithmetic Operations in Select Statements:

Arithmetic Expressions can be implemented through SELECT statement.


Arithmetic Expressions can be implemented to
Modify the way the data is displayed.
Perform calculations.

An Arithmetic Expression can contain:

Simple columns names


Constant numeric values
Arithmetic operators

ARITHMETIC OPERATORS:

The Arithmetic operations can be used to create expressions on NUMBER and DATE data.
The Arithmetic operators supported are….
+ Addition
- Subtraction
* Multiplication
/  division.

The Arithmetic operators can be used in any clause of a SQL statement. except the FROM clause.
SQL * Plus ignores Blank Spaces before and after the Arithmetic operator.
Sql> Select empno,ename,sal,sal+500 FROM Emp;
Sql> Select empno,ename,sal,sal-1000 FROM Emp;

Operator Precedence:

Multiplication and Division take priority over addition and subtractions(*/+-)


Operators of the same priority are evaluated from left to right.
To prioritize evaluation and to increase clarity parenthesis can be implemented.

Sql> Select empno,ename,sal,12*sal+100 from Emp;


Sql>Select empno,ename,sal,(12*sal)+100 from Emp;
Sql>Select empno,ename,sal,12*(sal+500) from Emp;

Handling Null Values:


NULL:
Unknown value
Undefined value
Not equal to 0 or blank space.
If a row lacks the data for a particular column, than that value is said to be NULL or to contain NULL.
It represented with NULL keyword
No operations allowed on Null,( If performed any arithmetic operations it return null only).
RDBMS must support NULL Values.
Sql>Select ename,job,sal,comm from emp;
Sql> Select ename,job,sal,comm,12*sal+comm from emp;

General Function:

This functions work with any data type and pertain to using null value.

NVL Function:

The NVL function is used to convert a NULL value to an actual value.

Syntax:
NVL(Expr1,Expr2)
Expr1: is the source value or expression that may contain NULL.
Expr2: is the target value for converting NULL.

NVL Conversions for Various Data Types:

NVL(Number_column, 0)
NVL(date_column, ’01-JAN-09’)
NVL(Character_column, ‘Unavailable’)
Note : If Expr1 is Character data then Expr2 may any Data type.
Sql>Select NVL(100,200) from dual;
Sql> Select NVL(null,200) from dual;
Sql> Select ename,sal,comm,sal+NVL(comm,0) from emp;
Sql> Select ename,sal,comm,(sal*12)+NVL(comm,0) from emp;
Sql> Select ename,sal,comm,(sal+500)+NVL(comm,0) from emp;

NVL2 Function:
Syntax:
NVL2(expr1,expr2,expr3)
If expr1 is not null,NVL2 returns expr2.if expr1 is null, NVL2 returns expr3.
Expr1 may any data type.
The data type of the return value is always the same as the data type of expr2 , unless Expr2 is character data .

Example:-
1) select nvl2(comm,0,1000) from emp;
2) select sal,comm, sal+nvl2(comm,100,1000) from emp;
>select ename,sal,comm, nvl2(comm,'sal+comm','sal') income
from emp where deptno in(10,30);

NULLIF Function:

Syntax:
NULLIF(expr1,expr2)
Compares two expressions and returns null if they are equal,or the first if there are not equal.

Example:
>SELECT NULLIF(100,200) from dual;

>SELECT ENAME,LENGTH(ENAME) "expr1",


JOB,LENGTH(JOB) "expr2",
NULLIF(LENGTH(ENAME),LENGTH(JOB)) result
from emp;
Note:
The data type of the expr1 is same as the data type of expr2.
The NULLIF function is logically equivalent to CASE expression.

COALESCE:

It return first non-null expression in the expression list.

Sql> SELECT coalesce(100,600,200) FROM dual;


Sql> SELECT coalesce(null,600,200) FROM dual;
Sql>SELECT Ename,Deptno,COALESCE(COMM,SAL,10) COMM FROM EMP

OCP Questions :

1)The EMPLOYEE tables has these columns:


LAST_NAME VARCHAR2(35)
SALARY NUMBER(8,2)
COMMISSION_PCT NUMBER(5,2)

You want to display the name and annual salary multiplied by the commission_pct for all employees. For records that have a NULL commission_pct, a zero must be displayed against the calculated column.

Which SQL statement displays the desired results?

A. SELECT last_name, (salary * 12) * commission_pct FROM EMPLOYEES;


B. SELECT last_name, (salary * 12) * IFNULL(commission_pct, 0) FROM EMPLOYEES;
C. SELECT last_name, (salary * 12) * NVL2(commission_pct, 0) FROM EMPLOYEES;
D. SELECT last_name, (salary * 12) * NVL(commission_pct, 0) FROM EMPLOYEES;

Defining a Column Alias:


An Alias is an alternate name given for any Oracle Object.
Aliases in Oracle are of two types.

*Column Alias *Table Alias


Column alias rename a Column Heading.
Alias Headings appear in uppercase By default.
Specify the alias after the column in the SELECT list using a space as a separator.
AS keyword between the column name and alias is optional.
The Alias contains spaces or special characters (such as # or $),
or is case sensitive, enclose the alias in double quotation marks (" ").
An alias cannot be used, any where in the SELECT list for operational purpose.
An alias effectively renames the SELECT list item for the duration of the Query.

Sql> SELECT Empno EmpNumber,


Ename EmpName,
Sal “EmpSalary”
Job Designation FROM Emp;

Sql> SELECT Grade AS “SalGrade”,


Hisal “High Salary Range”,
Losal “Lower Salary Range” From Salgrade;

Sql> Select empno “EmpNumber”,


Sal “Basic”,Sal*0.25 HRA,
Sal*0.20 DA,Sal*0.15 “Pf”,
Sal+Sal*0.25+Sal*0.20-Sal*0.15 “Gross”
FROM emp;
Concatenation Operator:
The Concatenates operator concatenate columns or character strings or expressions or constant to other values or columns.
Is represented by two vertical bars (||).
The resultant column that is a character .

Sql>SELECT empno||ename FROM Emp;

Sql> Select 'The Basic Salary of '||Ename|| 'is Rs '||Sal Employee From
Emp;

Sql>Select Empno||Ename||Ename||' ,Designation is '||job


"Employees Information " From Emp;

LITERALS IN ORACLE:

A Literal and Constant valueare synonyms to one another and refer to a fixed data value.
The types of Literals recognized by Oracle are
Text Literals
Number Literals
Interval Literals
Text Literals:
It specifies a text or character literal.
It is used to specify values whenever ‘text’ or CHAR appear in

*Expression *Condition *SQL Function * SQL Statements.

It should be enclosed in single quotes.


A text literal can have a maximum length of 4000 Bytes.

Example:
‘Employee Information’
'Manager's Specification'

Using Literal Character Strings:

A literal value is a character, a number, or a date that is included in the SELECT list.
A literal value not a column name or a column alias.
A literal is printed for each row returned, that is retrieved by the SELECT statement.
Literal strings of free-format text can be included in the query.
A free-format text treated the same as a column in the SELECT list.
Date and character literal must be enclosed within the single quotation marks ‘ ‘.
Literal increase the readability of the output.

Sql>Select Ename ||’:’|| ‘Month Salary=’|| Sal As Salaries From Emp;

Sql>Select ‘The Designation of ‘|| Ename ||’ is ’|| job As Designation From Emp;

Sql> Select 'The employee name is: '||Ename||' and '||'Designation is :'||job
from Emp;

Sql> Select 'The Annual Salary of '||Ename||' is '||Sal*12 As


Annual_Salary From Emp;

Sql> Select Dname||'Department is Located at '||Loc From Dept ;

Sql> Select Ename||' Joined the Organization on '|| Hiredate From Emp;

Sql> Select Ename||' Works in Department Number '||Deptno||


' as ' ||job From Emp;

Sql> Select ‘The Employee Name is: ‘||Ename||’, Designation is ‘||Job


FROM Emp;

Sql>SELECT 'The Gross salary of '||Ename||' is '||(Sal+Sal*.25+Sal*.20-Sal*.15) FROM Emp;

Duplicate Rows:

Unless we indicate otherwise, iSQL*Plus displays the results of a query without eliminating duplicate rows.
To eliminate duplicate rows in the result, the DISTINCT keyword used.
We can specify multiple columns after the DISTINCT qualifier.
The DISTINCT qualifier affects all the selected columns, and the result is every distinct combination of the columns.

Sql>Select DISTINCT Job From Emp;

Sql> Select DISTINCT Job,Deptno From Emp;

Sql>Select DISTINCT Deptno,Job From Emp;

Filter Of Record:
The number of rows returned by a query can be limited using the WHER clause.
The method of restriction is the basis of the WHERE clause in SQL.
A WHRE Clause contains a condition that must be met and should directly follow the From Clause.

Sql>SELECT *|{[DISTINCT] column|expression [alias],...}


FROM table
[WHERE condition(s)];

The WHERE clause can compares


Values in Columns
Literal Values
Arithmetic Expressions
Function

The components of WHER clause are


Column Name
Comparison Operator
Column Name, constant or list of values.

The Character strings and dates should be enclosed in single quotation marks.
Character values are case sensate and Date values are format sensitive
(DD-MON-YY)
The Comparison operator are used in conditions that compare one expression to another.

Relational Or Comparison operators:

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


Example:

Sql>SELECT empno, ename, job, sal from emp;

Sql>SELECT loc, dname, deptno from dept;

Sql>SELECT * from emp;

Sql>SELECT * from students;

Sql>SELECT * from emp WHERE deptno=10;

Logical Operators:
A logical condition combines the result of two component conditions to produce a single result.
Three logical operators are available in Oracle.

AND OR NOT

AND Operator:

The AND operator allows creating an SQL statement based on two or more conditions being met.
It Returns FALSE if either is FALSE, else returns unknown.

Truth Table:

AND
TRUE TRUE TRUE
FALSE TRUE FALSE
TRUE FALSE FALSE
FALSE FALSE FALSE

Example:

Sql> Select Ename,Sal,Job Emp Where (Sal>=1500 AND Sal<=5000)


AND Job=’MANAGER’;

OR Operator:

It return TRUE if either component conditions is TRUE.


It returns FALSE if both are FALSE, else return unknown.

Truth Table:

OR
TRUE TRUE TRUE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE

Sql>Select Empno,Ename,Sal,Deptno From Emp


Where Sal>=2000 OR Deptno=20;

Sql>Select Empno,Ename,Job,Hiredate From Emp


Where Job=’MANAGER’ OR Deptno=30;

Sql>Select Empno,Ename,Job,Deptno From Emp


Where (Deptno=10 OR Deptno=20) OR JOB=’MANAGER’;

Sql>Select Ename,Job From Emp Where (Job='CLERK' or Job='SALESMAN'


or ob='ANALYST');
Sql> Select Ename,Hiredate,Deptno From Emp
Where Job=’MANAGER’ OR Deptno=30;

Sql>Select Ename,Sal,Job From Emp


Where (Sal<=2500 OR Sal>=5000) OR Job=’MANAGER’;

NOT Operator:

It returns TRUE if the following condition is FALSE.


It returns FALSE if the following condition is TRUE.
If the condition is Unknown, it returns Unknown.

Combination of AND OR Operator:

Sql>Select Ename,Sal From Emp


Where (Job='CLERK' or Job='PRESIDENT' or Job='ANALYST')
And Sal>3000;

Sql> Select Empno,Ename,Job,Sal From Emp


Where (Sal>1500 OR Job='MANAGER') AND Deptno=10;
Sql>Select Empno,Ename,Job,Sal From Emp
Where (Deptno=20 OR Job='MANAGER') AND Sal>=3000;

Not Operator Example:

Sql>Select Empno,Ename,Job,Sal From Emp Where NOT


Ename='SMITH';

Sql>Select Empno,Ename,Job,Sal From Emp Where NOT


Sal>=5000;

Sql>Select Empno,Ename,Job,Sal From Emp Where NOT


Job='CLERK';

Sql>Select Empno,Ename,Job,Sal From Emp Where NOT


Sal<=5000;

Sql>Select Empno,Ename,Job,Hiredate From Emp


Where NOT Hiredate='17-DEC-80';

Sql>Select Empno,Ename,Job,Hiredate
From Emp
Where NOT JOb='CLERK' AND Deptno=20;

Some Things To Note:

Sql>Select Ename,Sal,Job From Emp Where Job>'CLERK';

Sql>Select Ename,Sal,Job From Emp Where Job<'CLERK';

Sql>Select Ename,Deptno,Hiredate From Emp Where Hiredate>'20-


DEC-81';

Sql>Select Ename,Deptno,Hiredate From Emp Where Hiredate<'20-


DEC-81';

Sql>Select Ename,Job,Hiredate From Emp Where Job^='CLERK';

Sql>Select Ename,Job,Hiredate From Emp Where NOT Job^=


'CLERK';

Sql>Select Ename,Job,Hiredate From Emp Where NOT


Job='CLERK';

Sql>Select Ename,Job,Hiredate From Emp


Where NOT Hiredate='17-DEC-1980';

Sql>Select Ename,Job,Hiredate From Emp


Where NOT Hiredate>'18-DEC-1981';

Rules of Precedence:

The default Precedence order is


All comparison operators
NOT logical condition
AND logical condition
OR logical condition
Note:
Override rules of precedence by using parentheses.

Example:

Sql> SELECT Ename,Job, SalFROM Emp


WHERE Job = 'CLERK' OR Job = 'MANAGER' AND Sal> 1500;

Sql> SELECT Ename,Job, Sal FROM Emp


WHERE (Job = 'CLERK' OR Job = 'MANAGER') AND Sal> 1500;

SQL *Plus Operator:

BETWEEN …. AND…..; NOT BEWEEN ….AND….


BETWEEN is used to o display rows based on a range of values.
The declared range is inclusive.
The lower limit should be declared first.

Sql>Select Empno,Ename,comm. From Emp Where Comm


Between 500 AND 1000;

Sql>Select Ename,Sal,Job From Where Sal NOT Between 1000 AND 1500;

Sql>Select Ename,Sal,Job From Emp Where Job Between ‘MANAGER’


AND ‘SALESMAN’;

Sql>Select Ename,Sal,Job From Emp Where Job NOT Between


‘MANAGER’ AND ‘SALESMAN’;

Sql>Select Ename,Sal,Job,Hiredate From Emp Where Hiredate


Between ’17-FEB-1981’ AND ’20-JUN-1983’;

Sql>Select Ename,Sal,Job,Hiredate From Emp Where Hiredate


NOT Between ’17-FEB-1981’ AND ’20-JUN-1983’;

IN Operator: NOT IN Operator:

The Operator is used to test for values in a specified list.


The Operator can be used upon any datatype.

Sql>Select Ename,Sal,Job From Emp Where Ename


IN(‘FORD’,’SMITH’);

Sql>Select Empno,Job,Sal From Emp Where Ename NOT


IN(‘FORD’,’SMITH’);

Sql>Select Ename,Sal,Deptno From Emp Where Deptno IN(20,30);

Sql>Select Ename,Sal,Deptno From Emp Where Deptno NOT IN(20,30);

Sql>Select Ename,Sal,Deptno From Emp Where


Hiredate IN(’20-FEB-1981’,’09-JUN-1981’);
Sql>Select Ename,Sal,Deptno From Emp Where
Hiredate NOT IN(’20-FEB-1981’,’09-JUN-1981’);

LIKE Operator : NOT LIKE Operator:

Use the LIKE condition to perform wildcard .


The LIKE Operator searches of valid search string values.
Search conditions can contain either literal characters or numbers.
The available wild cards are
%  It is represent any sequence of Zero or more character.
_ Represent any single character, only at that position only.

The Wild Card symbols can be used in any combination with literal character.
For finding exact match for ‘%’ and ‘-‘ the ESCAPE option has to be used, which is ‘/’ symbol with ESCAPE option.

Sql>SELECT Empno,Ename From Emp Where Ename LIKE ‘M%’;

Sql> SELECT Empno,Ename From Emp WHERE Ename NOT


LIKE‘M%’;

Sql>SELECT Empno,Ename From Emp WHERE Ename LIKE ‘_O%’;

Sql> SELECT Empno,Ename From Emp WHERE Ename


NOT LIKE ‘_O%’;

Sql> SELECT Empno,Ename From Emp WHERE Ename LIKE ‘SM%’;

Sql> SELECT Empno,Ename,Job From Emp WHERE Job LIKE ‘_____’;

Sql> SELECT Ename,Hiredate From Emp WHERE Hiredate


LIKE ‘%-FEB-1981’;

Sql> SELECT Ename,Hiredate From Emp WHERE Hiredate


LIKE ‘%JAN%’;

Sql>Select *From Dept Where Dname LIKE '__\_%' ESCAPE '\';


(update dept set dname='SO_FT_WARE' where deptno=50;)

IS NULL Operator : IS NOT NULL Operator:

The Operator tests for NULL values.


It is the only operator that can be used to test for NULL’s.
NULL value means the value is unav ailable, unassigned, unknown, or inapplicable.

Sql>SELECT Ename,Deptno,Comm From Emp WHERE Comm IS NULL;

Sql>SELECT Ename,Deptno,Mgr,Job From Emp WHERE Mgr IS NULL;

Sql> SELECT Ename,Deptno,Comm From Emp WHERE Comm>=0;

Sql>SELECT Ename,Deptno,Comm From Emp


WHERE Comm IS NOT NULL;
Sql>SELECT Ename,Deptno,Comm From Emp WHERE Mgr
IS NOT NULL;

ORDER BY Clause:
The Order of rows returned in a query result is undefined.
The ORDER BY clause can be used to sort the rows.
The ORDER BY clause must be the last clause of the SQL statement.
An expression, or an alias, or column position as the sort condition.
Default ordering of Data is Ascending.

**Number 1-999
**Dates Earlist-Latest
**String A-Z;NULLSLast.
Syntax:
SELECT expr FROM table [WHERE condition(s) ]
[ORDER BY {column, expr} [ASC|DESC]];

The default order upon column is Ascending, to change the default ordering DESC should be used after the column name.
Sorting can be implemented on column aliases ,and can also be implemented upon multiple columns.

Sql>Select Ename,Job,Sal,Deptno From Emp ORDER BY Sal;

Sql>Select Ename,Job,Sal,Deptno From Emp ORDER BY Sal DESC;

Sql>Select Ename,Job,Sal,Deptno From Emp Where Job=’CLERK’ ORDER BY Sal;

Sql>Select Ename,Job,Sal,Deptno From Emp Where Sal>=2000 ORDER


BY Deptno,Ename DESC;

Sql>Select Ename,Job,Sal,Sal*12 Annsal From Emp ORDER BY AnnSal;

Sql>Select Ename,Job,Sal,Deptno From Emp ORDER BY Deptno,Job,Sal ;

Sql>Select Ename,Job,Sal,Deptno From Emp ORDER BY 2 DESC;

Sql>Select * From Emp ORDER BY 5 DESC;

The single row functions can appear in:

**SELECT List
**WHERE List
**Start With Clause
**CONNECT BY Clause

The types of single row functions are

**CHARACTER **NUMBER **DATE **CONVERSION

Multiple Row Functions:

These function manipulate group of rows to give one result per group of rows.

Single Rows Function:


They are used to manipulate data items.
They accept one or more arguments and return one value for each row returned by the query.
An argument can be :
User-supplied constant
Variable value
Column name
Expression
Syntax:

Func_Name(Column/Expr,[Arg1,Arg2,……])

Features of single-row functions include:

Acting on each row returned in the query.


Returning one result per row.
Returning a data value of a different type than that referenced.
Expecting one or more arguments.
Can be used in SELECT, WHERE, and ORDER BY clauses.
Can be nested.

Specification Behavior of Function:

Character functions: Accept character input and can return both character and
number values.
Number functions:Accept numeric input and return numeric values.
Date functions:Operate on values of the DATE data type (All date
functions return a value of DATE data type except the MONTHS_BETWEEN function, which returns a number.)

Conversion functions: Convert a value from one data type to another.


General functions:
NVL
NVL2
NULLIF
COALSECE
CASE
DECODE

Character Functions:

They return the data type VARCHAR2,limited to a length of 4000 Bytes.


If the return value length exceeds, then the return value is truncated, without an error.
Functions can be divided into
Case-manipulation functions.
Character-manipulation functions.

Character Function Purpose:

LOWER(column|expression)

It converts alpha character values to lowercase .


The return value has the same data type as argument char type(CHAR or VARCHAR2)

Syntax: LOWER(column | xpression)


Sql>Select LOWER(‘DURGASOFT ’) From Dual;

Sql>Select Ename,Job,LOWER(‘MY DATA’) From Emp;

Sql>Select Ename,LOWER(Ename) From Emp Where Deptno=10;

Sql>Select 'The '||Ename || '''s Designation is '|| Job From Emp


Where LOWER(Job)='manager'

Upper Function:

It Converts the Alpha character values to Upper Case.


The return value has the same data type as the argument char.

Syntax:
UPPER(Column | Expression)

Sql>Select Upper(DURGASOFT ') From Dual;

Sql>Select Ename,Job, Upper (‘My Data’) From Emp;

Sql>Select Ename,Job, Upper (Ename), Upper (Job) From Emp Where Deptno=20;

Sql> Select Ename,Job From Emp Where Job=Upper(‘Manager’);

Sql> Select Upper('E.F Codd') "Capitalised" From Dual;

Sql>Select 'The '||Ename || '''s Designation is '|| Lower(Job) From Emp


Where Job=Upper('manager') Order by Sal;

Sql>Select Upper('The '||Ename|| ' Basic Salary is '||Sal) "Emp


Salaries" ,Job From Emp
Where Job In(Upper('Manager'),Upper('clerk')) Order by Sal Desc;

INITCAP Function:

It returns a string with the first letter of each word in upper case, keeping all othered
letters in Lower case.

Sql>Select initcap(Ename) From emp;

Sql>Select Initcap(DURGASOFT ') From Dual;

Sql>Select ‘The Job Title for’||Inticap(Ename)||’ is’|| Lower(Job) Details


From Emp;

Sql>Select Ename,Upper(Ename),Lower(Ename),Initcap(Ename) From Emp;

Sql>Select Empno,Initcap(Ename),Deptno From Emp


Where Ename=Upper(‘ford’);
CONCAT Function:
It Concatenates the first characters value to the second character value. Only two parameters accept.
It return the character data type.

Syntax: CONCAT (Column1/Exp1, Column2/Exp2)

Sql>Select Concat(‘Oracle’,’DURGASOFT’) From Emp;

Sql>Select Ename,Job,Concat(Ename,Job) From Emp Where Deptno=20;

Sql> Select Concat(Concat(Ename,Job),Sal) From Emp;

Sql> Select Concat('The Employee Name is',Initcap(Ename)) As


"Employee Names " From Emp Where Deptno in(10,20);
Sql>Select Concat(Concat(Initcap(Ename),’is a’),Job) Job From Emp
Where Deptnoin(10,20);

Sql>Select Concat(‘&Fname’,’&Sname’) “Full Name” From Dual;

SUB STRING Function:

Returns specified characters from character value, string from a specified position ‘m’ to ‘n’ characters long.
To extract the portion of the string it is mainly used.

Points to Remember…
If m is 0, it is treated as 1.
If m is positive, Oracle counts from the beginning of char to find the first character.
If n is Omitted, Oracle returns all characters to the end of char.
If n is less than 1 or 0, A null is returned.
Floating points numbers passed as arguments to substr are automatically converted to Integers.

Syntax:SUBSTR(Col/Exp,m,[n])

Sql> Select Substr(‘SIVA RAMA KRISHNA’,1,4) From Dual;

Sql>Select Substr('SIVA RAMA KRISHNA',6,4) From Dual;

Sql>Select Substr('SIVA RAMA KRISHNA',11) From Dual;

Sql>Select Substr('SIVA RAMA KRISHNA',-7) From Dual;

Sql> Select Substr('SIVA RAMA KRISHNA',-12,4) From Dual;

Sql> Select Substr('SIVA RAMA KRISHNA',-12,4) From Dual;

Sql> Select Ename,Job From Emp Where


Substr(Job,6)=Upper('man');

Sql> Select Concat(Initcap(Ename),


Concat(' is a ',Concat(Initcap(Substr(Job,1,3)),' Eater.')))
From Emp Where Substr(Job,4,3)=Upper('Age');
Real Time Scenario:

LENGTH Function:

Returns the number of characters in a value.


If the char has data type CHAR, the length includes all trailing blanks.
If the char is NULL, if retrun NULL.

Syntax:

LENGTH(Column|Expression)

Sql>Select Length('E.F CODD') From Dual;

Sql>Select Length(Ename)||' Characters exists in '||Initcap(Ename)||' ''s Name.'


As "Names and Lengths " From Emp;

Sql>Select Initcap(Ename),Job From Where Length(Ename)=5;

Sal> Select Initcap(Ename),Job From Emp


Where Substr(Job,4,Length(Substr(Job,4,3)))='AGE';
Real Time Scenario:

INSTRING Function:

It returns the numeric position of a named character.

Syntax:INSTR(Column | Expression, ‘C’, [,m], [n] )

Searches for Column / Expression beginning with its ‘m’th character for the ‘n’ th occurrences of character ‘C’, and return the position of the character .
‘m’ can be positive or negative, if negative searches backward from the end of Column / Expression.
The value of ‘n’ should be positive.
The default value of both ‘m’ and ‘n’ are 1.
If search is unsuccessful, the return value is zero.

Sql>Select Instr('SIVA RAMA KRISHNA','A',1,1) From Dual;

Sql> Select Instr('SIVA RAMA KRISHNA','A',17,2) From Dual;

Sql>Select Instr('SIVA RAMA KRISHNA','MA',7,1) From Dual;

Sql>Select Instr('SIVA RAMA KRISHNA','A',-1,1) From Dual;

Sql>Select Instr(Job,'A',1,2) From Emp Where Job='MANAGER';

Sql>Select Instr(Job,'A',2) From Emp Where Job='MANAGER';

Sql> Select Instr(Job,'A') From Emp Where Job='MANAGER';

LPAD Function:
Pads the character value right-justified to a total width of n character positions.
The default padding character is space.

Syntax:
LPAD(Column | Expression, n, 'C')

Fill extra spaces with char ‘C’ up to ‘n’ position on left side.

Sql>Select Lpad('Page 1',20,'*') From Dual;

Sql> Select Lpad('Page 1',20) From Dual;

Sql> Select Lpad(Ename,20,'@') From Emp Where Deptno=10;

RPAD Function:

Pads the character value left-justified to a total width of n character positions.


The default padding character is space.

Syntax:RPAD(Column | Expression, n, 'C')

Sql>Sql>Select Rpad('Page 1',20,'*') From Dual;

Sql> Select Rpad('Page 1',20) From Dual;

Sql> Select Rpad(Ename,20,'@') From Emp Where Deptno=10


Sql>Select Ename,Lpad(Ename,10),Rpad(Ename,10,'-') From Emp
Where Deptno=10;

Sql> Select Ename,Lpad(Rpad(Ename,10,'-'),15,'-') From Emp

Real Time Scenario:

LTRIM Function:

It enables to trim heading character from a character string.


All the left most characters that appear in the set are removed.

Syntax:LTRIM(Char,Set)

Sql> Select Ltrim('xyxyORACLE 10g','xy') From Dual;

Sql> Select Ltrim('MM KRISHNA','M') From Dual;

RTRIM Function:

It enables to trim heading character from a character string.


All the right most characters that appear in the set are removed.

Syntax: RTRIM(Char,Set)

Sal> Select Rtrim('ORACLE 10gxyxy','xy') From Dual;


Sql>Select Rtrim('KRISHNA AAA','A') From Dual;

Sql> Select Rtrim(Job,'ER'),Job From Emp Where Ltrim(Job,'MAN')


Like 'GER';

TRIM Function:

Trims heading or trailing characters (or both) from a character string.


If trim_character or trim_source is a character literal, you must enclose it in single quotes.
If Leading is specified concentrates on leading characters.
If Trailing is specified concentrates on trailing characters.
If Both or none is specified concentrates both on leading and trailing.
Returns the varchar2 type.

Sql> Select Trim( 'S' From 'MITHSS') From Dual;

Sql> Select Trim( 'S' From 'SSMITH') From Dual;

Sql> Select Trim( 'S' From 'SSMITHSS') From Dual;

Sql>Select Trim(Leading 'S' From 'SSMITHSS') From Dual

Sql>Select Trim(Trailing 'S' From 'SSMITHSS') From Dual;

Sql>Select Trim(Both 'S' From 'SSMITHSS') From Dual;

REPLACE Function:
It return the every Occurrence of search string replace by the replacement string.
If the replacement string is omitted or null, all occurrences of serch string are removed.
If substitutes one string for another as well as to remove character strings.

Syntax:REPLACE(text,Search_string, [Replacement_string])

Sql>Select Replace('Led','L','R') From Dual;

Sql>Select Replace('Led','L','Ra') From Dual;

Sql>Select Replace('Led','Le','R') From Dual;

Sql> Select Ename,Replace(Job,'MAN','DAM') From Emp


Where Job='MANAGER';

Sql>Select Job,Replace(Job,'P') From Emp Where Job='PRESIDENT';

Sql> Select Job,Replace(Job,'MAN','EXECUTIVE') From Emp


Where Job='SALESMAN';

Real Time Scenario:


TRANSLATE Function:

Used to Translate Character by character in a String.

Syntax:TRANSLATE(char,From ,To)

It returns a char with all occurrences of each character in ‘From’ replaced by corresponding character in ‘To’.
Characters in char that are not in From are not replaced.
The argument From can contain more characters than To.
If the extra characters appear in Char, they are removed from the return value.

Sql>Select Translate(Job,'P',' ') From Emp Where Job='PRESIDENT';

Sql>Select Translate(Job,'MN','DM') From Emp Where Job='MANAGER';

Sql> Select Job,Translate(Job,'A','O') From Emp Where Job='SALESMAN';

Sql> Select Translate('Led','Le','R') From Dual;

Real Time Scenario:

CHR Function:

It returns a character having the binary equivalent to ‘n’.


It returns the equivalent for ‘n’ in database character set or national character set.

Syntax:CHR(n)

Sql>Select Chr(75)||Chr(82)||Chr(73)||Chr(83)||Chr(72)||Chr(78)||Chr(65)
Name From Dual;

ASCII Function:

It returns the decimal representation in the character database set of the first characters of the Char.

Syntax: ASCII(Char)

Sql> Select Ascii('A') From Dual;

Sql>Select Ename,Ascii(Ename) From Emp;

Sql> Select Ascii('&name') From Dual;

NUMBER Function:

These function accept number input and return numeric values.


Many functions return values that are accurate to 38 decimal digits.

ROUND Function:
Systax: ROUND(m,n)

It returns ‘m’ round to ‘n’ places right of the decimal point.


If ‘n’ omitted , n is rounded to 0, places
‘n’ can be negative , and rounds off the digits to the left of the decimal point.
‘n’ must be an integer.

Sql>Select 19.637 Num1ROUND(19.637,1) Rounded


From Dual;
Sql> Select 19.637 Num-,ROUND(19.637,-1) Rounded
From Dual;
Sql> Select 7843.637 Num1_,
ROUND(7843.637,2) Rounded,
ROUND(7843.637,-1) Rounded,
ROUND(7843.637,-2) Rounded,
ROUND(7843.637,-3) Rounded,
ROUND(7843.637,-4) Rounded
From Dual;

TRUNCATE Function:
Systax:TRUNC(m,n)
It returns ‘m’ Truncated to ‘n’ decimal places.
If ‘n’ omitted , n is truncated to 0 decimal places.
‘n’ can be negative to truncate ‘m’ digits left of the decimal point.
Sql>Select 19.637 Num1,TRUNC(19.637,1) Truncated
From Dual;
Sql> Select 19.637 Num1-, TRUNC(19.637,-1) Truncated
From Dual;
Sql> Select 7843.637 Num1,
TRUNC(7843.637,2) Truncated,
TRUNC(7843.637,2) Truncated,
TRUNC(7843.637,2) Truncated,
TRUNC(7843.637,2) Truncated,
TRUNC(7843.637,2) Truncated
From Dual;
CEIL Function:
Syntax:CEIL(n)
Returns the Largest integer greater than or equal to ‘n’.
The adjustment is done to the highest Nearest decimal value.
Sql>Select 19.001 Num1,CEIL(19.001) Ceiled
From Dual;
Sql> Select 19.34 Num1,
CEIL(19.32) Ceiled ,
CEIL(19.2) Ceiled ,
CEIL(19) Ceiled ,
From Dual;
FLOOR Function:
Syntax: FLOOR(n)
Returns the smallest integer less than or equal than ‘n’.
The adjustment is done to the lowest Nearest decimal value.
Sql>Select 19.001 Num1, FLOOR(19.999) Floor
From Dual;
Sql> Select 18.34 Num1,
FLOOR(18.34) Floor,
FLOOR(18.9) Floor,
FLOOR(18) Floor
From Dual;
MODULUS Function:
Syntax: MOD(m,n)
It Returns remainder of ‘m’ divided by ‘n’.
It returns ‘m’ if ‘n’ is 0.
Sql> Select MOD(100,10) Modulus,
MOD(17,4) Modulus From Dual;
POWER Function:
Syntax: POWER(m,n)
It Returns ‘m’ Raised to the ‘n’th power.
The base ‘m’ and the exponent ‘n’ can be any number.
Sql> Select POWER(5,2) Power,
POWER(-5,2)Power
From Dual;
Sql> Select POWER(5,-2) Power,
POWER(-5,-2)Power
From Dual;

SQUARE Function:
Syntax: SQRT(n)
It Returns Square Root of ‘n’ as Real Value.
The Value of ‘n’ cannot be negative.
Sql> Select SQRT(25) From Dual;

ABSOLUTE Function:
Syntax: ABS(n)
It Returns the Absolute value of ‘n’

Sql> Select ABS(-100) From Dual;


Sql>Select Sal, Comm, Sal-Comm, ABS(Sal-Comm) FROM Emp;

SIGN Function:
Syntax: SIGN(n)
It Returns the SIGN, Specification of a number.
If n<0,returns -1
If n=0,returns 0
If n>0,returns 1

Sql> Select SIGN(-10), SIGN(10), SIGN(0) From Dual;


Sql>Select Sal, Comm, SIGN(Sal-Comm), ABS(Sal-Comm) FROM Emp
Where SIGN(Sal-Comm)=-1

Working With Dates:

Oracle stores dates in an internal numeric format.


The dates in Oracle range from January 1,4712 BC to December 31,9999 AD.
The default display and input format for any date is DD-MON-YY.
The numeric format represents

**Century **Year **Month **Day **Hours


**Minutes **Seconds

SYSDATE:

It is a date function that returns current date and time.


SYSDATE is generally selected upon a DUAL Table.

Sql>Select SYSDATE From Dual;

Date Arithmetic:

As database stores dates as numbers, it allows to perform calculations using arithmetic operators such as addition and subtraction.
We can perform the following operations…….
Date + Number Date Adds a number of days to a date.
Date - Number Date Subtracts a number of days from a date .
Date - Date Number of days Subtracts one date from another.
Date + Number/24 Date Adds a number of hours to a date.

Sql>Select SysdateFrom Dual;

Sql>Select Sysdate,Sysdate+10 From Dual;

Sql>Select Sysdate,Sysdate+48/24 From Dual;

Sql>Select Ename,Hiredate,Hiredate+10 From Emp;

Sql>Select Ename,Hiredate,Hiredate-5 From Emp;

Sql>Select Ename,Hiredate,Sysdate-Hiredate “ExofEmps” From Emp;

Sql>Select Ename,Round((Sysdate-Hiredate)/7) Weeks From Emp;

Sql>Select Empno,Hiredate,Round((Sysdate-Hiredate)/365)
From Emp;

DATE Function:

Add_ months Function:

Syntax:ADD_MONTHS(D, +(or)-N)

Adds ‘N’ number of calendar months to date.


The value of ‘N’ must be an integer and can be negative.

Sql>Select Sysdate, Add_months(Sysdate,1) From Dual;

Sql>Select Ename, Sal, Hiredate, Add_months(Hiredate,1) From Emp


Where Deptno=30;

Months_Between Function:

Syntax: Months_between(D1,D2)
It gives the different between dates D1 and D2 In months.
If D1 is later than D2, the result is Positive, else Negative.
If D1 and D2 are either the same days of the months or both last days of the months, the result is always an integer.

Sql>Select Ename,Hiredate,
Round(Months_Between(Sysdate,Hiredate)/12) " Experience In Years"
From Emp;
Sql> Select Ename,Hiredate,Months_Between(Sysdate,Hiredate)
From
EmpWhereMonths_Between(Sysdate,Hiredate)<320;

Next_Day Function:

Syntax: Next_day (D, Char)

It returns the date of the first week day named by char, that is later
than the data D.
The CHAR must be a day of the week in the sessions data language.
The day of the week can be full name or the abbreviation.

Sql>Select Sysdate, Next_day(Sysdate,’WED’) From Dual;

Sql>Select Sal,Hiredate,Next_day(Hiredate,’MONDAY’) From Emp;

Last_Day Function:

Syntax:Last_day(D)

It returns the date of the last day of the month that contains D.
Mostly used to determine how many days are left in the current month.

Sql> Select Sysdate, Last_day(Sysdate) Last,


Last_day(Sysdate)-SysdateDaysleft From Dual ;

Real Time Scenario:

Sql> Select Add_months(Last_day(Sysdate),-1)+1 From Dual;

Rounding of Dates:

Syntax: Round(Date,’Format’)

Returns Date rounded to the Unit specified by the format.


If format is omitted, Date is rounded to the nearest day.

Sql> Select Round(Sysdate,'DAY') From Dual;


Sql>Select Round(Sysdate,'MONTH') From Dual;

Sql>Select Round(Sysdate,'YEAR') From Dual;

Truncating Dates:
Synatx:Trunc(Date,’Format’)

Return Date with the time portion of the day truncated to the specified unit.
If format is omitted, data is truncated to the nearest day.

Sql> Select Round(Sysdate,'DAY'), Trunc(Sysdate,'DAY') From Dual;

Sql>Select Round(Sysdate,'MONTH'), Trunc(Sysdate,'MONTH') From Dual;


Sql>Select Round(Sysdate,'YEAR'), Trunc(Sysdate,'YEAR') From Dual;

Conversion Function:

The Conversation functions convert a value from one data type to another.
The Data type conversion in Oracle is two types.

**Implicit Data type Conversion

**Explicit Data type Conversion

Implicit Data type Conversion:

Implicit Date type conversion work according to the convention specified by oracle.
The Assignment succeeds if the Oracle server can convert the date type of value.
CHAR to NUMBER conversion succeed only if the character string represent a valid NUMBER.
CHAR to DATES conversion succeed only if the character string represent the default format of DD-MON-YY.

In Assignment Operator:
Varchar2/Char àNumber
Varchar2/Char àDate
Number àVarchar2
Date àVarchar2

Explicit Data type Conversion:


SQL provided three function to convert a value from one data type to another.
The explicit conversation function are
TO_CHAR àTo Character Conversion.
TO_DATE àTo Date Conversion.
To_Numberà To Number Conversion

TO_CHAR Conversion:

This function can be used in two ways.


TO_CHAR(Number Conversion)
TO_CHAR(Date Conversion)

TO_CHAR(Number Conversion)
Syntax: TO_CHAR(NUMBER,fmt)
Converts Number of Number data type to a value of VARCHAR2 data type.
‘fmt’ is the optional number format, that can be used.

TO_CHAR(Date Conversion)
Syntax: TO_CHAR(DATE,fmt)
Converts Date of Date data type to a value of VARCHAR2 data type in the format specified.
‘fmt’ is the optional Date format, that can be used.

Decimal Indicator:Dà99D99
It returns the specified position of the decimal character .
The default decimal delimiter is period ‘.’
Only one decimal indicator can be specified in a number format model.

Sql>Select 1234,TO_CHAR(1234,'9999D99') From Dual;

Sql>Select 1234,TO_CHAR(1234,'999D99') From Dual;

Scientific Notation Indicator:EEEEà9.9EEEE

Returns a Numeric value using scientific notation.


Sql>Select TO_CHAR(5634,'9.9EEEE') From Dual;

Group Separator: Gà9G999

Returns the specified position of the Group separator


Multiple Group separators can be specified.

Sql>Select TO_CHAR(1234567,'99G99G9999') From Dual;

Sql> Select Sal,TO_CHAR(Sal,'9G999') From Emp;

Local Currency Indicator: LàL999 OR 999L

Returns the specified position of the local currency symbol.

Sql>Select 1234,TO_CHAR(1234,'L9999') From Dual;


Sql>Select Sal,TO_CHAR(Sal,'L999999') Currency From Emp Where Deptno=10;
Sql>Select Sal,TO_CHAR(Sal,'L99G999D99','NLS_CURRENCY=IndRupees')
Sal FromEmp Where Deptno=20;

Trailing Minus Indicator: MIà9999MI

Return negative value with a trailing minus sign’-‘.


Returns positive value with a trailing Blank.
‘MI’ Format should be declared as Trailing argument only.

Sql>select -10000,TO_CHAR(-10000,'L99G999D99MI') From Dual ;

Sql>select Sal,Comm,Comm-Sal,
TO_CHAR(Comm-Sal,'L99G999D99MI') From Emp;

Negative Number Indicator:PRà9999PR

Returns negative number in ’<>’.


It Can appear only as trailing declaration.
Sql>select TO_CHAR(-1000,'L99G999D99PR') From Dual;

Sql>select Sal,Comm,Comm-Sal,
TO_CHAR(Comm-Sal,'L9999PR') From Emp;

Roman Number Indicator:

RNàReturns Upper Roman Number.


rnà Returns Lower Roman Number.
The value can be an integer between 1 and 3999.

Sql> select 12,TO_CHAR(12,'RN'),TO_CHAR(12,'rn') From Dual;

Sign Indicator:SàS99999 OR 99999S

Returns Negative value with a leading Minus Sign.


Returns Positive value with a leading Plus Sign.
Returns Negative value with Trailing Minus Sign.
Returns Positive value with a Trailing Plus Sign.
‘S’ can appear as First or Last value.

Sql> select 1000,TO_CHAR(1000,'S9999'),TO_CHAR(-1000,'S9999') From Dual;

Sql>select TO_CHAR(1000,'9999S'),TO_CHAR(-1000,'9999S') From Dual;

Sql>select Sal,TO_CHAR(Sal,'S99999'),TO_CHAR(Sal,'9999S') From Emp;

Sql>select Sal,Comm,TO_CHAR(Comm-Sal,'S99999'), TO_CHAR(Comm-Sal,'9999S')


From Emp;
Hexadecimal Indicator: XàXXXX

Returns the Hexadecimal value of the specified number of Digits.


If the Number is not an integer, oracle rounds it to an integer.
Accepts only positive values or 0.

Sql>select 2000,TO_CHAR(2000,'XXXX') From Dual;

Sql>Select Ename,Sal,TO_CHAR(Sal,'XXXX') Hexsal From Emp;

Group Separator:à9,999

Returns a comma in the specified position.


Multiple commas can be specified.

Sql>select 20000,TO_CHAR(20000,'99,999.99') From Dual;

Sql>Select Ename,Sal,TO_CHAR(Sal,'99,999.99') From Emp;

Decimal Indicator:à99.99

Returns a decimal point, at the specified position.


Only one period can be specified in a number format model.
Sql> Select 20000,TO_CHAR(20000,'L99,999.99') From Dual;

Sql>Select Ename,Sal,TO_CHAR(Sal,'L99,999.99') From Emp;

Dollar Indicator: $ à$9999

Return value with a leading dollar sign.

Sql>Select 20000,TO_CHAR(20000,'$99,999.99') From Dual;

Sql> Select Ename,Sal,TO_CHAR(Sal,'$99,999.99') From Emp;

Zero Indicator:0à0999 OR 9990

Returns Lading OR Trailing Zeros.

Sql>select 1000,TO_CHAR(1000,'0999999'),TO_CHAR(1000,'09999990') From Dual;

Sql>select Ename,Sal,TO_CHAR(Sal,'$099,999.99') From Emp;

Digit Place Marker: 9à9999

Returns value with a specified number of digits with a Leading space when positive or Leading minus when Negative.

Sql>select 1000,600,TO_CHAR(1000-600,'99999'),
TO_CHAR(600-1000,'99999') From Dual;

Sql>select 20.25,20,TO_CHAR(20.55-20,'99999'),
TO_CHAR(20.25-20,'99999') From Dual;

ISO Currency Indicator: CàC9999

Return specified position of the ISO Currency Symbol.

Sql>select 1000,TO_CHAR(1000,'C9999.99') From Dual;

Sql>select Ename,Sal, TO_CHAR(Sal,'C9999.99') From Emp;

Date Format Models:

The date format models can be used in the TO_CHAR function to translate a DATE value from original format to user format.
Data Format Elements:

A Date format model is composed of one or more date format elements.


For input format models, format items cannot appear twice, and format items that represents similar information cannot be combined.
Capitalization in a spelled word, abbreviation, or roman numeral follows capitalization in the corresponding format element.
Punctuation such as Hyphens, Slashes, Commas, periods and Colons.

AD or A.D./BC or B.C. Indicator:


Indicator AD/BC with or without periods.

Sql>Select Sysdate,TO_CHAR(Sysdate,’AD’) From Dual;


Sql>Select TO_CHAR(Sysdate,’B.C.’),
TO_CHAR(Sysdate,’A.D.’) From Dual;

Sql>Select Ename,Sal,Hiredate,TO_CHAR(Hiredate,’A.D.’) From Emp;

Meridian Indicator:

It indicates meridian indicator with or without periods.

Sql>Select Sydate,TO_CHAR(Sysdate,’A.M.’),
TO_CHAR(Sysdate,’PM’) From Dual;

Sql>Select Ename,Sal,Hiredate,TO_CHAR(Hiredate,’AM’) From Emp;

Century Indicator: CC

Indicates the century.

Sql> Select Sydate,TO_CHAR(Sysdate,’CC-AD’) From Dual;

Numeric Week day indicator:Dà(1-7)

Returns the week day number.

Sql>Select Sysdate,TO_CHAR(Sysdate,’D’) From Dual;

Sql>Select Ename,Sal,Hiredate,TO_CHAR(Hiredate,’D’) From Emp;

Week day spelling indicator:àDay.

Pads to a length of 9 characters.

Sql>Select Sysdate,TO_CHAR(Sysdate,'DAY') From Dual;

Sql>Select Ename,Hiredate,TO_CHAR(Hiredate,'DAY')
From Emp Where TO_CHAR(Hiredate,'DY')='MON';

Month day Indicator:DD

It indicates the day of the Month(1-31)

Sql>Select Sysdate,TO_CHAR(Sysdate,'DD-DAY') From Dual;

Sql>Select Ename,Hiredate,TO_CHAR(Hiredate,'DD_DAY') From Emp;

Sql> Select Ename,Hiredate,TO_CHAR(Hiredate,'DY') From Emp


Where TO_CHAR(Hiredate,'DD-DY')='28-MON';

Year day indicator:DDD


It indicates the day of the Yaer(1-366)

Sql>Select Sysdate,TO_CHAR(Sysdate,'DDD') From Dual;


Sql>Select Ename,Hiredate,TO_CHAR(Hiredate,'DDD') From Emp;
Sql> Select Ename,Hiredate,TO_CHAR(Hiredate,'DDD') From Emp
Where TO_CHAR(Hiredate,'DY')='MON';

Abbreviated week day: DY

It indicates the day of the Yaer(1-366)

Sql>Select Sysdate,TO_CHAR(Sysdate,'D-DY-DAY') From Dual;


Sql>Select Ename,Hiredate,TO_CHAR(Hiredate,'D-DY-DAY') From Emp
Where Deptnoin(10,20);

ISO standard year week indicator: IW

Specifies the week of the yaer(1-52 or 1-53) based on the ISO standard.

Sql>Select Sysdate,TO_CHAR(Sysdate,'IW') From Dual;

Sql>Select Ename,Hiredate,TO_CHAR(Hiredate,’IW’) From Emp;

ISO standard 4 digit year indicator: IYYY

Specifies 4 digit year based on the ISO standard.


It can even be used in combination of IYY,IY,I.
Sql>Select Sysdate,TO_CHAR(Sysdate,'IYYY')
From Dual;
Sql>Select Ename,Hiredate,TO_CHAR(Hiredate,’IYYY’)
From Emp
Where TO_CHAR(Hiredate,'DY')='MON';
Four Digit Year Indicator:YYYY or SYYY

Return four digit year,’S’ prefixes BC dates with ‘-‘.


It can even be used in combination of YYY or YY or Y.
Y,YYY returns year with comma in that position.

>Select to_char(sysdate,’syyyy’) from dual


Sql>Select Hiredate,TO_CHAR(Hiredate,'YYYY'),
TO_CHAR(Hiredate,'YYY') From Emp;

Sql>Select TO_CHAR(Sysdate,'YYYY'),TO_CHAR(Sysdate,'YYY'),
TO_CHAR(Sysdate,'YY') From Emp;

Spelled Year Indicator: YEAR or SYEAR

Returns the numerical year in spelling.

Sql> Select SYSDATE, TO_CHAR(Sysdate,'Year'),TO_CHAR(Sysdate,'YEAR')


From Dual;
Sql> Select Empno,Ename,Hiredate,TO_CHAR(Hiredate,'Year') From Emp;

Week of the month indicator: W

Specifies the week of the month(1-5).


Week starts on the first day of the month and ends on the seventh day.
Sql> SelectSysdate,TO_CHAR(Sysdate,'W') From Dual;

Sql> SelectEmpno,Ename,Hiredate,TO_CHAR(Hiredate,'W') From Emp;

Year week Indicator:WW

Specifies the week of the year(1-53)


Week 1 starts on the first day of the year and continues to the seventh day in that year.

Sql> SelectSysdate,TO_CHAR(Sysdate,'WW') From Dual;

Sql> SelectEmpno,Ename,Hiredate,TO_CHAR(Hiredate,'WW') From Emp;

Quarter of the Year Indicator:Q

Returns the Quarter if the year.


Quarter starting with the month of January and ending with every three months.

Sql> SelectSysdate,TO_CHAR(Sysdate,'Q') From Dual;

Sql> SelectEmpno,Ename,Hiredate,TO_CHAR(Hiredate,'Q') From Emp Where TO_CHAR(Hiredate,’Q’)=3;


Julian Day Indicator: J

Returns the JULIAN Day of the given date.


It is the number of day since January 1,4712 BC.
Number specified with ‘J’ must be integers.

Sql> SelectSysdate,TO_CHAR(Sysdate,'J') From Dual;

Sql> SelectEmpno,Ename,Hiredate,TO_CHAR(Hiredate,'J-DDD-DD-D') From Emp;

Number Month Indicator:MM

Returns the numeric abbreviation of the month.

Sql> Select Sysdate,TO_CHAR(Sysdate,'MM-YYYY') From Dual;


Sql> Select Ename,TO_CHAR(Hiredate,'DD-MM-YYYY') From Emp Where TO_CHAR(Hiredate,’MM’)=12;

Abbreviated Month Indicator:MON


Returns the abbreviated name of the Month.

Sql> Select Sysdate,TO_CHAR(Sysdate,'MON') From Dual;

Sql> Select Hiredate,TO_CHAR(Sysdate,'MONTH') From Emp;

Twelve Hour Clock Mode: HH or HH12


It is default clock mode.
Returns the hour of the day in twelve hour clock mode.

Sql> Select Sysdate,TO_CHAR(Sysdate,'HH'), TO_CHAR(Sysdate,'HH12,PM')


From Dual;
Sql> Select Ename,Hiredate,TO_CHAR(Hiredate,'HH12:PM') From Emp;

Twenty Hour Clock Mode:HH24

Returns the hour of the day in twenty four hour clock mode.(0-23)

Sql> Select Sysdate,TO_CHAR(Sysdate,'HH24') From Dual;

Real Time Scenario:

Minutes Indicator: MI

Returns the minutes from the given date(0-53).

Sql> Select Sysdate,TO_CHAR(Sysdate,'MM') From Dual;


Sql> Select Ename,Hiredate,TO_CHAR(Hiredate,'HH:MM') From Emp
Where Deptno=20;

Roman Month Indicator: RM

Return the roman numeral month(I-XII).

Sql> Select Sysdate,TO_CHAR(Sysdate,'RM'), TO_CHAR(Sysdate,'DD-RM-YY')


From Dual;
Sql> Select Ename,Hiredate,TO_CHAR(Hiredate,'DD-RM-YY') From Emp
Where Deptno=20;

Seconds Indicator: SS

Returns seconds from the given the dates(0-59)

Sql> Select Sysdate,TO_CHAR(Sysdate,'SS'),


TO_CHAR(Sysdate,'HH:MI-SS') From Dual;

Sql> Select Sysdate,TO_CHAR(Sysdate,'RM'),


TO_CHAR(Sysdate,'Day-Month-Yaer HH24:MI:SS PM.') From Dual;

Sql> Select Ename,Hiredate,TO_CHAR(Hiredate,'HH24-MI-SS') From Emp


Where Deptno=30;

Date Format Punctuators:

The punctuation marks that can be used in date formats are…

'-', '/', '!', '.', ';', ':', 'text'


Date Format element suffices: TH or SP
THàSuffixes the ordinal number with ‘st’ or ‘nd’ or ‘rd’ or ‘th’.

Example:

Sql>Select Sysdate,TO_CHAR(Sysdate,'DDth,MONTH,YYYY') From Dual;

Sql>Select Ename,Hiredate, TO_CHAR(Hiredate,'DDth,MONTH,YYYY') From Emp;

SPàSpells ordinal numbers.

Sql>Select Sysdate,TO_CHAR(Sysdate,'DDsp,MONTH,YYYY') From Dual;

Sql>Select Ename,Hiredate,TO_CHAR(Hiredate,'DDsp,MONTH,YYYY') From Emp;

Sql>Select Ename,Hiredate, TO_CHAR(Hiredate,'DDspth,MONTH,YYYY') From Emp;

Sql>Select Sysdate,TO_CHAR(Sysdate,'DDspth Month YYYYSP') From Dual;

Date Format Elements restrictions:

The suffixes when added to date return values always in English.


Data suffixes are valid only on output, hence cannot be used to insert a data into the database.

Format Model Modifiers:


Fill Mode Indicator :FM

It suppresses blank padding in the return value of the TO_CHAR function.

Sql> Select Sysdate,


TO_CHAR(Sysdate,'DDSPTH MONTH YYYYSP'),
TO_CHAR(Sysdate,'FMDDSPTH MONTH YYYYSP') From Dual;

TO_NUMBER Function:

Syntax:TO_NUMBER(Char,fmt)

It convert a char ,value of CHAR or VARCHAR2 data type containing a NUMBER in the format specified by the optional format model ‘fmt’, to a value of NUMBER data type.

Sql> Select '$10,000.00',


TO_NUMBER('$10,000.00','L99,999.99') From Dual;

Sql> Select '$10,000.00',


TO_NUMBER('$10,000.00','L99,999.99')+500 From Dual;

TO_DATE function:

Syntax:TO_DATE(Char,’fmt’)
Converts given char of Char or Varchar2 data type to a value of DATE data type.
The ‘fmt’ is optional Date format specified the format of CHAR.

Sql> Select TO_CHAR(TO_DATE('12-JAN-1980'),'DDSP') From Dual;


Sql> Select Ename,Hiredate,
ADD_MONTHS(TO_DATE
('1980-DECEMBER-17','YYYY-MONTH-DD'),3) FROM Emp
WHERE Hiredate='17-DEC-1980';

Sql>Select Ename,Hiredate, ADD_MONTHS(


TO_DATE('1980-DECEMBER-17','YYYY-MONTH-DD'),3) FROM Emp
WHERE TO_CHAR(Hiredate,'FMYYYY-MONTH-DD')='1980-DECEMBER-17';

INSERT Statement With Invalid Number:

Sql>Create Table Temp


( Empno Number(8),
Doj Date );

Sql>Insert into Temp


Values( TO_NUMBER(‘1,23,456’,’9G99G999’),
SYSDATE );

Sql> Insert into Temp


Values( TO_NUMBER('1,23,456-','9G99G999MI'),
SYSDATE );

Invalid Dates:

Sql>Insert Into Temp Values(1001,’12-JAN-09 11:30:15’);

Sql> Insert Into Temp


Values(
1001,TO_DATE(’12-JAN-2009
11:30:15 P.M.’,’DD-MON-YYYY HH:MI:SS P.M’
);
Sql> Insert Into Temp
Values(
1001,
TO_DATE('12-JAN-3712 B.C.',
'DD-MON-YYYY B.C. ')
);

Sql> Insert Into Temp


Values(
1001,
TO_DATE(100,'J')
);

Sql>Select TO_DATE(10,’DD’) From Dual;


Sql> Select TO_DATE(10,’DDD’) From Dual;

Sql>Select TO_DATE(1,’W’) From Dual;

Sql> Select TO_DATE(1,’WW’) From Dual;


RR Date Format Elements:

The RR date format element is similar to the YY date format element.


Te RR format elements provides additional flexibility for storing data values in other centuries.
The RR date format element allows to store the date to the previous as well as the next centuries.
The RR format elements should be used in association with TO_DATE conversion function only, else the system treats it as YY format element.
The format can be used as either ‘RR’ or ‘RRRR’ format element.

Century Identification:

Last Two Digits of the


year managed by clock 0 To 49 50 To 99
Returns the date in Returns the date in the
Current century previews Century.

Some Combinations

Sql>Select
TO_CHAR( ADD_MONTHS(Hiredate,1), 'DD-MON-YYYY' ) "Next Month"
From Emp Where Empno=7788;

Sql> Select
Concat(Concat(Ename, 'is a '), Job )Designation From Emp
Where Deptno=20;
Sql> Select Trunc( TO_DATE('27-OCT-92','DD-MON-YY'), 'YEAR' )"New Year"
From Dual;
Sql>Select
TO_CHAR( ADD_MONTHS(
LAST_DAY(Hiredate),5),'DD-MON-YYYY' )"Five Months"
From Emp Where Empno=7788;
Sql>Select
MONTHS_BETWEEN(
TO_DATE( ’02-02-1995’,’MM-DD-YYYY’ ),
TO_DATE( ’02-02-1995’,’MM-DD-YYYY’ )
)Months FROM Dual;

Sql>Select NEXT_DAY(’15-MAR-98’,’TUESDAY’) From Dual;

Sql>Select Ename,
NVL(TO_CHAR(Comm),’Not Applicable’) “Commission”
From Emp
WHERE Deptno=30;

Sql>Select
Round(
TO_DATE(’27-OCT-92’,’DD-MON-YY’),’YEAR’
)”New Year”
From Dual;

Sql>Select TO_CHAR(Hiredate,’MONTH DD,YYYY’)


From Emp
Where Ename=’FORD’;

Sql>Select Ename,
TO_CHAR(Hiredate,’FMMonth,DD YYYY’) Hiredate
From Emp WhereDeptno=20;
Sql> Select
TO_CHAR(
TO_DATE('27-OCT-98','DD-MON-RR'),'YYYY') Year From Dual;

Assumption: Queries are issued Between Year 1950-1999.

Sql> Select TO_CHAR(Sysdate,'FMDDTH')||' of '||


TO_CHAR(Sysdate,'Month')||' , '||
TO_CHAR(Sysdate,'YYYY')Idea From Dual;

Sql>Select Ename,Job,
NVL(TO_CHAR(MGR),’Supreme Authority’) “Managers”
From Emp Order by Sal Desc;

Spelling a Number:

Sql> Select
TO_CHAR( TO_DATE('&GiveNumber','J'), 'JSP' ) "Spelled Number"
From Dual;

Selecting a Date Specific to its Century:

Sql>Select
TO_CHAR( TO_DATE(Hiredate,’DD-MON-RRRR’), ‘DD-MON-YYYY’ ) Hiredate
From Emp;
Text Encryption:
Sql>Select
‘KRISHNA REDDY’ OrgName,
Translate(
‘KRISHNA REDDY’,
‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’,
‘1234567890!@#$%^&*()-=_+;,.’)Encryptedname
From Dual;

Text Decryption:

Sql> Select '!*9(8$1 *544;' Encryptedname,


Translate(
'!*9(8$1 *544;',
'1234567890!@#$%^&*()-=_+;,',
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
)Encryptedname
From Dual

Aggregating or Group Functions:

Group functions operate on sets of rows to give one


result per group.
Group functions can appear in select lists and in ORDER BY and HAVING clauses.
The Oracle Server applies the group functions to each group of rows and returns a single result row for each group.
The group functions to return summary information for each group.

Syntax:
group_function(DISTINCT/ALL Column)

Guidelines for Using Group Functions:

The data types for the arguments can be CHAR, VARCHAR2, NUMBER, or DATE.
All group functions except COUNT(*) ignore null values. To substitute a value for null values, use he NVL function. COUNT returns either a number or zero.
The Oracle Server implicitly sorts the result set in ascending order of the grouping columns specified, when you use a GROUP BY clause. To override this default ordering, you can use
DESCin an ORDER BY clause.
When a group function is declared in a SELECT list, on single row columns should be declared.

Average Function:

Syntax: AVG(DISTINCT/ALL Column)

It returns the Average value of column.


It ignores NULL values.

Sql>Select Avg(Sal),Avg(DISTINCT Sal) From Emp;

Sal>Select Avg(Comm),Avg(DISTINCT Comm) From Emp;

Sum Function:

Syntax: SUM(DISTINCT/ALL Column)

It returns the SUM value of column.


It ignores NULL values.

Sql>Select SUM(Sal),SUM(DISTINCT Sal) From Emp;

Sql>Select SUM (Comm), SUM (DISTINCT Comm) From Emp;

Maximum Function:

Syntax: MAX(DISTINCT/ALL Column)

It returns the Maximum value of column.


It ignores NULL values.
Sql>Select MAX(Sal),MAX(DISTINCT Sal) From Emp;

Sql>Select MAX (Comm), MAX (DISTINCT Comm) FromEmp;

Sql> Select MAX(Ename) From Emp;

Minimum Function:

Syntax: MIN(DISTINCT/ALL Column)

It returns the Minimum value of column.


It ignores NULL values.

Sql>Select MIN(Sal),MIN(DISTINCT Sal) From Emp;

Sql>Select MIN (Comm), MIN (DISTINCT Comm) From Emp;

Sql> Select MIN(Ename) From Emp;

Sql> Select MIN(Hiredate),Max(Hirdate) From Emp;

Standard Deviation Function:

Syntax: STDDEV(DISTINCT/ALL Column)

It returns the Standard Deviation of column.


It ignores NULL values.

Sql>Select STDDEV(Sal),STDDEV(DISTINCT Sal) From Emp;

Sql>Select STDDEV (Comm), STDDEV (DISTINCT Comm) From Emp;

Variance Function:

Syntax: Variance(DISTINCT/ALL Column)

It returns the Variance of N.


It ignores NULL values.

Sql>Select VARIANCE(Sal), VARIANCE (DISTINCT Sal) From Emp;

Sal>Select VARIANCE (Comm), VARIANCE (DISTINCT Comm) From Emp;

Count Function:

Syntax: COUNT(*/DISTINCT/ALL Column)

It Gives No of Rows in the Query.


If ‘*’ used to returns all Rows, Including duplicated and NULLs.
It can used to specify the count of all rows or only distinct values of column.

Sql>Select COUNT(Empno) From Emp;


Sql> Select COUNT(Job),COUNT(DISTINCT Job) From Emp;

Sql>Select COUNT(Sal),COUNT(DISTINCT Sal) From Emp;

Sql>Select Count(*) From Emp;

Sql> Select COUNT(Empno),COUNT(DISTINCT MGR) From Emp;

Sql>Select Select COUNT(Job),COUNT(DISTINCT MGR) From Emp Where Deptno=20;

Creating Groups of Data:

The Group by clause is used to decide the rows in table into groups.

Syntax1:
Sql>SELECT columnname1, Columnname2,……
FROM table
[WHERE condition(s)]
[GROUP BY Column name(s)]
[ORDER BY column(s)];

Syntax2:
Sql>SELECT columnname1, GRP_FUN(Column)
FROM table
[WHERE condition(s)]
[GROUP BY Columnname(s)]
[ORDER BY column(s)];

Guidelines to use Group By Clause:

All GROUP BY CLAUSE columns list may or may not used in SELECT clause.
The Extra non Group functional column should be declared in the GROUP BY Clause.
If the GROUP Function is included in a SELECT clause, we should not use individual result columns.
Using WHERE clause, Rows can be pre excluded before dividing then into groups.
Column aliases cannot be used used in GROUP BY CLAUSE.
By default, Rows are sorted by ascending order of the columns included in the GROUP BY LIST.

Example:

Sql>Select Job FromEmp GROUP BY Job;

Sql>Select Deptno FromEmp GROUP BY Deptno;

Sql> Select Mgr FromEmp GROUP BY Mgr;

Sql> Select TO_CHAR(Hiredate,'YYYY') YearGroup From Emp


GROUP BY TO_CHAR(Hiredate,'YYYY');

Sql> Select TO_CHAR(Hiredate,'Month') MonthGroup


From Emp GROUP BY TO_CHAR(Hiredate,'Month');
Sql> Select TO_CHAR(Hiredate,'DD') DayGroup
From Emp GROUP BY TO_CHAR(Hiredate,'DD');

Sql> Select TO_CHAR(Hiredate,'Month') MonthGroup


From Emp Where TO_CHAR(Hiredate,’Mon’)<>’Dec’
GROUP BY TO_CHAR(Hiredate,'Month');

Creating Group wise summaries:

Sql>Select Owner,COUNT(Object_Name)
From dba_objects Group By Owner;

Sql> Select Deptno,COUNT(*) From emp Group By Deptno;

Sql>Select Deptno, AVG(Sal) From Emp Group By DeptnoOredr By AVG(Sal);

Sql>Select Deptno,Min(Sal),Max(Sal) From Emp Group by Deptno;

Sql>Select Ename, Max(Sal) From Emp Group By Deptno;

Note: It will give error .

Sql>Select Deptno,SUM(Sal) From Emp Group By Deptno;

Sql>Select Deptno,Job,SUM(Sal) From Emp GROUP BY Deptno,Job;

Sql>Select Deptno,Job,SUM(Sal) From Emp GROUP BY Deptno,Job;

Sql>Select Job,Min(Sal),Max(Sal) From Emp Where Deptno=30 GROUP BY Job;

Sql>Select Deptno,Sum(Sal),Max(Sal) From Emp Where Job='CLERK'


GROUP BY Deptno;

OCP Questions:

1)Examine the description of the STUDENTS table:

STD_ID NUMBER(4)
COURSE_ID VARCHARD2(10)
START_DATE DATE
END_DATE DATE

Which two aggregate functions are valid on the START_DATE column? (Choose two)

A. SUM(start_date) B. AVG(start_date)
C. COUNT(start_date) D. AVG(start_date, end_date)
E. MIN(start_date) F. MAXIMUM(start_date)

Having Clause:

You may not want all the summary rows returned by a GROUP BY query. You know that you can use WHERE to eliminate detail rows returned by a regular query. With summary queries,
you can use the HAVING clause to eliminate summary rows.
It used generally with GROUP BY Clause the having is useful for specifying a condition for the group.
The Clause is used to filter data that is associated with group function.

Syntax:
SELECT [column,] group_function(column). . .
FROM Table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING having_expression];
[ORDER BY Column/Alias];

You might also like