0% found this document useful (0 votes)
40 views106 pages

SQL1

This document discusses retrieving data from Oracle databases using the SQL SELECT statement. It describes the basic SELECT statement syntax and clauses, how to select specific columns or all columns, arithmetic expressions in the SELECT statement, implications of NULL values, using column aliases, concatenation operators, literal strings, alternative quote operators, the DISTINCT keyword, and selecting from the DUAL table. The goal is to understand how to retrieve customized data using the SELECT statement.

Uploaded by

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

SQL1

This document discusses retrieving data from Oracle databases using the SQL SELECT statement. It describes the basic SELECT statement syntax and clauses, how to select specific columns or all columns, arithmetic expressions in the SELECT statement, implications of NULL values, using column aliases, concatenation operators, literal strings, alternative quote operators, the DISTINCT keyword, and selecting from the DUAL table. The goal is to understand how to retrieve customized data using the SELECT statement.

Uploaded by

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

DBMS Using

Oracle-Day-2
DBMS USING ORACLE

OBJECTIVES
DBMS using oracle
DBMS USING ORACLE > OBJECTIVES

At the end of this Lecture, you will be able to

Describe how to retrieve data using the SQL SELECT statement


Explain how to restrict and sort data
Understand how to use single row functions to customize the output
Understand conversion functions and conditional expressions on the retrieved
data
DBMS USING ORACLE

CONCEPT
Retrieving Data Using
the SQL SELECT
Statement
DBMS USING ORACLE > RESTRICTING AND SORTING DATA

Topics covered:
Basic SELECT statement
Arithmetic expressions and NULL values in the SELECT statement
Column aliases
Use of concatenation operator, literal character strings, alternative quote operator,
and the DISTINCT keyword
DESCRIBE command
DUAL table
DBMS USING ORACLE > RETRIEVING DATA USING THE SQL SELECT
STATEMENT

SELECT statement retrieves the data stored in relational tables


SELECT statement never modifies or alters the data in the database, but provides a
read-only method of extracting information.
DBMS USING ORACLE > TYPES OF SELECT STATEMENTS

Projection – restricts the number of columns retrieved from the table


Selection – restricts the number of rows/tuples retrieved from the table
Join – obtains data from multiple tables by specifying the relationship
between them
DBMS USING ORACLE > BASIC SELECT STATEMENT

In its simplest form a SELECT statement should have


A SELECT clause, which specifies the columns to be projected
A FROM clause, which specifies the table/tables from which the data is to be
retrieved

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


FROM table;
DBMS USING ORACLE > SELECTING ALL COLUMNS

All the columns of a table can be projected in the select statement by


specifying their respective column names
In the below query all the columns of the departments table are projected

SELECT department_id, department_name, manager_name, location_id


FROM departments;

Alternatively use an asterisk (*) to project all the columns from a table

SELECT *
FROM departments;
DBMS USING ORACLE > SELECTING SPECIFIC COLUMNS

If the data is to be obtained from specific columns, specify the names of the
columns separated by commas in the select statement
The below query only projects the department_id and location_id columns of the
departments table

SELECT department_id, location_id


FROM departments;
DBMS USING ORACLE > GUIDELINES FOR SQL STATEMENTS

SQL statements can be entered on one or more lines.


SQL statements are not case sensitive.
Keywords cannot be abbreviated or split across lines.
Clauses(like SELECT, FROM,WHERE etc.) are usually placed on separate
lines.
Indents are used to enhance readability.
Semicolons are required to execute multiple SQL statements.
In SQL Developer, SQL statements can be optionally terminated by a semicolon (;).
In SQL*Plus, each SQL statement end with a semicolon(;).
DBMS USING ORACLE > ARITHMETIC EXPRESSION IN SELECT

Calculations like – addition(+), subtraction(-), multiplication( *) and division ( / ) can


be performed on the data retrieved from the tables
This allows modifications on the retrieved data
Arithmetic operators can be used in any clause of the SQL statement, except the
FROM clause
For example:

SELECT last_name, salary, salary + 300


FROM employees;

The select statement retrieves the last name, salary of all the employees along with
an additional column of salary + 300
The column salary+300 is a computed column
DBMS USING ORACLE > ARITHMETIC EXPRESSION IN SELECT– OPERATOR
PRECEDENCE

To obtain the employee first name and the annual compensation of employees
Annual compensation of salary is obtained by multiplying the salaries of each
employee by 12 and providing a one time bonus of $500

SELECT first_name,salary*12+ 500


FROM employees;

Here multiplication has a higher precedence than addition and hence salary of
every employee is multiplied by 12 and then 500 is added.
DBMS USING ORACLE > ARITHMETIC EXPRESSION IN SELECT– OPERATOR
PRECEDENCE

How to obtain the employee first name, last name and the annual compensation of
employees, by providing a monthly bonus of $100 ?

SELECT first_name, last_name, (salary+100)*12


FROM employees;

General precedence rules can be overridden by using parenthesis


Here the monthly salary of every employee is added with 100 and the resultant is
multiplied by 12 to get the annual compensation
DBMS USING ORACLE > IMPLICATIONS OF NULL IN SELECT

If a row or a tuple does not have a value its said to be


NULL
NULL indicates that the value is:
Unavailable
Unassigned
Unknown
Not known
NULL cannot be considered as zero or a blank space
The COMMISSION_PCT column of the EMPLOYEES
table has NULL values since only a sales manager
and sales representative can earn a commission.
Other employees are not entitled to earn
commissions and are represented by NULL.
DBMS USING ORACLE > IMPLICATIONS OF NULL IN SELECT

If any column in the arithmetic expression is NULL then the resultant value is
NULL
Adding or subtracting a value with NULL, would result in a NULL value
NULL cannot be considered as zero or a blank space
The below query would result in NULL values for employees who do not earn
commission

