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

Introduction To Oracle: SQL

The document provides an introduction to relational database concepts and the Oracle SQL language. It discusses key topics such as: 1) The relational model proposed by Dr. E.F. Codd which forms the basis for relational database management systems and includes collections of relations, a set of operators, and data integrity. 2) Key components of a relational database including tables that contain rows and columns of data that are logically related through primary and foreign keys. 3) Common SQL statements used to define the database schema, manipulate data, and control transactions and access including DDL, DML, and DCL statements. 4) Examples of basic SQL SELECT statements to retrieve data from one or
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views

Introduction To Oracle: SQL

The document provides an introduction to relational database concepts and the Oracle SQL language. It discusses key topics such as: 1) The relational model proposed by Dr. E.F. Codd which forms the basis for relational database management systems and includes collections of relations, a set of operators, and data integrity. 2) Key components of a relational database including tables that contain rows and columns of data that are logically related through primary and foreign keys. 3) Common SQL statements used to define the database schema, manipulate data, and control transactions and access including DDL, DML, and DCL statements. 4) Examples of basic SQL SELECT statements to retrieve data from one or
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 95

Introduction to Oracle : SQL

System Development Life Cycle

Strategy
and
Analysis
Design
Build
and
Document
Transition

Production
Data Storage on Different Media
SALGRADE
DEPT GRADE LOSAL HISAL
DEPTNO DNAME LOC 1 700 1200
10 ACCOUNTING NEW YORK 2 1201 1400
20 RESEARCH DALLAS 3 1401 2000
4 2001 3000
30 SALES CHICAGO
5 3001 9999
40 OPERATIONS BOSTON

a a a a a
a a a a a a a a a a
a a a a a a a a a a
a a a a a a a a a a
a a a a a a a a a a
a a a a a a a a a a
a a a a a

Electronic Filling Cabinet Database


Spreadsheet
Relational Database Concepts
 Dr. E.F. Codd proposed the relational model for database systems in
1970.
 It is the basis for the relational database management system
(RDBMS).
 The relational model consists of the followings :

* Collection of objects or relations


* Set of operators to act on the relations
* Data integrity for accuracy and consistency
Definition of a Relational Database
A relational database is a collection of relations or two-dimensional tables.

Database
a a a a a
a a a a a
a a a a a
a a a a a
a a a a a
a a a a a

Table Name : EMP Table Name : DEPT


EMPNO ENAME JOB DEPTNO DEPTNO DNAME LOC
7839 KING PRESIDENT 10 10 ACCOUNTING NEW YORK
7698 BLAKE MANAGER 30 20 RESEARCH DALLAS
7782 CLARK MANAGER 10 30 SALES CHICAGO
7788 SCOTT ANALYST 20 40 OPERATIONS BOSTON
Relational Database Terminology
2 3 4
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 17-Dec-80 800 300 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-91 2975 20
7654 MARTIN SALESMAN 7698 28-Sep-81 1250 1400 30
7698 BLAKE MANAGER 7830 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 6 17-Nov-81 5000 10
7844 TURNER SALESMAN 7698 08-Sep-81 1500 5 0 30
7876 ADMAS 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
1 7934 MILLER CLERK 7782 23-Jan-82 1300 10

1. Row/Tuple 2. P.Key 3. Not Key Value 4. F. Key 5. Field 6. Null


Relating Multiple Tables
• Each row of data in a table is uniquely identified by a primary key.
• You can logically relate data from multiple tables using Foreign key.

Table Name : EMP Table Name : DEPT


EMPNO ENAME JOB DEPTNO DEPTNO DNAME LOC
7839 KING PRESIDENT 10 10 ACCOUNTING NEW YORK
7698 BLAKE MANAGER 30 20 RESEARCH DALLAS
7782 CLARK MANAGER 10 30 SALES CHICAGO
7788 SCOTT ANALYST 20 40 OPERATIONS BOSTON

Primary Key Foreign Key Primary key


Relating Database Properties

• Can be accessed and modified by executing structured query


language (SQL) statements.

• Contains a collection of tables with no physical pointers.

• Uses a set of operators.


Communicating with RDBMS Using SQL

SQL Statement is entered


