Você está na página 1de 17

Week5_Lab4

1.

CHARACTER OR TEXT FUNCTIONS:

Character or text functions are used to manipulate text strings. They accept strings or
characters as input and can return both character and number values as output.
Few of the character or text functions are as given below:

Function Name

Return Value

LOWER (string_value) All the letters in 'string_value' are converted to lowercase.


UPPER (string_value)

All the letters in 'string_value' are converted to uppercase.

I N I T C A P
All the letters in 'string_value' are converted to mixed case.
(string_value)
LTRIM (string_value, All occurrences of 'trim_text'
trim_text)
of 'string_value'.

are removed from the left

RTRIM (string_value, All occurrences of 'trim_text' are removed from the right
trim_text)
of'string_value' .
T R I M ( t r i m _ t e x t A l l o c c u r r e n c e s o f 'trim_text' f r o m t h e l e f t a
n d r i g h t of 'string_value' ,'trim_text' and can be only one
FROM string_value)
character long .
S U B S T R Returns 'n' number of characters from'string_value' starting from the
(string_value, m, n)
'm' position.
L E N G
(string_value)

Number of characters in 'string_value' is returned.

LPAD (string_value, n, Returns 'string_value' left-padded with'pad_value' . The length of


pad_value)
the whole string will be of 'n' characters.
RPAD (string_value, n, Returns 'string_value' right-padded with 'pad_value' . The length of
pad_value)
the whole string will be of 'n' characters.

For Example, we can use the above UPPER() text function with the column value as
follows.
SELECT UPPER (product_name) FROM product;

The following examples explain the usage of above mentioned character or text functions
Function Name

Examples

Return Value

LOWER(string_value)

LOWER('Good Morning')

good morning

UPPER(string_value)

UPPER('Good Morning')

G O O
MORNING

INITCAP(string_value)

INITCAP('GOOD MORNING')

Good Morning

LTRIM(string_value, trim_text)