SELECT last_name, 12*salary*commission_pct


FROM employees;
DBMS USING ORACLE > COLUMN ALIASES

When displaying the result of a query, SQL uses the name of the selected column
as the column heading
The entire computation “(commission_pct*salary)+100” would be displayed as
column header, which is not descriptive

Hence a column alias is used to rename a column header to provide meaningful


names to columns.
DBMS USING ORACLE > COLUMN ALIASES

Column Aliases:
Are useful with computed columns
Immediately follows the column name (There can also be the optional AS keyword
between the column name and the alias.)
Requires double quotation marks if it contains spaces or special characters, or if it
is case-sensitive
In the below example “AS” keyword is used before the alias name
SELECT last_name AS name, job_id AS JOB,(commission_pct*salary)+100 AS
comm
FROM employees;

In the below example the alias name contains space and hence its enclosed in
double
SELECT last_name Name , salary*12 "Annual Salary"
FROM employees;
DBMS USING ORACLE > CONCATENATION OPERATOR

A concatenation operator is
Useful to link columns or character strings to other columns
Columns on the either side of the operator are combined to make a single
column
Is represented by two vertical bars(||)

SELECT last_name||job_id AS "Employees"


FROM employees;
DBMS USING ORACLE > SPECIFYING LITERAL CHARACTER STRINGS

A literal is a character, number or a date values.


Select statement can include literal values along with data retrieved.
Date and character literal values must be enclosed within single quotes.
The literal value is output for each row returned.
In the below query the last name and job_id of employees are concatenated with
the string literal ‘ is a ’

SELECT last_name ||' is a '||job_id


AS "Employee Details"
FROM employees;

The space between the single quotation mark is


introduced to improve readability in the output
DBMS USING ORACLE > ALTERNATIVE OUATE OPERATOR

SQL statements can use character literals in expressions or conditions.


If the literal itself contains a single quotation mark, use the quote (q) operator to
choose any alternate quotation mark.
In the below query the string(department’s) contains a single quotation mark,
which is normally interpreted as a delimiter of a character string.
By using the q operator, square brackets[ ] are used as the quotation mark
delimiters.
The string between the square brackets delimiters is interpreted as a literal
character string.
SELECT department_name || q'[ Department's Manager Id:
]'
|| manager_id
AS "Department and Manager"
FROM departments;
DBMS USING ORACLE > ELIMINATING DUPLICATE ROWS

By Default, SELECT displays all the rows in the table inclusive of duplicate rows
Below query projects the department_id column of the employees table, which
contain duplicate values
To eliminate duplicate rows in the result, include the DISTINCT keyword in the
SELECT clause immediately after the SELECT keyword
DBMS USING ORACLE > DESCRIBE COMMAND

Describe command on a table displays :


Names of the columns in the table
Whether a column is NOT NULL
Datatype of the column
DESCRIBE employees
DBMS USING ORACLE > SELECTING DATA FROM DUAL

Every schema has access to a special table called DUAL which is owned by
SYS and is accessed by all users
It contains one column, DUMMY, and one row with the value X. The DUAL
table is useful to return a value of a computation only once
The DUAL table is generally used for completeness of the SELECT clause
syntax, because both SELECT and FROM clauses are mandatory, and several
calculations do not need to select from the actual tables

DESCRIBE dual

select 10+12 as"Ten plus 12"


from dual;
DBMS USING ORACLE > RETRIEVING DATA USING THE SQL SELECT STATEMENT –
GUIDED ACTIVITY

GUIDED ACTIVITY
DBMS USING ORACLE > RETRIEVING DATA USING THE SQL SELECT STATEMENT –
GUIDED ACTIVITY

How many unique departments have employees working in them

For employees who quit the organization, find out how many years the employees
were employed. Assume that the year consists of 365.25 days. Also retrieve the
EMPLOYEE_ID, JOB_ID, START_DATE, and END_DATE for these employees

Query the JOBS table and return a single expression of the form The Job Id for
the <job_title’s> job is: <job_id>. Take note that the job_title should have an
apostrophe and an “s” appended to it to read more naturally. A sample of this
output for the organization president is: “The Job Id for the President’s job is:
AD_PRES.” Alias this column expression as “Job Description” using the AS
keyword.
DBMS USING ORACLE

CONCEPT
Restricting and Sorting
Data
DBMS USING ORACLE > RESTRICTING AND SORTING DATA

Topics covered:
Restricting the retrieved data with:
The WHERE clause
The comparison operators using =, <=, BETWEEN, IN, LIKE, and NULL
conditions
Logical conditions using AND, OR, and NOT operators
Rules of precedence for operators in an expression
Sorting rows using the ORDER BY clause
Substitution variables
DEFINE and VERIFY commands
DBMS USING ORACLE > RESTRICTING THE RETRIVED DATA

Suppose we want to display the employee_id, last_name, job_id and


department_id of all employees in department 90
To achieve this we will have to:
Project the columns : employee_id, last_name, job_id and department_id from the
employees table
Restrict those rows which has department_id = 90
“retrieve all
EMPLOYEES employees in
department 90”


DBMS USING ORACLE > WHERE CLAUSE

Rows returned from SELECT can be restricted using a WHERE clause which
follows the FROM clause
The WHERE clause contains a condition that must be satisfied(evaluated to true)
to restrict the rows
SELECT *|{[DISTINCT] column|expression
[alias],...}
FROM table
[WHERE logical expression(s)];