Statement is sent to
SQL> SELECT loc database
FROM dept;
Database
Data is displayed
LOC
NEW YORK
DALLAS
CHICAGO
BOSTON
SQL Statements
SELECT Data Retrieval
INSERT
UPDATE Data Manipulation Language(DML)
DELETE
CREATE
ALTER
DROP Data Definition Language(DDL)
RENAME
TRUNCATE
COMMIT
ROLLBACK Transaction Control
SAVEPOINT
GRANT
REVOKE Data Control Language(DCL)
Tables Used During the Programme :
EMP
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 17-Dec-80 800 300 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-91 2975 20
7654 MARTIN SALESMAN 7698 28-Sep-81 1250 1400 30
7698 BLAKE MANAGER 7830 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 ADMAS 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
Table Name : DEPT SALGRADE
DEPTNO DNAME LOC GRADE LOSAL HISAL
1 700 1200
10 ACCOUNTING NEW YORK
2 1201 1400
20 RESEARCH DALLAS 3 1401 2000
30 SALES CHICAGO 4 2001 3000
40 OPERATIONS BOSTON 5 3001 9999
Writing Basic SQL Statements
Capabilities of SQL SELECT Statements
Selection Projection

Table1 Selection
Join

Table 1 Table2
Basic SQL Statement

SELECT [DISTINCT] { *, column [alias], …}


FROM table;

• SELECT identifies what columns.


• FROM identifies which table.
Writing SQL Statements

• SQL statements are not case sensitive.


• SQL statements can be on one or more lines.
• Keywords cannot be abbreviated or split across lines.
• Clauses are usually placed on separate lines.
• Tabs and indents are used to enhance readability.
Selecting All Columns

SQL> SELECT *
2 FROM dept;

DEPTNO DNAME LOC


10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
Selecting Specific Columns
SQL> SELECT deptno, loc
2 FROM dept;
DEPTNO LOC
10 NEW YORK
20 DALLAS
30 CHICAGO
40 BOSTON

SQL> SELECT loc, deptno


2 FROM dept;
LOC DEPTNO
NEW YORK 10
DALLAS 20
CHICAGO 30
BOSTON 40
Column Heading Defaults
• Default justification
* left : Date and character data
* Right : Numeric data
• Default display : Uppercase

SQL> SELECT ename, hiredate, sal


2 FROM emp;
ENAME HIREDATE SAL
KING 17-Nov-81 5000
BLAKE 01-May-81 2850
CLARK 09-Jun-81 2450
JONES 02-Apr-91 2975
MARTIN 28-Sep-81 1250
ALLEN 20-Feb-81 1600

14 rows selected.
Arithmetic Expressions

Create expressions on NUMBER and DATE data


by using arithmetic operators.

Operator Description
+ Add
- Subtract
* Multiply
/ Divide
Using Arithmetic Operators

SQL> SELECT ename, sal, sal+300


2 FROM emp;
ENAME HIREDATE SAL SAL+300
KING 17-Nov-81 5000 5300
BLAKE 01-May-81 2850 3150
CLARK 09-Jun-81 2450 2750
JONES 02-Apr-91 2975 3275
MARTIN 28-Sep-81 1250 1550
ALLEN 20-Feb-81 1600 1900

14 rows selected.
Operator Precedence

* / + -

• Multiplication and division take priority over


addition and subtraction.
• Operators of the same priority are evaluated
from left to right.
• Parentheses are used to force prioritized
evaluation and to clarity statements.
Operator Precedence

SQL> SELECT ename, sal, 12*sal+100


2 FROM emp;
ENAME SAL 12*SAL+100
KING 5000 60100
BLAKE 2850 34300
CLARK 2450 29500
JONES 2975 35800
MARTIN 1250 15100
ALLEN 1600 19300

14 rows selected.
Operator Precedence

SQL> SELECT ename, sal, 12*(sal+100)


2 FROM emp;
ENAME SAL 12*(SAL+100)
KING 5000 61200
BLAKE 2850 35400
CLARK 2450 30600
JONES 2975 36900
MARTIN 1250 16200
ALLEN 1600 20400

14 rows selected.
Defining a Null Value
• A Null is a value that is unavailable, unassigned,
unknown, or inapplicable.
• A Null is not the same as zero or a blank space.
SQL> SELECT ename, job, sal, comm
2 FROM emp;
ENAME JOB SAL COMM
KING PRESIDENT 5000
BLAKE MANAGER 2850
...
TURNER SALESMAN 1500 0

14 rows selected.
Null Values in Arithmetic Expressions

• Arithmetic expression containing a null value


evaluate to null.
SQL> SELECT ename, 12*sal + comm
2 FROM emp
3 WHERE ename=‘KING’;

ENAME 12*SAL+COMM
KING
Defining a Column Alias
• Renames a column heading.
• Is useful with calculations.
• Immediately follows column name; Optional AS
keyword between column name and alias.
• Requires double quotation marks if it contains
space or special characters or is case sensitive.
Using Column Aliases

