Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

SQL 2 - More Functions and WHERE Clause

Uploaded by

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

SQL 2 - More Functions and WHERE Clause

Uploaded by

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

THE DEMO

TABLES
Selected Character Functions
• INITCAP( )
• LOWER( )
• UPPER( )
• LENGTH( )
• SUBSTR( )
• INSTR( )
• LPAD( ) RPAD( )
• LTRIM( ) RTRIM( )
• REPLACE( )
More Character functions

SELECT dname SELECT INITCAP(dname) SELECT LENGTH(dname)


FROM dept; FROM dept; FROM dept;
SUBSTR(..) Function

To display the first three characters of an employee’s name:

SELECT SUBSTR(ename,1,3)
FROM EMP;
The name
of the The starting
column you position for The number of characters
are your you are extracting; if
extracting extraction absent, assumes
characters everything from
from character 1 onwards
SUBSTR( ) function
To display the last 4 characters of every employee name:

SELECT SUBSTR(ename, -4)


FROM emp;

What will this display?

SELECT SUBSTR(ename, -4, 2)


FROM emp;
INSTR ( ) function
Searches for a specific character or substring and returns the
position in which that character/substring is found

SELECT INSTR(ename,'E'), ename


FROM emp;

Returns the character position


of the first ‘E’ in every name
LPAD and RPAD functions
Allow you to ‘pad out’ or fill the left or the right side of a
character string with a given character.

SELECT dname, RPAD(dname, 15, ‘*’)


FROM dept;

The column The


being The width character
‘padded’ of the being used
column for the
needing padding
‘padding’

SELECT dname, LPAD(dname, 15, ‘*’)


FROM dept;
LTRIM and RTRIM functions
Functions remove specific string characters from left or right of a
string.

Eg: If you wanted to strip the last ‘S’ from


employee names:
SELECT ename, RTRIM(ename, 'S')
FROM emp;
REPLACE function
Searches for a character/string and replaces it with
a given character/string
SELECT ename, REPLACE(ename,'LL','la-la-la')
FROM emp;

Serching for Replacing


‘LL’ in the any LL’s
ename found with
column ‘la-la-la’
Exercises – using the
‘EMP’ table:
• List all jobs in lower case;
• Produce a list of employee names,
followed by the number of characters in
each name.
• List the first three characters of each job,
but don’t include any duplicates.
• Display a single field named ‘Funny Name’
which consists of the first three characters
of each employee’s name joined to the last
three characters of their name.

You will need:


SELECT ..
FROM …

LENGTH( ) SUBSTR( ) LOWER( )

DISTINCT || (Concatination)
DATE FUNCTIONS
• SYSDATE
• MONTHS_BETWEEN( )
SELECT hiredate
• ADD_MONTHS ( ) FROM emp;

• TO_CHAR ( )
• TO_DATE ( )
Date Functions
• Default display for date in Oracle is DD-MON-YY
• It is stored as a number and includes the year,
month, day, minutes and seconds
• Valid dates are between 1-JAN-4712 B.C. and 31-
DEC-9999 A.D.
• Because dates are stored as numbers, you can do
‘maths’ with them (the result is in days) eg: from the
ORD table:
SELECT ordid, shipdate – orderdate
FROM ord;

Result is the number of days


between the order’s shipdate and
the orderdate
Date functions
SYSDATE – returns the system date.
Can be used with ‘date maths’:
SELECT ename, (SYSDATE – hiredate)/7
FROM emp;

Gives the number of weeks the


employee has been hired
(rather too precisely …!)

SELECT ename, TRUNC ((SYSDATE – hiredate)/7 )


FROM emp;

The function TRUNC truncates the


decimal places
Or you can use ROUND to round to the
nearest whole number
MONTHS_BETWEEN function
Displays the no. of months between two
dates, eg:
SELECT ename, MONTHS_BETWEEN (SYSDATE, hiredate)
FROM emp;

ADD_MONTHS function
Adds given no. of months to a date field, eg
SELECT hiredate, ADD_MONTHS (hiredate, 24)
FROM emp;