The Below query displays the employee_id, last_name, job_id and department_id
of all employees in department 90
SELECT employee_id, last_name, job_id, department_id
FROM employees
WHERE department_id = 90 ;
DBMS USING ORACLE > WHERE CLAUSE
Operators used in WHERE
The where clause specifies the condition which needs clause
to be evaluated.
Operator Meaning
The condition in the WHERE clause is of the form : = Equal to
> Greater than
expr operator value
>= Greater than or equal to
expr is column name or a combination of < Less than
columns <= Less than or equal to
<> Not equal to
Operator is a conditional operator BETWEEN Between two values
Value is a numeric, character or Date literal ...AND... (inclusive)
IN(set) Match any of a list of values
A column alias cannot be used in the where clause as LIKE Match a character pattern
an expression IS NULL Is a null value
Example:
... WHERE hire_date = '01-JAN-2015‘
... WHERE salary >= 6200
DBMS USING ORACLE > WHERE CLAUSE

Character or Date literal values in the condition of a WHERE clause, must be enclosed in
single quotation marks
Number constants, need not be enclosed with single quotation marks
Character values are case-sensitive and date values are format-sensitive
The default date display format is DD-MON-RR

SELECT last_name, job_id, department_id


FROM employees
WHERE last_name = 'Whalen' ;

SELECT last_name
FROM employees
WHERE hire_date = '17-FEB-96' ;
DBMS USING ORACLE > WHERE CLAUSE – LOGICAL OPERATORS

Multiple conditions can be specified in the WHERE clause to restrict the rows
of the select statement.
A logical operator is used combine the results of one or more conditions in the
WHERE clause.
A row is returned only if the overall result of the condition is true.
Below table lists the logical operator and its significance
Operator Meaning
AND Returns TRUE if both component conditions
are true
OR Returns TRUE if either component condition
is true
NOT Returns TRUE if the condition is false
DBMS USING ORACLE > WHERE CLAUSE – LOGICAL OPERATORS

Query : Retrieve last name and salary of all employees having salary greater than
50,000,working in department 90.
To retrieve the requested data:
Project the columns last_name and salary
restrict the data using the conditions : salary > 50,000 AND department_id = 90

SELECT last_name, salary


FROM employees
WHERE salary > 50000
AND
Department_id = 90;

AND requires both the component conditions to


be true
DBMS USING ORACLE > WHERE CLAUSE – LOGICAL OPERATORS

Query : Retrieve last name and salary of all employees having salary less than 50,000 or
joined after “01-JAN-2008”
To retrieve the requested data:
Project the columns last_name and salary
restrict the data using the conditions: salary < 50,000 OR hire_date > ‘01-JAN-2008’

SELECT last_name, salary


FROM employees
WHERE salary < 50000
OR
Hire_date > ‘01-JAN-2008’;

OR requires one of the component conditions to be true for the data to


be selected
DBMS USING ORACLE > WHERE CLAUSE – LOGICAL OPERATORS
Query : Retrieve last name and salary of all employees who does not belong to
department 30
To retrieve the requested data:
Project the columns last_name and salary
restrict the data using the condition: NOT department_id = 30

SELECT last_name, salary


FROM employees
WHERE NOT department_id = 30;

NOT negates the condition


DBMS USING ORACLE > WHERE CLAUSE – BETWEEN OPERATOR

Rows can be retrieved based on a range of values. The range specifies the upper limit
and the lower limit.
Below query displays the last name and salary of all employees whose salary is greater
than or equal to 10,000 and less than or equal to 25,000
SELECT last_name, salary
FROM employees
WHERE salary >= 10000 AND
salary <= 25000;

Alternatively, the above can be achieved by using the BETWEEN operator

SELECT last_name, salary


FROM employees
WHERE salary BETWEEN 10000 AND 25000 ;
DBMS USING ORACLE > WHERE CLAUSE – BETWEEN OPERATOR

To retrieve salaries and last name of employees who has salaries not in the range
10,000 and 25,000,
Use NOT operator along with between

SELECT last_name, salary


FROM employees
WHERE salary NOT BETWEEN 10000 AND 25000 ;
DBMS USING ORACLE > WHERE CLAUSE – IN OPERATOR

To test for values in a specified set of values, IN operator is used in the WHERE clause
which tests the membership condition.
Below query retrieves last name, salary and manager_id of employees whose
manager_id is 100,101 or 201.

SELECT last_name, salary, manager_id


FROM employees
WHERE manager_id IN (100,101,201);

The above query can be achieved using a combination of OR conditions


SELECT last_name, salary, manager_id
FROM employees
WHERE manager_id = 100 OR manager_id = 101
OR manager_id = 201;

The set of values to the IN operator can be specified in any order


DBMS USING ORACLE > WHERE CLAUSE – LIKE OPERATOR
The exact value to be searched(to restrict the rows) might not be known while
executing the query.
Rows can be selected that match a character pattern by using the LIKE operator.in
the WHERE clause.
These patterns are denoted by :
% denotes zero or many characters
_ denotes one character
SELECT first_name, last_name, employees whose
FROM employees first name starts
WHERE first_name LIKE ‘S%’;
with “S”

SELECT first_name, last_name,


Employees whose last
FROM employees name has a letter “O” as
WHERE last_name LIKE ‘_O%’; the second character
DBMS USING ORACLE > WHERE CLAUSE – IS NULL

Conditional operators cannot be used to check for NULL values


IS NULL operator is used to check for the presence NULL values
Below query retrieves all employees who does not have a manager

SELECT first_name, last_name,


FROM employees
WHERE manager_id IS NULL;

IS NOT operator is used to check for the absence of NULL values


Below query retrieves all employees whose receives commission

SELECT first_name, last_name,


FROM employees
WHERE COMMISSION_PCT IS NOT NULL;
DBMS USING ORACLE > WHERE CLAUSE – OPERATOR PRECEDENCE

Rules of precedence determine the order in which the expressions are evaluated.
Use of parenthesis around the expressions would override the default precedence

Operator Meaning
1 Arithmetic operators
2 Concatenation operator
3 Comparison conditions
4 IS [NOT] NULL, LIKE, [NOT] IN
5 [NOT] BETWEEN
6 Not equal to
7 NOT logical condition
8 AND logical condition