SQL> SELECT ename AS name, sal salary


FROM emp;
NAME SALARY

SQL> SELECT ename “Name”,


sal*12 “Annual Salary”
FROM emp;
NAME Annual Salary

Concatenation Operator
• Concatenates columns or character string to other
columns.
• Is represented by two vertical bars.

• Creates a resultant column that is a character


expression.
Using the Concatenation Operator
SQL> SELECT ename || job AS “Employees”
FROM emp;
Employees

KINGPRESIDENT
BLAKEMANAGER
CLARKMANAGER
JONESMANAGER
MARTINSALESMAN
ALLENSALESMAN

14 rows selected.
Literal Character Strings
• A literal is a character, a number, or a date included
in the SELECT list.
• Date and Character literal values must be enclosed
within single quotation marks.
• Each character string is output once for each row
returned.
Using Literal Character Strings
SQL> SELECT ename || ‘is a ’ || job
AS “Employees Details”
FROM emp;
Employees Details

KING is a PRESIDENT
BLAKE is a MANAGER
CLARK is a MANAGER
JONES is a MANAGER
MARTIN
… is a SALESMAN
14 rows selected.
Duplicate Rows
The default display of queries is all rows, including
duplicate rows.
SQL> SELECT deptno
FROM dept;
DEPTNO

10
30
10
… 20
14 rows selected.
Eliminating Duplicate Rows
Eliminate duplicate rows by using the DISTINCT
keyword in the SELECT clause.
SQL> SELECT DISTINCT deptno
FROM dept;
DEPTNO

10
20
30
SQL and SQL Plus Interaction
SQL Statements SQL Statements
Buffer

Server
SQL*Plus a a a a a
a a a a a
a a a a a
a a a a a
a a a a a
a a a a a

a a a a a
a a a a a
a a a a a
SQL Statements a a a a a Query Results
a a a a a
a a a a a

Formatted Report
SQL and SQL*Plus

SQL is a command language for communication with Oracle


Server from any tool or application. Oracle SQL contains
many extensions. When you enter a SQL statement, it is
stored in a part of memory called the SQL buffer and
remains there until you enter a new statement.

SQL*Plus is an Oracle tool that recognizes and submit SQL


statements to the Oracle Server for execution and contains its
own command language.
SQL and SQL*Plus
SQL
• Can be used by a range of users, including those with little or no
programming experience.
• Is a nonprocedural language
• Reduces the amount of time required for creating and
manipulating systems.
• Is an English-like language
SQL*Plus
• Accepts Adhoc entry of statements and SQL input from files
• Provides a line editors for modifying SQL statements
• Controls environment settings, Format query results into a basic
report
SQL Statements Versus SQL*Plus Commands

SQL SQL*Plus
• A Language • An environment
• ANSI Standard • Oracle proprietary
• Keyboard cannot be abbreviated • Keyboards can be abbreviated
• Statements manipulated data and • Commands do not allow
table definitions in the database manipulation of values in the
database

SQL SQL SQL SQL


Statements Buffer Statements Buffer
Overview of SQL*Plus

• log into SQL*Plus


• Describe table structure
• Edit your SQL statement
• Execute SQL from SQL*Plus
• Save SQL statements to files and append SQL
statements to files
• Load commands from files to buffer to edit
Logging in to SQL*Plus
• From Windows environment

• From command line


sqlplus [username[/password[@database]]]
Displaying Table Structure
Use the SQL*Plus DESCRIBE command to display the
structure of a table

SQL> describe dept

Name Null? Type


DEPTNO NOT NULL NUMBER(2)
DNAME VARCHAR(14)
LOC VARCHAR(13)
SQL *PLUS Editing Commands
• A[PPEND] text
Adds text to the end of the current line
• C[HANGE] / old / new
Changes old text to new in the current line
• C[HANGE] / text
Deletes text from the current line
• CL[EAR] BUFF[ER]
Deletes all lines from SQL Buffer
• DEL
Delete current line
• DEL n
• DEL m n
SQL *PLUS Editing Commands
• I[NPUT]
Inserts an indefinite number of lines
• I[NPUT] text
Inserts a line consisting of text
• L[IST] / L[IST] n / L[IST] m n
List all / one (n) / range of lines (m to n)
• R[UN]
Display & runs the current SQL statement in buffer
•n Specifies the line to make the current line
• n text Replaces line n with text
• O text Inserts a line before line 1
SQL *PLUS File Commands