LTRIM ('Good Morning', 'Good) Morning

RTRIM (string_value, trim_text)

RT R I M ( ' G o o d M o r n i n
Good
g ' , ' Morning')

TRIM (trim_text FROM


TRIM ('o' FROM 'ood morning')
string_value)

d Morning

SUBSTR (string_value, m, n)

SUBSTR ('Good Morning', 6, 7)

Morning

LENGTH (string_value)

LENGTH ('Good Morning')

12

LPAD (string_value, n, pad_value) LPAD ('Good', 6, '*')

**Good

RPAD (string_value, n, pad_value) RPAD ('Good', 6, '*')

Good**

2.

NUMBER FUNCTION:

Round

Round(43.659,2) 43.66

Trunc

Trunc(43.659,2)

43.65

Mod

Mod(1600,300)

100

3.
DATE
FUNCTIONS:
These are functions that take values that are of data type DATE as input and return values of
data types DATE, except for the MONTHS_BETWEEN function, which returns a number
as output.

Few date functions are as given below.


Function Name

Return Value

ADD_MONTHS (date, n)

Returns a date value after adding 'n'months to the date 'x'.

MONTHS_BETWEEN (x1,
Returns the number of months between dates x1 and x2.
x2)
LAST_DAY (x)

It is used to see the last day in a month from the


date 'x' specified.

SYSDATE

Returns the systems current date and time.

The below table provides the examples for the above functions
Function Name

Examples

R e t u r n
Value

ADD_MONTHS ( )

ADD_MONTHS ('16-Sep-81', 3)

16-Dec-81

MONTHS_BETWEEN( MONTHS_BETWEEN ('16-Dec-81', '163


Jan-81')
)
LAST_DAY( )

LAST_DAY ('01-Jun-08')

4.
CONVERSION
FUNCTIONS:
Type Conversions
TO_DATE Convert a String to a Date
TO_NUMBER Convert a String to a Number
TO_CHAR Convert a Date or Number to a String

30-Jun-08

These are func,ons that help us to convert a value in one form to


another form. For Ex: a null value into an actual value, or a value from
one datatype to another datatype like NVL, TO_CHAR, TO_NUMBER, TO_DATE.

Few of the conversion functions available in oracle are:


Function Name

Return Value

TO_CHAR (x [,y])

Converts Numeric and Date values to a character string value. It


cannot be used for calculations since it is a string value.

T O _ D A T E ( x [ , Converts a valid Numeric and Character values to a Date value.


date_format])
Date is formatted to the format specified by 'date_format'.
NVL (x, y)

If 'x' is NULL, replace it with 'y'. 'x' and 'y'must be of the same
datatype.

DECODE (a, b, c, d, e, Checks the value of 'a', if a = b, then returns'c'. If a = d, then


default_value)
returns 'e'. Else, returnsdefault_value.

System default is usually DD-MON-YY Format


Use the TO_CHAR function to display the way you want it
You can convert a string to a date (TO_DATE) and a date to a string
(TO_CHAR) TO_DATE(2004-NOV-02, YYYY-MON-DD)
TO_CHAR(sysdate, YYYYMMDD)

The below table provides the examples for the above functions
Function Name

Examples

Return Value

TO_DATE ()

TO_CHAR (3000, '$9999')


TO _ C H A R ( S Y S D AT E , ' D a y,
Month
YYYY')
TO_DATE ('01-Jun-08')

$3000
Monday, Jun
e
2008
01-Jun-08

NVL ()

NVL (null, 1)

TO_CHAR ()

NVL2
As an enhancement over NVL, Oracle introduced a function to substitute value not only for
NULL columns values but also for NOT NULL columns. NVL2 function can be used to
substitute an alternate value for NULL as well as non NULL value.
Syntax:
NVL2( string1, value_if_NOT_null, value_if_null )

The SELECT statement below would display 'Bench' if the JOB_CODE for an employee is
NULL. For a definite not null value of JOB CODE, it would show constant value 'Job Assigned'.
SQL> SELECT NVL2(JOB_CODE,'Job Assigned','Bench')
FROM employees;

NULLIF
The NULLIF function compares two arguments expr1 and expr2. If expr1 and expr2 are equal, it
returns NULL; else, it returns expr1. Unlike the other null handling function, first argument can't
be NULL.
Syntax:
NULLIF (expr1, expr2)
Note that first argument can be an expression that evaluates to NULL, but it can't be the literal
NULL. Both the parameters are mandatory for the function to execute.
The below query returns NULL since both the input values, 12 are equal.
SELECT NULLIF (12,12)
FROM DUAL;

Similarly, below query return 'SUN' since both the strings are not equal.
SELECT NULLIF ('SUN','MOON')
FROM DUAL;

COALESCE
COALESCE function, a more generic form of NVL, returns the first non-null expression in the
argument list. It takes minimum two mandatory parameters but maximum arguments has no
limit.
Syntax:
COALESCE (expr1, expr2,... expr_n )
Consider the below SELECT query. It selects the first not null value fed into address fields for an
employee.
SELECT COALESCE (address1, address2, address3)Address
FROM employees;

Interestingly, the working of COALESCE function is similar to IF..ELSIF..ENDIF construct.


The query above can be re-written as IF address1 isnotnull THEN
result := address1;
ELSIF address2 isnotnull THEN
result := address2;
ELSIF address3 isnotnull THEN
result := address3;
ELSE
result :=null;
END IF;
What is a DUAL table in Oracle?
This is a single row and single column dummy table provided by oracle. This is used to perform
mathematical calculations without using a table.
Select * from DUAL
Output:
DUMMY
------X
Select 777 * 888 from Dual

Output:
777*888
--------689976
TO_CHAR FUNCTION EXAMPLES - WITH DATES
The following is a list of valid parameters when the TO_CHAR function is used to convert a
date to a string. These parameters can be used in many combinations.

MON

Abbreviated name of month.

M O N T Name of month, padded with blanks to length of 9 characters.


H
RM

Roman numeral month (I-XII; JAN = I).

WW

Week of year (1-53) where week 1 starts on the first day of the year and
continues to the seventh day of the year.

Week of month (1-5) where week 1 starts on the first day of the month and
ends on the seventh.

Day of week (1-7).

DAY

Name of day.

DD

Day of month (1-31).

DDD

Day of year (1-366).

DY

Abbreviated name of day.

The following are date examples for the TO_CHAR function


TO_CHAR(sysdate, 'yyyy/mm/dd');

would return '2003/07/09'

TO_CHAR(sysdate, 'Month DD, YYYY');

would return 'July 09, 2003'

TO_CHAR(sysdate, 'FMMonth DD, YYYY');

would return 'July 9, 2003'

TO_CHAR(sysdate, 'MON DDth, YYYY');

would return 'JUL 09th, 2003'

TO_CHAR(sysdate, 'FMMON DDth, YYYY');

would return 'JUL 9th, 2003'

TO_CHAR(sysdate, 'FMMon ddth, YYYY');

would return 'Jul 9th, 2003'

You will notice that in some TO_CHAR function examples, the format_mask parameter begins
with "FM". This means that zeros and blanks are suppressed. This can be seen in the examples
below.

TO_CHAR(sysdate, 'FMMonth DD, YYYY');

would return 'July 9, 2003'

TO_CHAR(sysdate, 'FMMON DDth, YYYY');

would return 'JUL 9th, 2003'

TO_CHAR(sysdate, 'FMMon ddth, YYYY');

would return 'Jul 9th, 2003'

The zeros have been suppressed so that the day component shows as "9" as opposed to "09".
FREQUENTLY ASKED QUESTIONS (TO_CHAR
FUNCTION) Question: Why doesn't this sort the days of the week
in order?
select ename, hiredate, TO_CHAR((hiredate),'fmDay') "Day"
from emp
order by "Day";
Answer: In the above SQL, the fmDay format mask used in the TO_CHAR function will
return the name of the Day and not the numeric value of the day.
To sort the days of the week in order, you need to return the numeric value of the day by using
the fmD format mask as follows:
select ename, hiredate, TO_CHAR((hiredate),'fmD') "Day"
from emp
order by "Day";

What are group functions?


Group Functions ignore null values in the column.
These are the GROUP functions:

1. AVG
2. COUNT
3. MAX
4. MIN
5. STDDEV
6. SUM
7. VARIANCE

Syntax: select columns, GROUP FUNCTION(COLUMN) from table WHERE condition


GROUP BY column_name ORDER BY column_name;
Eg: select AVG(salary), MAX(salary),MIN(salary),SUM(salary) from employee where JOB_ID
= 1234;
Select count(*) from employee where dept_id = 20;
Select count(DISTINCTDEPT_ID) from employee;

Creating Groups of Data: Group By Clause Syntax:


Divide row in a table into smaller groups by using the GROUP BY clause. All the columns in
SELECT list that are not in group functions must be in the GROUP BY clause.
The GROUP BY column does not have to be in the SELECT list.
Syntax: Select columns, GROUP_FUNCTION(column) from table where condition group by
GROUP_BY_EXPRSSION order by column;
Eg: SELECT DEPT_ID, AVG(SALARY) FROM EMPLOYEE GROUP BY
DEPT_ID; Group by clause can be used by MULTIPLE columns.
Eg: Select dept_id,job_id, SUM(Salary) from employee group by dept_id,job_id;
Illegal Queries, Any Column or expression in the SELECT list that is not an aggregate
function must be in the GROUP BY clause, it is not a single-group group function.
You can not use the where clause to restrict groups.
You use the having clause to restrict groups.

You cant use group functions in the Select dept_id, count(last_name) from employee;
Column missing in the group by clause.

The HAVING clause:


Group Results can be exclude using HAVING Clause. It restricts group,
Rows are grouped.
The group function is applied.
Group matching the having clause are displayed.
Eg: Select dept_id,max(salary) from emp group by dept_id having max(salary)>1500;

Lab practice queries

Note: Before start solving the below queries just run the below script in the putty one by one

CREATE TABLE s_12345_dept


(id

NUMBER(7)

CONSTRAINT s_dept_id_nn NOT NULL,


name

VARCHAR2(25)

CONSTRAINT s_dept_name_nn NOT NULL,


region_id

NUMBER(7),

CONSTRAINT s_dept_id_pk PRIMARY KEY (id),


CONSTRAINT s_dept_name_region_id_uk UNIQUE (name, region_id));

INSERT INTO s_dept VALUES (10, 'Finance', 1);


INSERT INTO s_dept VALUES ( 31, 'Sales', 1);
INSERT INTO s_dept VALUES (32, 'Sales', 2);
INSERT INTO s_dept VALUES ( 33, 'Sales', 3);
INSERT INTO s_dept VALUES (34, 'Sales', 4);
INSERT INTO s_dept VALUES (35, 'Sales', 5);
INSERT INTO s_dept VALUES (41, 'Operations', 1);
INSERT INTO s_dept VALUES (42, 'Operations', 2);
INSERT INTO s_dept VALUES ( 43, 'Operations',
3); INSERT INTO s_dept VALUES ( 44,
'Operations', 4); INSERT INTO s_dept VALUES
( 45, 'Operations', 5);
INSERT INTO s_dept VALUES (50, 'Administration',
1); COMMIT;

CREATE TABLE s_12345_emp (id


NUMBER(7) CONSTRAINT
s_emp_id_nn NOT NULL, last_name
VARCHAR2(25)
CONSTRAINT s_emp_last_name_nn NOT NULL,
first_name
userid
start_date

VARCHAR2(25),
VARCHAR2(8),
DATE,

comments

VARCHAR2(25),

manager_id

NUMBER(7),

title
dept_id
salary
commission_pct

VARCHAR2(25),
NUMBER(7),
NUMBER(11, 2),
NUMBER(4, 2),

CONSTRAINT s_emp_id_pk PRIMARY KEY (id),


CONSTRAINT s_emp_userid_uk UNIQUE (userid)
);

INSERT INTO s_emp VALUES (1, 'Velasquez', 'Carmen', 'cvelasqu', to_date('03-MAR-90 8:30',
'dd-mon-yy hh24:mi'), NULL, NULL, 'President',50, 2500, NULL);
INSERT INTO s_emp VALUES ( 2, 'Ngao', 'LaDoris', 'lngao',
'VP, Operations',41, 1450, NULL);

'08-MAR-90', NULL, 1,

INSERT INTO s_emp VALUES ( 3, 'Nagayama', 'Midori', 'mnagayam', '17-JUN-91', NULL, 1,


'VP, Sales',31, 1400, NULL);
INSERT INTO s_emp VALUES (4, 'Quick-To-See', 'Mark', 'mquickto', '07-APR-90', NULL, 1,
'VP, Finance', 10, 1450, NULL);

INSERT INTO s_emp VALUES (5, 'Ropeburn', 'Audry', 'aropebur', '04-MAR-90', NULL, 1,
'VP, Administration', 50, 1550, NULL);
INSERT INTO s_emp VALUES (6, 'Urguhart', 'Molly', 'murguhar',
'Warehouse Manager',41, 1200, NULL);

'18-JAN-91', NULL, 2,

INSERT INTO s_emp VALUES (7, 'Menchu', 'Roberta', 'rmenchu','14-MAY-90', NULL, 2,


'Warehouse Manager', 42, 1250, NULL);
INSERT INTO s_emp VALUES (8, 'Biri', 'Ben', 'bbiri',
Manager',43, 1100, NULL);

'07-APR-90', NULL, 2, 'Warehouse

INSERT INTO s_emp VALUES (9, 'Catchpole', 'Antoinette', 'acatchpo','09-FEB-92', NULL, 2,


'Warehouse Manager', 44, 1300, NULL);
INSERT INTO s_emp VALUES (10, 'Havel', 'Marta', 'mhavel', '27-FEB-91', NULL, 2,
'Warehouse Manager', 45, 1307, NULL);
INSERT INTO s_emp VALUES (11, 'Magee', 'Colin', 'cmagee','14-MAY-90', NULL, 3, 'Sales
Representative', 31, 1400, 10);
INSERT INTO s_emp VALUES (12, 'Giljum', 'Henry', 'hgiljum', '18-JAN-92', NULL, 3, 'Sales
Representative', 32, 1490, 12.5);
INSERT INTO s_emp VALUES (13, 'Sedeghi', 'Yasmin', 'ysedeghi','18-FEB-91', NULL, 3, 'Sales
Representative',33, 1515, 10);
INSERT INTO s_emp VALUES (14, 'Nguyen', 'Mai', 'mnguyen','22-JAN-92', NULL, 3, 'Sales
Representative', 34, 1525, 15);
INSERT INTO s_emp VALUES (15, 'Dumas', 'Andre', 'adumas', '09-OCT-91', NULL, 3, 'Sales
Representative', 35, 1450, 17.5);
INSERT INTO s_emp VALUES (16, 'Maduro', 'Elena', 'emaduro','07-FEB-92', NULL, 6, 'Stock
Clerk',41, 1400, NULL);
INSERT INTO s_emp VALUES (17, 'Smith', 'George', 'gsmith', '08-MAR-90', NULL, 6, 'Stock
Clerk', 41, 940, NULL);
INSERT INTO s_emp VALUES (18, 'Nozaki', 'Akira', 'anozaki', '09-FEB-91', NULL, 7, 'Stock
Clerk',42, 1200, NULL);
INSERT INTO s_emp VALUES (19, 'Patel', 'Vikram', 'vpatel', '06-AUG-91', NULL, 7, 'Stock
Clerk', 42, 795, NULL);
INSERT INTO s_emp VALUES (20, 'Newman', 'Chad', 'cnewman', '21-JUL-91', NULL, 8,
'Stock Clerk', 43, 750, NULL);

INSERT INTO s_emp VALUES (21, 'Markarian', 'Alexander', 'amarkari', '26-MAY-91', NULL,
8, 'Stock Clerk', 43, 850, NULL);
INSERT INTO s_emp VALUES (22, 'Chang', 'Eddie', 'echang','30-NOV-90', NULL, 9, 'Stock
Clerk',44, 800, NULL);
INSERT INTO s_emp VALUES (23, 'Patel', 'Radha', 'rpatel','17-OCT-90', NULL, 9, 'Stock
Clerk',34, 795, NULL);
INSERT INTO s_emp VALUES (24, 'Dancs', 'Bela', 'bdancs','17-MAR-91', NULL, 10, 'Stock
Clerk',45, 860, NULL);
INSERT INTO s_emp VALUES (25, 'Schwartz', 'Sylvie', 'sschwart', '09-MAY-91', NULL, 10,
'Stock Clerk',45, 1100, NULL);
COMMIT;

Practice
Questions

1. select to_number('$3,221,000.16','$9,999,999.99') N1 from dual;


2. Display first name ,last name and salary from s_emp where salary
should display in the format $99,999
3. Write query to display employee name, commission , hire date and
job from s_emp if commission is null then display 0,if hire date is
null then display
01/01/1980 and if job is null then display UNKNOWN JOB.
4. Write query to display first name and last name as full name,
salary *12+
commission_pct *salary as Total Salary from s_emp.If
commission_pct
*salary is null then consider it as zero use nvl function
5. s e l e c t t o _ c h a r ( s y s d a t e , ' Y Y Y Y ' ) C 1 , t o _ c h a r
(sysdate,'YEAR')C2,to_char(sysdate,'MM')
C 3 , t o _ c h a r ( s y s d a t e , ' D Y ' ) C4,to_char(sysdate,'DAY')
C5 from dual; Explain the result.
YYYY- format of year of 20th and 21st Century eg: 1996 & 2015
YEAR It will print in full name eg: 2015 as twenty fifteen
MM month in numeric format
DY- first three characters of weekday
DAY Display full name of that weekday

6. s e l e c t t o _ c h a r ( s y s d a t e , ' Y Y ' ) C 2 , t o _ c h a r ( s y
sdate,'RR')C3,to_char(sysdate,'MONTH') C
4,to_char(sysdate,'MON')C5,to_char(sysdat
e , ' R M ' ) C 6 , t o _ c h a r ( s y s d a t e , ' W W ' )
C7,to_char(sysdate,'W') C8 from dual; Explain the result.
Solution: W week of the month
WW- week of the year
RM Display the month in roman
number MON month (only 3
characters) MONTH display full
name of month
RR RR converts two-digit years into four-digit years by rounding
YY- It allows you to retrieve just two digits of a year, for example, the 99 in
1999
7. Display word gOwoLFpack in 3 ways by using Initcap , upper and
lower functions
8. select
substr('ABCDEFG',0)
S1
,substr('ABCDEFG',1) S2
,substr('ABCDEFG',4)
S3
,substr('ABCDEFG',4,3) S4
,substr('ABCDEFG',-5)
S5 ,substr('ABCDEFG',-5,4) S6
,substr('ABCDEFG',-5,10) S7
,substr('ABCDEFG',-5,-1) S8 from dual; Explain the result.
substr('ABCDEFG',0)
display full string

= It will start from 1 therefore, it will

substr('ABCDEFG',1) = Since,It is 1 till end (by default) display


whole string.
substr('ABCDEFG',4) = 4th position till end of string
substr('ABCDEFG',4,3) =4th position till only 3 characters of
string substr('ABCDEFG',-5) = last 5 characters from end

substr('ABCDEFG',-5,4) = first it will fetch 5 characters from


backend then display first 4 characters
substr('ABCDEFG',-5,10) = first it will fetch 5 characters from
backend then display first 10 characters
substr('ABCDEFG',-5,-1) = first it will fetch 5 characters from
backend then search 1 character from 1st position back which is not
there
9. Display ename and length of ename from s_emp.0.REPLACE(string1,
string2, string3), returns with string2 --replaced by string3 inside string1.
Take any string you want.

10.write query to display employee name ,job, salary and revised salary
from s_emp
If job is Ware house manager then revised salary = salary*1.03
If job is Sales representative then revised salary = salary*1.1
If job is stock clerk then revised salary = salary*1.01
Else display revised salary = salary(Use decode function).[Extra Credit].

Você também pode gostar