9 OR logical condition
DBMS USING ORACLE > WHERE CLAUSE – OPERATOR PRECEDENCE

SELECT last_name, job_id, salary


FROM employees
WHERE job_id = 'SA_REP'
OR job_id = 'AD_PRES'
AND salary > 15000;

SELECT last_name, job_id, salary


FROM employees
WHERE (job_id = 'SA_REP'
OR job_id = 'AD_PRES')
AND salary > 15000;
DBMS USING ORACLE > ORDER BY CLAUSE

By default, the order of rows returned in a query result is undefined.


Sort the retrieved rows using the ORDER BY clause: ASC: Ascending order
The ORDER BY is the last clause in the SELECT statement
Columns not in the SELECT list can also be sorted
Below query sorts the data retrieved based in the increasing order of hire date:
SELECT last_name, job_id, department_id, hire_date
FROM employees
ORDER BY hire_date ;


DBMS USING ORACLE > ORDER BY CLAUSE

By default :
Numeric values are sorted with the lowest values first (for example, 1 to 999).
Date values are sorted with the earliest value first (for example, 01-JAN-92 before
01-JAN-95).
Character values are sorted in the alphabetical order (for example, “A” first and “Z”
last).
Null values are displayed last for ascending sequences and first for descending
sequences
SELECT last_name, job_id, department_id, hire_date
sorts the data
FROM employees
in DESC order
ORDER BY hire_date DESC ;

SELECT employee_id, last_name, salary*12 annsal sorts the data


FROM employees on column alias
ORDER BY annsal ;
DBMS USING ORACLE > ORDER BY CLAUSE

Below query sorts the data based on the numeric position of a column/column alias
in the SELECT clause

SELECT last_name, job_id, department_id, hire_date


FROM employees
ORDER BY 3;

Below query sorts the data by department_id is ascending order and the data within
each department_id is sort in the descending order of the salary

SELECT last_name, department_id, salary


FROM employees
ORDER BY department_id, salary DESC;
DBMS USING ORACLE > SUBSTITUTION VARIABLES

SQL statements are usually executed with predetermined values for columns and
conditions in the WHERE clause.
This default behavior can be changed by using substitution variables, which
prompts for user input at run-time. This allows to execute the same query with
different values
A substitution variable can be thought of as a container in which values are
temporarily stored. When the statement is run, the stored value is substituted.
& and && operator are used as substitution variables.
Substitution variable can be used anywhere in the SELECT statement, except the
SELECT keyword itself.
DBMS USING ORACLE > SUBSTITUTION VARIABLES

In the below query a variable named – employee_num is prefixed with an ampersand


(&) to prompt the user enter a value
The value enter by the user is stored in the variable employee_num which gets
substituted

SELECT employee_id, last_name, salary, department_id


FROM employees
WHERE employee_id = &employee_num ;

Use Single quotation marks while substituting the Date and character values

SELECT last_name, department_id, salary*12


FROM employees
WHERE job_id = '&job_title' ;
DBMS USING ORACLE > SUBSTITUTION VARIABLES
Substitution variables are used in:
WHERE conditions
ORDER BY clauses and Column expressions
Table names in the FROM clause
Columns in the SELECT clause
The below query:
Projects the employee_id, last_name, job_title and any column that the user specifies
at runtime from the employees table
Restricts the data based on the condition specified by the user at run time
Sorts the data based on the column name specified by the user at run time

SELECT employee_id, last_name, job_id,&column_name


FROM employees
WHERE &condition
ORDER BY &order_column ;
DBMS USING ORACLE > SUBSTITUTION VARIABLES

Double ampersand (&&) can be used to reuse the substitution variable value
without prompting the value from the user each time
During the execution of the below query the user will be prompted only once in the
current session, to enter the value of the variable – column_name, which is
substituted with a column name from the employees table for projecting and
sorting the data

SELECT employee_id, last_name, job_id, &&column_name


FROM employees
ORDER BY &column_name ;

Subsequent substitutions using column_name in the current session would not


prompt the value from the user
DBMS USING ORACLE > DEFINE COMMAND

Alternatively, Substitution variables can be created using the DEFINE command


DEFINE employee_num = 200
User would not be prompted to enter a value for employee number and the defined
variable would be substituted automatically.
The value is defined for the current session and can be reused in any query which
requires the substitution of employee number

SELECT employee_id, last_name, salary, department_id


FROM employees
WHERE employee_id = &employee_num ;

Use the UNDEFINE command to remove a variable.


UNDEFINE employee_num
DBMS USING ORACLE > VERIFY COMMAND

Use the VERIFY command to toggle the display of the substitution variable
both before and after, oracle replaces substitution variables with values:

SET VERIFY ON
SELECT employee_id, last_name, salary
FROM employees
WHERE employee_id = &employee_num;
DBMS USING ORACLE

GUIDED ACTIVITY
DBMS USING ORACLE > RESTRICTING AND SORTING DATA – GUIDED ACTIVITY

Retrieve a list of department names that end with the three letters “ing” and
second character is “a” from the DEPARTMENTS table

Write a query that extracts the JOB_TITLE, MIN_SALARY, and MAX_SALARY


columns, as well as an expression called VARIANCE, which is the difference
between the MAX_SALARY and MIN_SALARY values, for each row. The result
should include only JOB_TITLE values that contain either the word “President” or
“Manager.” Sort the list in descending order based on the VARIANCE expression.
If more than one row has the same VARIANCE value, then, sort these rows by
JOB_TITLE in reverse alphabetic order.
DBMS USING ORACLE > RESTRICTING AND SORTING DATA – GUIDED ACTIVITY

A common computation performed by the Finance department relates to the