• SAVE filename.ext
• GET filename
• START filename.ext
• @ filename
• EDIT filename.ext
• SPOOL filename.ext
• EXIT
Practice 1
1. Initiate a SQL *Plus Session using the user ID and
password give to you.
2. Whether this SELECT statement will execute ?
Select ename, job, sal Salary from emp;
3. Whether this SELECT statement will execute ?
Select * from Salgrade;
4. Whether this SELECT statement will execute ?
Select empno, ename, salary x 12 Annual Sal
From emp;
5. Show the Structure of Dept table. Select all data from
the Dept table.
6. Show the Structure of Emp table. Display 4 columns.
Practice 1

7. Create a query to display Unique jobs from emp table.


8. Name the column heading as Emp#, Employees, job
and Hiredate.
9. Display the name concatenated with the job, separated
by a comma and space, and name this column as
Employee and Designation.
10. Create a query to display all the data from emp table.
Separate each column by a comma. Name the column
name as Final_Output.
7839, KING, PRESIDENT, , 17-NoV-81, 5000, ,10
7698, BLAKE, MANAGER, , 7839, 01-May-81, 2850, , 30

2. Restricting and Sorting Data
Limiting Rows Using a Selection
EMP …retrieves all
7839 ENAME JOB … DEPTNO employees in
7698 KING PRESIDENT 10 department 10”
7782 BLAKE MANAGER 30
7566 JONES MANAGER 10
... 20

EMP
EMPNO ENAME JOB MGR HIREDATE
7839 KING PRESIDENT 17-Nov-81
7782 CLARK MANAGER 7839 9-Jun-81
7934 MILLER CLERK 7782 23-Jan-82
Using the WHERE Clause
SQL> SELECT ename, job, deptno From Emp
WHERE job=‘CLERK’;

ENAME JOB DEPTNO

JAMES CLERK 30
SMITH CLERK 20
ADMAS CLERK 20
MILLER CLERK 10
Character Strings and Dates
• Character strings and date values are enclosed in
single quotation marks
• Character values are case-sensitive and date values
are format-sensitive
• Default date format is ‘DD-MON-YY’

SQL> SELECT ename, job, deptno


FROM emp
WHERE ename=‘JAMES’;

SQL> SELECT ename, empno, job, deptno


FROM emp
WHERE job=‘CLERK’;
Comparision Operators
Operator Meaning
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
<> Not equal to
… WHERE job=‘CLERK’
… WHERE ename=‘SMITH’
… WHERE sal>=1500
… WHERE hiredate = ’01-JAN-95’
… WHERE sal <= comm
Comparision Operators
Operator Meaning
BETWEEN Between two values
…AND…
IN(list) Match any of a list of values
LIKE Match a character pattern
IS NULL Is a null value

… WHERE sal BETWEEN 1000 and 2000


… WHERE mgr IN (7902, 7566, 7788)
… WHERE ename IN (‘FORD, ‘ALLEN’)
… WHERE mgr IS NULL
… WHERE ename LIKE ‘S%’
Using the LIKE Operator
• Use the LIKE operator to perform wildcard
searches of valid search string values
• Search conditions can contain either literal
characters or numbers…
• % denotes zero or many characters
• _ denotes one character

SQL> SELECT ename FROM emp


WHERE ename LIKE ‘S%’;

SQL> SELECT ename FROM emp


WHERE hiredate LIKE ‘%81’;
Using the LIKE Operator
• You can combine pattern matching characters.
SQL> SELECT ename FROM emp
WHERE ename LIKE ‘_A%’;
ENAME
JAMES
WARD

• You can use the ESCAPE identifier to search for


“%” or “_”.
SQL> SELECT ename FROM emp
ename LIKE ‘%A\_%B’ ESCAPE ‘\’;
Logical Operator

Operator Meaning
AND Returns TRUE if both component
conditions are TRUE
OR Returns TRUE if either component
conditions are TRUE
NOT Returns TRUE if the component
conditions are TRUE
Using the AND Operator
AND Operator both conditions to be TRUE

SQL> SELECT empno, ename, job, sal


FROM emp
WHERE sal>=1100
AND job=‘CLERK’;

EMPNO ENAME JOB SAL

7876 ADMAS CLERK 1100


7934 MILLER CLREK 1300
Using the OR Operator
OR requires either condition to be TRUE
SQL> SELECT empno, ename, job, sal
FROM emp
WHERE sal>=1100
OR job=‘CLERK’;
EMPNO ENAME JOB SAL

7839 KING PRESIDENT 5000


