SQL1
SQL1
Oracle-Day-2
DBMS USING ORACLE
OBJECTIVES
DBMS using oracle
DBMS USING ORACLE > OBJECTIVES
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
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
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
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 ?
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
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
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(||)
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
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
GUIDED ACTIVITY
DBMS USING ORACLE > RETRIEVING DATA USING THE SQL SELECT STATEMENT –
GUIDED ACTIVITY
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
…
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
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
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’
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;
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
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.
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
…
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 ;
Below query sorts the data based on the numeric position of a column/column alias
in the SELECT clause
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
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
Use Single quotation marks while substituting the Date and character values
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
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
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
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
TRIM('H' FROM 'HelloWorld') elloWorld Trims leading or trailing characters (or both) from a
character string
DBMS USING ORACLE > CHARACTER MANIPULATION FUNCTIONS
Function Result
ROUND(45.926, 2) 45.93
TRUNC(45.926, 2) 45.92
MOD(1600, 300) 100
DBMS USING ORACLE > NUMERIC FUNCTIONS
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
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
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
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.”
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
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
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
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,'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;
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')
Below query displays the salary for the employee ‘Ernst’ in the format
'$99,999.00
TO_NUMBER(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:
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
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
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
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
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.
SUMMARY
DBMS USING ORACLE
DBMS USING ORACLE > SUMMARY
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.