calculation of taxes levied upon an employee. The tax deducted per employee is
calculated by obtaining the annual salary for the employee and the current tax
rate, which may vary from year to year as per the regulations laid from the
ministry of finance. Write a reusable query for the current tax rate and for an
employee_id as input, return the EMPLOYEE_ID, FIRST_NAME, SALARY,
ANNUAL SALARY,TAX_RATE, and the TAX AMOUNT.
DBMS USING ORACLE

CONCEPT
Using Single row
functions to customize
the output
DBMS USING ORACLE > USING SINGLE ROW FUNCTIONS TO CUSTOMIZE THE OUTPUT

Topics covered:
Single-row SQL functions
Character functions
Numeric functions
Working with dates
Date functions
DBMS USING ORACLE > FUNCTIONS IN SQL

SQL
Functions
Takes one or more arguments and
returns a value

Single Row Multiple Row


Functions functions
Returns one result per set of
Returns one result per row Rows
DBMS USING ORACLE > TYPES OF SINGLE ROW FUNCTIONS

Character functions - Accept character input and return

Single Row Functions


both character and number values

Numeric functions - Accept numeric input and return


numeric values

Date functions - Operate on values of the DATE data type

Conversion functions – Convert a value from one data type to


another

General functions – Operate on NULL values


DBMS USING ORACLE > TYPES OF CHARACTER FUNCTIONS

Character
functions

Case Character
conversion Manipulation
functions functions
▪ LOWER • CONCAT
▪ UPPER • SUBSTR
▪ INITCAP • LENGTH
• INSTR
• LPAD
• RPAD
• TRIM
• REPLACE
DBMS USING ORACLE > CASE CONVERSION FUNCTIONS

Function Result Explanation


LOWER(‘SQL DbCourse’) Sql db course Converts mixed-case or uppercase character strings to lowercase

UPPER(‘SQL DbCourse’) SQL DB Converts mixed-case or lowercase character strings to uppercase


COURSE
INITCAP(‘SQL DbCourse’) Sql Db Course Converts the first letter of each word to uppercase and the remaining
letters to lowercase

SELECT employee_id, last_name, department_id


FROM employees
WHERE last_name = 'higgins';

SELECT employee_id, last_name, department_id


FROM employees
WHERE LOWER(last_name) = 'higgins';
DBMS USING ORACLE > CHARACTER MANIPULATION FUNCTIONS

Function Result Explanation


CONCAT('Hello', 'World') HelloWorld Joins values together (only use two parameters
with CONCAT.)
SUBSTR('HelloWorld',1,5) Hello Extracts a string of determined length
LENGTH('HelloWorld') 10 Shows the length of a string as a numeric value

INSTR('HelloWorld', 'W') 6 Finds the numeric position of a named character

LPAD(salary,10,'*') *****24000 Returns an expression left-padded to the length of


n characters with a character expression

RPAD(salary, 10, '*') 24000***** Returns an expression right-padded to the length


of n characters with a character expression

REPLACE BLACK and Returns an expression right-padded to the length


('JACK and JUE','J','BL') BLUE of n characters with a character expression

TRIM('H' FROM 'HelloWorld') elloWorld Trims leading or trailing characters (or both) from a
character string
DBMS USING ORACLE > CHARACTER MANIPULATION FUNCTIONS

SELECT employee_id, CONCAT(first_name, last_name) NAME,


job_id, LENGTH (last_name),
INSTR(last_name, 'a') "Contains 'a'?"
FROM employees
WHERE SUBSTR(job_id, 4) = 'REP';
DBMS USING ORACLE > NUMERIC FUNCTIONS

ROUND: Rounds a numeric value to a specified decimal


TRUNC: Truncates a numeric value to a specified decimal
MOD: Returns remainder of division

Function Result
ROUND(45.926, 2) 45.93
TRUNC(45.926, 2) 45.92
MOD(1600, 300) 100
DBMS USING ORACLE > NUMERIC FUNCTIONS

SELECT ROUND(45.923,2), ROUND(45.923,0),


ROUND(45.923,-1)
FROM DUAL;

SELECT TRUNC(45.923,2), TRUNC(45.923),


TRUNC(45.923,-1)
FROM DUAL;

SELECT last_name, salary, MOD(salary, 5000)


FROM employees
WHERE job_id = 'SA_REP';
DBMS USING ORACLE > WORKING WITH DATES

The Oracle Database stores dates in an internal numeric format: century, year, month,
day, hours, minutes, and seconds.
The default date display format is DD-MON-RR.
Enables to store 21st-century dates in the 20th century by specifying only the last two
digits of the year
Enables to store 20th-century dates in the 21st century in the same way

SELECT last_name, hire_date


FROM employees
WHERE hire_date < '01-FEB-88';
DBMS USING ORACLE > WORKING WITH DATES

Current Specified RR format YY format


Year Date
1998 22-OCT-95 1995 1995
1998 27-OCT-18 2018 1917
2004 27-OCT-17 2017 2017
2014 27-OCT-95 1995 2095

If the specified two-digit year is:

0–49 50–99
If two digits The return date is in The return date is in
of the 0–49 the current century the century before
current the current one
year are: The return date is in The return date is in
50–99 the century after the the current century
current one
DBMS USING ORACLE > WORKING WITH DATES

SYSDATE is a function that returns the current date and time on the Oracle
server

SELECT sysdate
FROM dual;
DBMS USING ORACLE > WORKING WITH DATES

Since the database stores dates as numbers, perform calculations using


arithmetic operators such as addition and subtraction.
Add to or subtract a number from a date to get a resultant date value.
Subtract two dates to find the number of days between those dates.
Add hours to a date by dividing the number of hours by 24.
Below query displays the last name and the number of weeks the worker has
been employed for all employees in department 90

SELECT last_name, (SYSDATE-hire_date)/7 AS WEEKS


FROM employees
WHERE department_id = 90;
DBMS USING ORACLE > DATE FUNCTIONS