7698 BLAKE MANAGER 2850
7782 CLARK MANAGER 2450
7566 JONES MANAGER 2975

14 rows selected.
Using the NOT Operator
SQL> SELECT ename, job FROM emp
WHERE job NOT IN (‘CLERK’, ‘MANAGER’,’ANALYST’);

ENAME JOB

KING PRESIDENT
MARTIN SALESMAN
ALLEN SALESMAN
TURNER SALESMAN
WARD SALESMAN

… WHERE sal NOT in 1000 and 2000


… WHERE comm is NOT NULL
… WHERE ename NOT like ‘A%’
Rules of Precedence
Order Evaluated Operator
1 All Comparison Operators

2 NOT

3 AND

4 OR

Overrides rules of precedence by using


Parentheses.
Rules of Precedence

SQL> SELECT ename, job, sal FROM emp


WHERE job =’SALESMAN’
OR job =’PRESIDENT’
AND SAL > 1500;

ENAME JOB SAL

KING PRESIDENT 5000


MARTIN SALESMAN 1250
ALLEN SALESMAN 1600
TURNER SALESMAN 1500
WARD SALESMAN 1250
Rules of Precedence
Use parentheses to force priority

SQL> SELECT ename, job, sal FROM emp


WHERE ( job =’SALESMAN’
OR job =’PRESIDENT’)
AND SAL > 1500;

ENAME JOB SAL

KING PRESIDENT 5000


ALLEN SALESMAN 1600
ORDER BY Clause
• Sort rows with ORDER BY clause
• ASC : ascending order, default
• DESC : descending order
• The ORDER BY clause comes last in the SELECT statement.

SQL> SELECT ename, job, deptno, hiredate


FROM emp
ORDER BY hiredate;

ENAME JOB DEPT HIREDATE

SMITH CLERK 20 17-DEC-80


ALLEN SALESMAN 30 20-FEB-81

14 rows selected
SORTING in Descending Order
SQL> SELECT ename, job, deptno, hiredate
FROM emp
ORDER BY hiredate DESC;

ENAME JOB DEPT HIREDATE

ADAMS CLERK 20 12-JAN-83


SCOTT ANALYST 20 09-DEC-82
MILLER CLERK 10 23-JAN-82
JAMES CLERK 30 03-DEC-81
FORD ANALYST 20 03-DEC-81
KING PRESIDENT 10 17-NOV-81

14 rows selected
SORTING by Column Alias
SQL> SELECT empno, ename, sal*12 annsal
FROM emp
ORDER BY annsal;

EMPNO ENAME ANNSAL


7369 SMITH 9600
7900 JAMES 11400
7876 ADAMS 13200
7654 MARTIN 15000
7521 WARD 15000
7934 MILLER 15600
7844 TURNER 18000

14 rows selected
SORTING by Multiple Columns
• The order of ORDER BY list is the order of sort.

SQL> SELECT ename, dept, sal


FROM emp
ORDER BY deptno, sal DESC;

ENAME DEPTNO SAL


KING 10 5000
CLARK 10 2450
MILLER 10 1300
FORD 20 3000

14 rows selected
Insert Practice Session 2 from here
SQL Functions

Functions are very powerful feature of SQL and can be used


to do the followings :
• Perform calculations on data
• Modify individual data items
• Manipulate output for groups of rows
• Format dates and numbers for display
• Convert column datatypes
SQL functions accepts arguments and always return a value.
Two Types of SQL Functions
There are two distinct types of functions :
• Single-row functions
• Multi-row functions

Single-row Functions :
These functions operate on single rows only and return one
result per row. There are diff. types of single-row functions :
• Character
• Number
• Date
• Conversion
Two Types of SQL Functions (cont…)

Multi-Row Functions :
These functions manipulates groups of rows to give one
Result per group of rows.
Single-Row Functions
• Manipulate data items
• Accept arguments and return one value
• Act on each row returned
• Return one result per row
• May modify the datatypes
• Can be used in SELECT, WHERE, and ORDER BY
• Can be nested

function_name (column | expression, [arg1, arg2, …] )


Character Functions

Case Conversion Character Manipulation


Functions Functions

LOWER CONCAT
UPPER SUBSTR
INITCAP LENGTH
INSTR
LPAD
TRIM
Case Conversion Functions
Convert case for Character Strings
Function Result
Lower (‘SNTI Course’) Snti course
Upper (‘snti course’) SNTI COURSE
Initcap (‘SNTI course’) Snti Course

SQL> Select ‘The Designation of ’|| inticap (ename) ||