Adds 24 months to
the hiredate field
The TO_CHAR Function
This is used for displaying dates in a particular format (rather
than the Oracle default of ‘DD-MON-YY’, by specifying a format
mask.
TO_CHAR (datefield, ‘format mask’)

Elements of a format
mask include:
TO_CHAR function
Egs:
SELECT TO_CHAR(orderdate, 'DAY, MONTH, YEAR')
FROM ord;

SELECT TO_CHAR(orderdate, ‘DD/MM/YY’)


FROM ord;

SELECT TO_CHAR(ORDERDATE, 'DDTH MON YYYY')


FROM ord;
TO_DATE function
This function allows users to enter a date in their preferred
format (eg DD/MM/YY):

SELECT ordid, orderdate


FROM ord
WHERE orderdate = TO_DATE(’06/01/16’, ‘DD/MM/YY’);
MISC FUNCTIONS
• NVL ( )
• DECODE ( )
• CASE

NUMBER FUNCTIONS
• ROUND( )
• TRUNC ( )
NVL and DECODE functions
NVL function
NULL values can cause problems in calculations, as any calculation involving a
NULL always equates to NULL. eg
SELECT empno, sal, comm, sal + comm
FROM emp;
You can see here that anywhere
where there is a NULL
commission gives a SAL+COMM
result of NULL

NVL function allows you to substitute a value for any NULLs found in a column, eg:
SELECT empno, sal, comm, sal + NVL(comm, 0)
FROM emp; This will look for
any NULLs in the ..and
comm column substitute
them with a 0
DECODE function
Allows you to ‘decode’ a field: Eg, supposing you wanted to display a list of
employees and the name of their departments, using just the emp table:
(assumes you know the names of the deparments)

SELECT ename, deptno, DECODE(deptno, 10, ‘Accounting’,


20, ‘Research’,
‘Other’) “Department”
FROM emp;

If the query finds a 10 in the deptno


column it will display ‘Accounting’; if
20, it will display ‘Research’, if any
other value, it will display ‘Other’
Using DECODE in conjunction with SUBSTR
Supposing EMPNO was coded such that the second digit
represents the employee’s cost centre; 9 = Alpha cost
centre; 8 = Beta cost centre, 7 = Gamma and everything
else is ‘Delta’

To retrieve a list of employee names and their cost centres:

SELECT ename, empno,


DECODE(SUBSTR(empno,2,1),
9,'Alpha',
8,'Beta',
7,'Gamma',
'Delta') "Cost Centre"
FROM emp;
CASE function
Eg: supposing the company wanted to give all employees in the ‘emp’
table a bonus based on their salary:
£100 for those earning less than 20000,
£200 for those earning between 20001 and 25000
and £300 for those earning over 25000
To disply the name of all employees, their salary and their bonus:
SELECT ename, sal,
CASE
WHEN (sal <20000) THEN ‘100’
WHEN (sal BETWEEN 20001 AND 25000) THEN ‘200’
WHEN (sal > 25000) THEN ‘300’
END “Bonus”
FROM EMP;
(also ELSE …)
Exercises – using the
‘CUSTOMER’ table:
• List all customer names and the content
of their ‘comments’ field. Show ‘’No
Comments” if the comments value is
missing.
• List all customer IDs and their areas in
full (if ‘NW’ then display ‘North West’, if
‘SW’ then ‘South West’, if ‘SE’, then
‘South East’, for anything else, display
‘Other’.
• Display tomorrow’s date in the format
’12/01/22 24:01:40’ (showing
hrs,minutes, seconds)

You will need:


NVL( ) DECODE ( ) TO_CHAR( )
Retrieving Specific Rows – adding a
condition using the WHERE Clause
To list the employee name and department number
for all employees in department 30:

NOTE: if the field you are using in


your condition is a NUMERIC field
type, then no single quotes are
required around your search criteria.

For non-numeric fields, the column


value needs to be enclosed in single
quotes (see next slide)
The WHERE Clause
To list the name of employees who are Salesmen: Note the stored data
is case sensitive
SELECT ename, job SELECT ename, job
FROM emp FROM emp
WHERE job = ‘SALESMAN’ WHERE job = ‘salesman’

Produces no records because the


data in the tables is in upper case
More operators
OR, AND
SELECT ename, job
FROM emp
WHERE job = ‘SALESMAN’
OR job = ‘CLERK’

SELECT ename, job


FROM emp
WHERE job = ‘SALESMAN’ OR‘CLERK’

SELECT ename, job


FROM emp
WHERE job = ‘SALESMAN’
AND sal > 5000
More operators
IN ( ) operator
Returns records matching one of the values listed in
the condition eg to retrieve the name of employees
working as clerks, managers or salesmen:
SELECT ename
FROM emp
WHERE job IN (‘CLERK’,’MANAGER’,’SALESMAN’);

This is the same as:


SELECT ename
FROM emp
WHERE job = ‘CLERK’
OR job = ‘MANAGER’
OR job = ‘SALESMAN’;
LIKE operator
Returns records matching a specified pattern. ‘Wildcard
characters’ are used to represent one or more characters:
% sign represents any number of characters (zero, one or more)
_ (underscore) represents exactly one character

Eg, to list names that start with ‘S’:


SELECT ename
FROM emp
WHERE ename LIKE ‘S%’

To list names that end with ‘S’:


SELECT ename
FROM emp
WHERE ename LIKE ‘%S’
LIKE operator
To List employees who have ‘A’ as the 2nd letter of their
name: One underscore = 1 characters,
followed by ‘A’, followed by % (ie
SELECT ename any number of characters)
FROM emp
WHERE ename LIKE ‘_A%’

NOTE: wildcard characters are always used with LIKE.


So the following (using = ) would not produce any output
because the query would treat the value in quotes as a string
literal, and would look for an employee named ‘_A%’:

SELECT ename
FROM emp
WHERE ename = ‘_A%’
Retrieving NULL values
NULL means the absence of data from a field – it’s not the same
as a space. When searching for NULL values the IS NULL
comparison operator is used.
Eg to search for employees who do not have a manager (mgr):

SELECT ename, mgr


FROM emp
WHERE mgr IS NULL;

If you use = NULL the query will run but will not retrieve any
records:
SELECT ename, mgr
FROM emp
WHERE mgr = NULL;
Exercises – using the
‘CUSTOMER’ table:
1. List the names of all customers
in the ‘SW’ area.
2. List the customer IDs of all
customers with a credit limit of
between 1000 and 3000.
3. List full details of all the
customers who live in Bath,
Bristol or London
4. List full details of customers who
live in the ‘SW’ area or have staff
no. 7889 (repid) as their rep.
More Exercises
1. The name of employees who are salesmen.

2. List the names of all employees supervised by


managers (mgr) 7902, 7839 or 7566. Order the list by
employee name.

3. A list of all salesmen and the sum of their salary


and commission as a single field. Rename this
column as ‘Total Salary’.

4. The name of all customers with a customer id


ending in 002 or with ‘W’ as the third letter of their
surname.

5.Produce an alphabetic listing of the name and


salary of all employees with names begin with ‘S’ or
‘W’.

6. Produce a list showing the customer name, the


customer’s rep and the customer’s area. Display the
area in full, where
SW = South West
NW = North West and everything else is ‘Other’
Further Reading:
Casteel, J: Oracle 11g SQL – Chapters 2 & 8

You might also like