Function Result
MONTHS_BETWEEN(date1, date2) Finds the number of months between date1 and
date2
ADD_MONTHS(date, n) Adds +/-n number of calendar months to date.
NEXT_DAY(date, 'char') Finds the date of the next specified day of the week
('char') following date
LAST_DAY(date) Finds the date of the last day of the month that contains
date
ROUND(date[,'fmt']) Returns date rounded to the unit that is specified by
the format model fmt.
TRUNC(date[, 'fmt']) Returns date with the time portion of the day truncated
to the unit that is specified by the format model fmt.
DBMS USING ORACLE > DATE FUNCTIONS
Assume SYSDATE =
‘13-JUL-15':
Query Result
SELECT MONTHS_BETWEEN('01-SEP-15','11-JAN-14') FROM 19.6774194
dual
SELECT MONTHS_BETWEEN('01-SEP-15','11-JAN-16') FROM -4.3225806
dual
SELECT ADD_MONTHS('31-JAN-15',1) FROM dual 28-FEB-15
SELECT ADD_MONTHS('31-JAN-16',-1) FROM dual 31-DEC-15
SELECT NEXT_DAY('01-SEP-15','FRIDAY') FROM dual 04-SEP-15
SELECT NEXT_DAY('01-SEP-15',5) FROM dual 03-SEP-15
SELECT LAST_DAY('15-AUG-15') FROM dual 31-AUG-15
SELECT ROUND(SYSDATE,'MONTH') FROM dual 01-JUL-15
SELECT ROUND(SYSDATE,'YEAR') FROM dual 01-JAN-16
SELECT TRUNC(SYSDATE,'MONTH') FROM dual 01-JUL-15
DBMS USING ORACLE > DATE FUNCTIONS

Write a Query that displays the employee number, hire date, Round and truncate the
hire_date based on year and month for all employees hired in the year 2003

SELECT employee_id, hire_date,


ROUND(hire_date, 'MONTH') "MONTH
ROUND“,
TRUNC(hire_date, 'MONTH') "MONTH
TRUNC",
ROUND(hire_date, 'YEAR') "YEAR ROUND",
TRUNC(hire_date, 'YEAR') "YEAR TRUNC“
FROM employees
WHERE hire_date LIKE '%03‘;
DBMS USING ORACLE > USING SINGLE ROW FUNCTIONS TO CUSTOMIZE THE
OUTPUT

GUIDED ACTIVITY
DBMS USING ORACLE > USING SINGLE ROW FUNCTIONS TO CUSTOMIZE THE OUTPUT –
GUIDED ACTIVITY

Retrieve a list of all FIRST_NAME and LAST_NAME values from the EMPLOYEES
table where FIRST_NAME contains the character string “li.”

Envelope printing restricts the addressee field to 16 characters. Ideally, the


addressee field contains employees’ FIRST_NAME and LAST_NAME values
separated by a single space. When the combined length of an employee’s
FIRST_NAME and LAST_NAME exceeds 15 characters, the addressee field
should contain their formal name. An employee’s formal name is made up of the
first letter of their FIRST_NAME and the first 14 characters of their LAST_NAME.
You are required to retrieve a list of FIRST_NAME and LAST_NAME values and
formal names for employees where the combined length of FIRST_NAME and
LAST_NAME exceeds 15 characters.
DBMS USING ORACLE > USING SINGLE ROW FUNCTIONS TO CUSTOMIZE THE OUTPUT –
GUIDED ACTIVITY

Write a Query that displays the employee number, hire date, number of months
employed, six-month review date, first Friday after hire date, and the last day of
the hire month for all employees who have been employed for fewer than 150
months and working for department 50
DBMS USING ORACLE

CONCEPT
Using conversion
functions and
conditional expressions
DBMS USING ORACLE > USING CONVERSION FUNCTIONS AND CONDITIONAL
EXPRESSIONS

Topics covered:
Implicit and explicit data type conversion
TO_CHAR, TO_DATE, TO_NUMBER functions
Nesting functions
General functions:
NVL
NVL2
NULLIF
COALESCE
Conditional expressions:
CASE
DECODE
DBMS USING ORACLE > CONVERSION FUNCTIONS

Conversion
Functions

Implicit Data Explicit Data


Type conversion Type conversion
DBMS USING ORACLE > IMPLICT DATA TYPE CONVERSION

Oracle Server can automatically convert the below data types:


From To
VARCHAR2 or CHAR NUMBER
VARCHAR or CHAR DATE
NUMBER VARCHAR2 or CHAR
DATE VARCHAR2 or CHAR

The expression hire_date > '01-JAN-90' results in the implicit conversion from the
string '01-JAN-90' to a date.
The expression grade = 2 results in the implicit conversion of the number 2 to the
string “2” because grade is a CHAR(2) column.
Note: CHAR to NUMBER conversions succeed only if the character string
represents a valid number.
DBMS USING ORACLE > EXPLICT TYPE CONVERSION

TO_NUMBER TO_DATE

NUMBER CHARACTER DATE

TO_CHAR TO_CHA
R
DBMS USING ORACLE > TO_CHAR : DATE TO CHAR

TO_CHAR converts a datetime data type to a value of VARCHAR2 data type in the
format specified by the format_specifier.
A format specifier is a character literal that describes the format of datetime stored in a
character string.
For example, the datetime format specifier for the string '11-Nov-1999' is
'DD-Mon-YYYY'. Use the TO_CHAR function to convert a date from its default format
specified

TO_CHAR(date, 'format_specifier')
DBMS USING ORACLE > TO_CHAR : DATE TO CHAR

The format specifier:


Must be enclosed with single quotation marks
Is case-sensitive
Can include any valid date format element
The names of days and months in the output are automatically padded with blanks
Has an optional “fm” format prefix to remove padded blanks or suppress leading
zeros
Is separated from the date value by a comma.
DBMS USING ORACLE > TO_CHAR : DATE TO CHAR