‘ is ’ || lower(job) as “EMPLOYEE DETAILS”
from emp;
Using Case Conversion Functions
Display the employee number, name and department
number for employee blake
SQL> Select empno, ename, deptno
from emp where ename=‘blake’;
no rows selected
SQL> Select empno, ename, deptno
from emp where ename=UPPER (‘blake’);
EMPNO ENAME DEPTNO
---------------------------------------------------------------- -------------------------------------------------- ----------------------------------------

7698 BLAKE 30
Character Manipulation Functions
Manipulate Character Strings
Function Result
Concat (‘World’ , ‘Cup’) World Cup
Substr (‘World Cup’,1,5) World
Length (‘World Cup’) 9
Instr (‘World Cup’, ‘r’) 3
LPAD (sal, 10, ‘*’ ) ******5000
TRIM(‘S’, ‘SSMITH’) MITH
Using Character Manipulation Functions
SQL> SELECT ename, CONCAT (ename, job),
LENGTH (ename), INSTR (ename, ‘A’)
FROM emp
WHERE SUBSTR(JOB,1,5)=‘SALES’;

Ename Concat(Ename, Job) Length(Ename) Instr(Ename,’A’)


------------------------------ ------------------------------------------------------------------------------- ----------------------------------------------------------- -----------------------------------------------------------------

MARTIN MARTINSALESMAN 6 2
ALLEN ALLENSALESMAN 5 1
TURNER TURNERSALESMAN 6 0
WARD WARDSALESMAN 4 2
Using Character Manipulation Functions
SQL> SELECT ename, CONCAT (ename, job),
LENGTH (ename), INSTR (ename, ‘A’)
FROM emp
WHERE SUBSTR(ENAME, -1, 1) = ‘N’;

Ename Concat(Ename, Job) Length(Ename) Instr(Ename,’A’)


------------------------------ ------------------------------------------------------------------------------- ----------------------------------------------------------- -----------------------------------------------------------------

MARTIN MARTINSALESMAN 6 2
ALLEN ALLENSALESMAN 5 1
Using Character Manipulation Functions
SQL> SELECT LPAD(DNAME,20,'*'), LPAD(DNAME,20),
LPAD(DEPTNO,20,'.')
FROM DEPT;

LPAD(DNAME,20,'*') LPAD(DNAME,20) LPAD(DEPTNO,20,'.')


--------------------------------- --------------------------- ---------------------------------
**********ACCOUNTING ACCOUNTING …………………..10

*************RESEARCH RESEARCH …………………..20

******************SALES SALES …………………..30

***********OPERATIONS OPERATIONS …………………...40


Using Character Manipulation Functions
SQL> SELECT RPAD(DNAME,20,'*'), RPAD(DNAME,20),
RPAD(DEPTNO,20,'.')
FROM DEPT;

RPAD(DNAME,20,'*') RPAD(DNAME,20) RPAD(DEPTNO,20,'.')


--------------------------------- --------------------------- ---------------------------------
ACCOUNTING********* ACCOUNTING 10 …………………..

RESEARCH************ RESEARCH 20 …………………..

SALES**************** SALES 30 …………………..

OPERATIONS********* OPERATIONS 40 …………………..


Using Character Manipulation Functions
LTRIM : It removes a char or combination of leading chars from
the beginning/left leading occurrences of specified column value. If
char is not specified, it will trim any blanks from the left side.

SQL> SELECT DNAME, LTRIM(DNAME, 'A'),


LTRIM(DNAME, 'SA')
FROM DEPT;

DNAME LTRIM(DNAME,‘A') LTRIM(DNAME,’AS’)


--------------------------- ------------------------------- -----------------------------------
ACCOUNTING CCOUNTING CCOUNTING
RESEARCH RESEARCH RESEARCH
SALES SALES LES
OPERATIONS OPERATIONS OPERATIONS
Using Character Manipulation Functions
RTRIM : It removes a char or combination of trailing chars from
the end/right side occurrences of specified column value. If char is
not specified, it will trim any blanks from the right side.

SQL> SELECT DNAME, RTRIM(DNAME, ‘G'),


LTRIM(DNAME, ‘GHS')
FROM DEPT;

DNAME LTRIM(DNAME,‘G') LTRIM(DNAME,’GHS’)


--------------------------- ------------------------------- -----------------------------------
ACCOUNTING ACCOUNTIN ACCOUNTIN
RESEARCH RESEARCH RESEARC
SALES SALES SALE
OPERATIONS OPERATIONS OPERATION
Using Character Manipulation Functions
TRANSLATE : This function is used for character substitution.

SQL> SELECT ENAME,TRANSLATE(ENAME,'C','P'),


JOB,TRANSLATE(JOB,'AR','IT')
FROM EMP WHERE DEPTNO = 20;

ENAME TRANSLATE(ENAME,'C', JOB TRANSLATE(JOB,'


------------ --------------------------------- ------------------- -----------------------
JONES JONES MANAGER MINIGET
FORD FORD ANALYST INILYST
SMITH SMITH CLERK CLETK
SCOTT SPOTT ANALYST INILYST
ADAMS ADAMS CLERK CLETK
Using Character Manipulation Functions
REPLACE : This function is used for character substitution.
SQL> SELECT JOB,
REPLACE(JOB, 'SALESMAN', 'SALESPERSON')
FROM EMP;
JOB REPLACE(JOB,'SALESMAN','SALESPERSON')
--------------- ------------------------------------------------------------------------
PRESIDENT PRESIDENT
MANAGER MANAGER
MANAGER MANAGER
SALESMAN SALESPERSON
SALESMAN SALESPERSON
SALESMAN SALESPERSON
CLERK CLERK
SALESMAN SALESPERSON
Using Number Functions
Number functions accept numeric input and return
numeric values. Oracle functions deal with three classes of
numbers : single values, group of values, and list of
values.
Oracle single-value functions usually change these values
through a calculation. A group of values is all the numbers
in one column from a series of rows. A list of values is a
series of numbers.

Single-values Functions
Using Number Functions
Round(Single-values Function) : It rounds the column, expression
or value to n decimal places or if n is omitted, no decimal places (if
n is negative, numbers to the left to the decimal point are rounded.

SQL> SELECT ROUND(45.923,1),ROUND(45.923), ROUND(45.323,1),


ROUND(42.323,-1), ROUND(SAL/32,2)
FROM EMP
WHERE DEPTNO = 10;

ROUND(45.923,1) ROUND(45.923) ROUND(45.323,1) ROUND(42.323,-1) ROUND(SAL/32,2)


--------------- -------------- --------------- ---------------- -----------------
45.9 46 45.3 40 156.25
45.9 46 45.3 40 76.56
45.9 46 45.3 40 40.63
Using Number Functions
Trunc(Single-values Function) : It truncates the column/expression/
value to n decimal places or if n is omitted, no decimal places (if n is
-ve, numbers to the left to the decimal point are truncated to zero.)

SQL> SELECT TRUNC(45.923,1), TRUNC(45.923),


TRUNC(45.323,1),TRUNC(47.323,-1)
FROM EMP
WHERE DEPTNO = 10

TRUNC(45.923,1) TRUNC(45.923) TRUNC(45.323,1) TRUNC(47.323,-1)


------------------------ ---------------------- -----------------------
------------------------
45.9 45 45.3 40
45.9 45 45.3 40
45.9 45 45.3 40
Using Number Functions
CEIL : It round up the column, expression or value to the next
higher value (irrespective of the decimal value).
SQL> SELECT CEIL(SAL), CEIL(79.2), CEIL(104.55),
CEIL(-11.1) FROM EMP
WHERE SAL BETWEEN 2000 AND 3500;
CEIL(SAL) CEIL(79.2) CEIL(104.55) CEIL(-15.1)
------------------- ------------------- ---------------------- ---------------------
2850 80 105 -15
2450 80 105 -15
2975 80 105 -15
3000 80 105 -15
3500 80 105 -15
Using Number Functions
FLOOR : It round down the column, expression or value to the
next lower value (irrespective of the decimal value).
SQL> SELECT FLOOR(SAL),FLOOR(79.2), FLOOR(104.55),
FLOOR(-15.1) FROM EMP
WHERE SAL BETWEEN 2000 AND 3500
FLOOR(SAL) FLOOR(79.2) FLOOR(104.55) FLOOR(-15.1)
----------------------- ---------------------- -------------------------
-----------------------
2850 79 104 -16
2450 79 104 -16
2975 79 104 -16
3000 79 104 -16
3500 79 104 -16
Using Number Functions
POWER : It raises the column/value to the nth power. It
can also be a negative value.

SQL> SELECT SAL, POWER(SAL,2), POWER(SAL,3),


POWER(20,5) FROM EMP
WHERE DEPTNO =10;

SAL POWER(SAL,2) POWER(SAL,3) POWER(20,5)


------------- --------------------------- ----------------------------
-------------------------
5000 25000000 1.2500E+11 3200000
2450 6002500 1.4706E+10 3200000
1300 1690000 2197000000 3200000
Using Number Functions
SQRT : It finds the square root of the column/value.

SQL> SELECT SAL, SQRT(SAL), SQRT(64), SQRT(COMM)


FROM EMP
WHERE COMM > 0;

SAL SQRT(SAL) SQRT(64) SQRT(COMM)


------------- --------------------------- ----------------------------
-------------------------
1250 35.3553391 8 37.4165739
1600 40 8 17.3205081
1250 35.3553391 8 22.3606798
Using Number Functions
SIGN : It returns -1, if a column/or value is a negative
number, returns 0, if its is zero and +1, if positive.
SQL> SELECT SAL-COMM, SIGN(SAL-COMM),
COMM-SAL, SIGN(COMM-SAL)
FROM EMP WHERE DEPTNO = 30;
SAL-COMM SIGN(SAL-COMM) COMM-SAL SIGN(COMM-SAL)
------------------- ----------------------------- --------------------
----------------------------
-150 -1 150 1
1300 1 -1300 -1
1500 1 -1500 -1
750 1 -750 -1
Using Number Functions
ABS : It returns the absolute value of the number. Absolute
value is always positive value.
SQL> SELECT SAL,COMM,COMM-SAL,
ABS(COMM-SAL), ABS(-75)
FROM EMP WHERE DEPTNO = 30;
SAL COMM COMM-SAL ABS(COMM-SAL) ABS(-75)
------------- --------------- ------------------- ---------------------------
----------------
2850 75
1250 1400 150 150 75
1600 300 -1300 1300 75
1500 0 -1500 1500 75

Using Number Functions
Mod : It returns the remainder of value1 divided by value2.
The value of mod is zero if divisor is zero or negative.
SQL> SELECT SAL, COMM, MOD(SAL,COMM),
MOD(150,20) FROM EMP
WHERE DEPTNO = 30 ORDER BY COMM;
SAL COMM MOD(SAL,COMM) MOD(150,20)
--------------- ------------------- ----------------------------- ----------------------
1500 0 1500 10
1600 300 100 10
1250 500 250 10
1250 1400 1250 10

Some Other Mathematical Functions are :
LOG(m,n) Returns logarithm base m, of n.
SIN(n) Returns the sine of n.
SINH(n) Returns the hyperbolic sine of n.
TAN(n) Returns the tangent of n.
TANH(n) Returns hyperbolic tangent of n.
COS(n) Returns cosine of n.
COSH(n) Returns hyperbolic cosine of n.
e.g.
SQL> SELECT LOG(10,10) FROM DUAL;

LOG(10,10)
-----------------
1
Working with Dates
• Oracle stores dates in an internal numeric format :
century, year, month, day, hours, minutes, seconds.
• The default date format is DD-MON-YY.
• SYSDATE is a function returning date and time.
• DUAL is a dummy table used to view SYSDATE.
The DUAL table is owned by the user SYS and can be accessed by all
users. It contains one column, DUMMY, and one row with value X. The
DUAL table is useful when you want to return a value one only – for
instance, the value of a constant, pseuudocolumn, or expression that is not
derived from a table with user data. The DUAL table generally used for
SELECT clause syntax completeness, because both SELECT and FROM
clause are mandatory, several calculations do not need to select from
actual tables.
Working with Dates
SQL> SELECT SYSDATE FROM DUAL;

SYSDATE
----------------------
19-JUL-04

Using Arithmetic Operators


The operations are :
date + number adds a no. of days to a date giving new date.
date - number subtracts a number of days from a date.
date1 – date2 subtracts date1 from date2 giving No. of days.
date + number/24 adds a number of hours to a date giving a date.
Working with Dates

SQL> SELECT ENAME, (SYSDATE-hiredate)/7 WEEKS


FROM emp
WHERE deptno =10;

ENAME WEEKS
---------------------- ---------------------------
KING 830.93709
CLARK 853.93709
MILLER 821.36566
Working with Dates
Function Description
MONTHS_BETWEEN No. of months between two
date
ADD_MONTHS Add calendar month to date
NEXT_DAY Next day of date specified
LAST_DAY No. of months between two
ROUND Round date
TRUNC Truncate date
Working with Dates

SQL> SELECT ENAME, (SYSDATE-hiredate)/7 WEEKS


FROM emp
WHERE deptno =10;

ENAME WEEKS
---------------------- ---------------------------
KING 830.93709
CLARK 853.93709
MILLER 821.36566

You might also like