Format specifiers for Days Months Format specifiers for Time components
and Years
Format Result Format Specifier Result
Specifier AM,PM,A.M, P.M Meridian Indicators
YYYY Full Year in numbers
HH, HH12 and Hour of day, 1–12 hours, and 0–23
YEAR Year spelled in English
HH24 hours
MM Two-Digit value for Month
MI Minute (0–59)
MONTH Full name of the month
SS Second (0–59)
MON Three letter abbreviation of the month
DY Three-letter abbreviation of the day of
week
DAY Full name of the day of the week
DD Numeric day of the month
DBMS USING ORACLE > TO_CHAR : DATE TO CHAR

select to_char(SYSDATE,'DD "of" MONTH')||


'is my birthdate' from dual;

select
to_char(SYSDATE,'DDspth "of" fmMONTH')||'
is my birthdate' from dual;
select to_char(SYSDATE,'DDth "of"
fmMONTH')||'
is my birthdate' from dual;

select to_char(SYSDATE,'DD.MM.YYYY')||'
is my birthdate' from dual;

select 'YOU ARE BORN in the Year '


||to_char(SYSDATE,'YEAR') from dual;
DBMS USING ORACLE > TO_CHAR : DATE TO CHAR

Query : Find the First Name, Hire Date in the format : “15 July 2015”
SELECT first_name,
TO_CHAR(hire_date, 'fmDD Month YYYY')
AS HIREDATE
FROM employees;

Query :Find the Last Name, Hire Date in the format : “Fifteenth of July 2015
12:00:00 AM”

SELECT first_name,
TO_CHAR(hire_date, 'fmDDth “of” Month YYYY fmHH:MI:SS
AM')
AS HIREDATE
FROM employees;
DBMS USING ORACLE > TO_CHAR : NUMBER TO CHAR

TO_CHAR converts a NUMBER data type to a value of VARCHAR2 data type in the
format specified by the format_specifier
This technique is useful for concatenating characters with numbers
A format specifier is a character literal that describes the format of Number to be
displayed as a character string
TO_CHAR(Number, 'format_specifier')

The below query converts number to character by applying a format specifier


‘0999999’ to number 0001
The zero and 6 nines in the format specifier indicate that leading zeros must be
displayed and that the display width must be set to seven characters
select to_char(00001,'0999999')||' is a special number'
from dual;
DBMS USING ORACLE > TO_CHAR : NUMBER TO CHAR

Number to Character Format Specifiers


Format Specifier Result
9 Represents a number
0 Forces a Trailing zero to be displayed
$ Places a floating dollar sign
L Uses the floating local currency symbol
. Prints a decimal point
, Prints a comma as a thousands indicator

Below query displays the salary for the employee ‘Ernst’ in the format
'$99,999.00

SELECT TO_CHAR(salary, '$99,999.00') SALARY


FROM employees
WHERE last_name = 'Ernst';
DBMS USING ORACLE > TO_NUMBER AND TO_DATE

Convert a character string to a number format using the TO_NUMBER function:

TO_NUMBER(char[, 'format_model'])

Convert a character string to a date format using the TO_DATE function:


TO_DATE(char[, 'format_model'])

These functions have an fx modifier. This modifier specifies the exact match for
the character argument and date format model of a TO_DATE function.
DBMS USING ORACLE > TO_NUMBER AND TO_DATE

To find employees hired before 1990, use the RR date format, which produces the
same results whether the command is run in 1999 or now:

SELECT last_name, TO_CHAR(hire_date,


'DD-Mon-YYYY')
FROM employees
WHERE hire_date <
TO_DATE('01-Jan-90','DD-Mon-RR');
DBMS USING ORACLE > NESTING FUNCTIONS

Single-row functions can be nested to any level.


Nested functions are evaluated from the deepest level to the least deep
level.

F3(F2(F1(col,arg1),arg2),arg3
)
Step 1 = Result 1
Step 2 = Result 2
Step 3 = Result 3
DBMS USING ORACLE > NESTING FUNCTIONS

SELECT last_name,
UPPER(CONCAT(SUBSTR (LAST_NAME, 1, 8), '_US'))
FROM employees
WHERE department_id = 60;

SELECT TO_CHAR(ROUND((salary/7),
2),'99G999D99',
'NLS_NUMERIC_CHARACTERS = '',.'' ')
"Formatted Salary"
FROM employees;
DBMS USING ORACLE > GENERAL FUNCTIONS

The following functions work with any data type and pertain to using
nulls:
Each of the below functions take arguments of the same data type
NVL (expr1, expr2)
NVL2 (expr1, expr2, expr3)
NULLIF (expr1, expr2)
COALESCE (expr1, expr2, ..., exprn)
DBMS USING ORACLE > NVL FUNCTION
NVL function converts a null value to an actual value. If the first argument is
NOT NULL displays the first argument, else displays the second argument
Below Query displays the last name, Salary, commission and final Annual
salary along with commission
Display 0, if The employee is not receive any commission
Final Annual salary is the sum of Annual Salary and the Commission on
the salary
SELECT last_name, salary, NVL(commission_pct, 0),
(salary*12) + (salary*12*NVL(commission_pct, 0)) ANNUAL_SAL
FROM employees;
DBMS USING ORACLE > NVL2 FUNCTION

The NVL2 function examines the first argument. If the first argument is not null, the
NVL2 function returns the second expression. If the first expression is null, the third
expression is returned.
Below Query displays the last name, Salary, commission and how the income
was earned
Income earned = ‘SAL‘ if commission is NULL
Income earned = ‘SAL+COMM if commission is NOT NULL

SELECT last_name, salary, commission_pct,


NVL2(commission_pct,
'SAL+COMM', 'SAL') income
FROM employees WHERE department_id IN (50, 80);
DBMS USING ORACLE > NULLIF FUNCTION
The NULLIF function compares the first argument with the second. If they
are equal returns NULL, else returns the first argument
It is now allowed syntactically to specify NULL for the first argument

Below Query displays the first name, length of first name, last name,
length of last name and result:
If both the first name and last name are of equal length display NULL
Else return the length of the first name
SELECT first_name, LENGTH(first_name) "expr1",
last_name, LENGTH(last_name) "expr2",
NULLIF(LENGTH(first_name), LENGTH(last_name)) result
FROM employees;
DBMS USING ORACLE > COALESCE FUNCTION
If the first argument to the COALESCE function is NOT NULL, then return that
expression
Else if the second expression is NOT NULL(and first argument is NULL), then it
returns that expression
Else(when the first and the second argument is NULL) return the third expression
In the below query:
if the comission_pct value is not null, it is displayed. If the comission_pct value is null,
the manager_id is displayed.
If the manager_id and commission_pct values are null, “No commission and no
manager” is displayed.
SELECT last_name, employee_id,
COALESCE(TO_CHAR(commission_pct),TO_CHAR(manager_id)
,
'No commission and no manager')
FROM employees;
DBMS USING ORACLE > COALESCE FUNCTION

Find the employees last name, first name, salary, commission and
new salary which is computed based on :
For employees who do not get any commission, the
organization gives a salary increment of $2,000
For employees who get commission the new salary is equal to
the existing salary + commission amount

SELECT last_name,first_name, salary,commission_pct, employee_id,


COALESCE(salary+(commission_pct*salary),salary+2000,salary) “NEW SALARY”
FROM employees;
DBMS USING ORACLE > CONDITIONAL EXPRESSIONS

Provide the use of the IF-THEN-ELSE logic within a SQL statement.


Use two methods:
CASE expression
DECODE function
DBMS USING ORACLE > CASE EXPRESSION

CASE expressions allow to use the IF-THEN-ELSE logic in SQL statements without the
need to invoke procedures.
CASE expr WHEN comparison_expr1 THEN return_expr1
[WHEN comparison_expr2 THEN return_expr2
WHEN comparison_exprn THEN return_exprn
ELSE else_expr]
END

The expressions expr and comparison_expr must be of the same data type
All of the return values (return_expr) must be of the same data type
SELECT last_name, job_id, salary,
CASE job_id WHEN 'IT_PROG' THEN 1.10*salary
WHEN 'ST_CLERK' THEN 1.15*salary
WHEN 'SA_REP' THEN 1.20*salary
ELSE salary END "REVISED_SALARY"
FROM employees;
DBMS USING ORACLE > DECODE FUNCTION

Facilitates conditional inquiries by doing the work of a CASE expression or an


IF-THEN-ELSE statement:

DECODE(col|expression, search1, result1


[, search2, result2,...,]
[, default])

Below query computes the revised salary by giving a salary increase of 10% to
IT_PROG, 15% to ST_CLERK and 20% to SA_REP. For other roles there would be no
increase in salary
SELECT last_name, job_id, salary, …
DECODE(job_id, 'IT_PROG', 1.10*salary,
'ST_CLERK', 1.15*salary,
'SA_REP', 1.20*salary,
salary) …
REVISED_SALARY
FROM employees;
DBMS USING ORACLE > USING CONVERSION FUNCTIONS AND CONDITIONAL
EXPRESSIONS

GUIDED ACTIVITY
DBMS USING ORACLE > USING CONVERSION FUNCTIONS AND CONDITIONAL
EXPRESSIONS – GUIDED ACTIVITY

Retrieve a list of FIRST_NAME and LAST_NAME values and an expression based


on the HIRE_DATE column for employees hired on a Saturday. The expression
must be aliased as START_DATE and a HIRE_DATE value of 17-FEB-1996 must
return the following string:
Saturday, the 17th of February, One Thousand Nine Hundred Ninety-Six.

You are required to return a set of rows from the EMPLOYEES table with
DEPARTMENT_ID values of 100. The set must also contain FIRST_NAME and
LAST_NAME values and an expression aliased as NAME_LENGTHS. This
expression must return the string 'Different Length' if the length of the
FIRST_NAME differs from that of the LAST_NAME, else the string 'Same Length'
must be returned.
DBMS USING ORACLE > USING CONVERSION FUNCTIONS AND CONDITIONAL
EXPRESSIONS – GUIDED ACTIVITY

You are requested to query the LOCATIONS table for rows with the value US in
the COUNTRY_ID column. An expression aliased as LOCATION_INFO is required
to evaluate the STATE_PROVINCE column values and returns different information
as per the following table. Sort the output based on the LOCATION_INFO
expression.

If State _Province Is The Value Returned Is


Washington Headquarters
Texas Oil Wells
California City
New Jersey Street Address
DBMS USING ORACLE

SUMMARY
DBMS USING ORACLE
DBMS USING ORACLE > SUMMARY

Key points discussed in this Lecture:

Select statement is used to retrieve the data from the DB


WHERE clause is used to restrict the data retrieved and Order by clause is used
to sort the data
Single row functions accept one or more arguments and return one result per row
Conversion functions are used to convert one data type to another with a
specified format
THANK
YOU
Copyright Manipal Global Education Services Pvt. Ltd. All Rights
Reserved.
All product and company names used or referred to in this work are trademarks or registered trademarks of their respective holders. Use of them in this
work does not imply any affiliation with or endorsement by them.

This work contains a variety of copyrighted material. Some of this is the intellectual property of Manipal Global Education, some material is owned by others
which is clearly indicated, and other material may be in the public domain. Except for material which is unambiguously and unarguably in the public domain,
permission is not given for any commercial use or sale of this work or any portion or component hereof. No part of this work (except as legally allowed for
private use and study) may be reproduced, adapted, or further disseminated without the express and written permission of Manipal Global Education or the
legal holder of copyright, as the case may be.

You might also like