Download presentation
Presentation is loading. Please wait.
Published byNoreen Nicholson Modified over 9 years ago
1
Database Programming Sections 1 & 2 – Case and Character Manipulations, number functions, date functions, conversion functions, general functions, conditional expressions, Null functions 10/10/06 – 10/7/11 & 10/18/11 Section 1 is slide 1-34 Section 2 starts at slide 35. User 2012
2
DUAL function The DUAL table has one row called "X" and one column called "DUMMY.“ The DUAL table is used to create SELECT statements and execute commands not directly related to a specific database table. SELECT (319/29) + 12 From Dual; Returns 1 row results Data type varchar2 Marge Hohly
3
Single Row Functions Single row functions are very powerful pre-defined code that accepts arguments and returns a value. An argument can be defined as a column name, an expression, or a constant. There are five single row functions groups: Character Date General Number Conversion Arguments in () Used in Select, Where, & Order By clauses SELECT UPPER(first_name) FROM d_clients WHERE first_name LIKE '%a%'; Marge Hohly
4
Case/Character Manipulation
Use case-manipulations to make sure the data in storage is in the same format as the query. Case- manipulation are generally used in Select, ORDER BY and Where clauses Marge Hohly
5
Single Row Functions Single-row character functions are divided into two categories: functions that convert the case of character strings functions that can join, extract, show, find, pad, and trim character strings. Single-row functions can be used in the SELECT, WHERE, and ORDER BY clauses. Slide 5: Tell Me / Show Me – DUAL TABLE Begin this lesson with a review question: What are the five types of single-row functions? Answer: Character, Number, Date, Conversion, and General Marge Hohly
6
Single Row Functions Character Functions (Case manipulation)
LOWER converts character strings to all lower case. SELECT last_name FROM employees WHERE last_name = ‘king’ WHERE LOWER(last_name) = ‘king’ (should be this way) UPPER converts character strings to all upper case. INITCAP converts the first letter of each word to upper case and the remaining letters to lower case. – DUAL TABLE (continued) DUAL will be used to learn many of the single-row functions Demonstrate and practice the following functions. 1. Create a query that outputs the CD titles in the DJ on Demand database in all lowercase letters. SELECT LOWER(title) FROM d_cds; 2. Create a query that selects the first names of the DJ on Demand clients who have an "a" somewhere in their name. Output the results set in all uppercase letters. Ask students why UPPER was put in the SELECT statement and not in the WHERE clause. SELECT UPPER(first_name) FROM d_clients WHERE first_name LIKE '%a%'; Marge Hohly
7
Case Manipulation LOWER(column|expression) converts alpha characters to lower-case. UPPER(column|expression) converts alpha character to upper case INITCAP(column|expression) converts alpha character values to uppercase for the first letter of each word. (Title Case) Marge Hohly
8
Character Functions Function Result LOWER (‘I Love SQL’) i love sql
Character Functions (Case manipulation) Function Result LOWER (‘I Love SQL’) i love sql UPPER (‘I love SQL’) I LOVE SQL INITCAP(‘I Love SQL’) I Love Sql Marge Hohly
9
DUAL examples SELECT LOWER('Marge') FROM dual;
SELECT UPPER(‘Hello’) FROM dual; SELECT SYSDATE FROM dual; Dual is helpful with data conversions Marge Hohly
10
LOWER examples Create a query that outputs the CD titles in the DJ on Demand database in all lowercase letters. SELECT LOWER(title) FROM d_cds; Create a query that selects the first names of the DJ on Demand clients who have an "a" somewhere in their name. Output the results set in all uppercase letters. Ask students why UPPER was put in the SELECT statement and not in the WHERE clause. SELECT UPPER(first_name) FROM d_clients WHERE first_name LIKE '%a%'; Marge Hohly
11
Using LOWER, UPPER & INITCAP
Use LOWER, UPPER, & INITCAP in SELECT statement to affect the output of the data Use in WHERE & ORDER BY to determine how data is chosen not displayed SELECT last_name,job_id FROM employees WHERE LOWER(job_id) = ‘it_prog‘; SELECT UPPER(last_name),job_id FROM employees; Marge Hohly
12
Character Functions CONCAT joins two values together.
Character Functions (Character manipulation) CONCAT joins two values together. SUBSTR extracts a string of characters from a value. LENGTH shows the length of a string as a numeric value. LPAD/RPAD pads specified character to the left or right. INSTR finds the numeric position of a named character. TRIM trims leading, trailing, or both characters from a string. REPLACE replaces a string of characters. CONCAT – concatenates the first value to the second value (equivalent to the (||) operator). 4 digit acct # SELECT LPAD(SUBSTR(‘ ’, 8, 4), 11, ‘*’) FROM dual; Marge Hohly
13
Single Row Functions Function Result LENGTH(‘ABCDEF’) 6
Character Functions (Character manipulation) Function Result CONCAT(‘ABC’, ‘DEF’) ABCDEF SUBSTR(‘ABCDEF’,2,3) BCD LENGTH(‘ABCDEF’) 6 INSTR(‘ABCDEF’,’C’) 3 CONCAT – concatenates the first value to the second value (equivalent to the (||) operator). CONCAT: Joins two values together. SUBSTR: Extracts a string of a determined length. SUBSTR (string, starting position, length of extract) LENGTH: Shows the length of a string as a number value. INSTR: Finds the numeric position of a named character. Marge Hohly
14
Try these SELECT SUBSTR(hire_date, 2, 4) FROM employees;
SELECT LENGTH(last_name), last_name FROM employees; SELECT LPAD(‘ ’,15,’*’) FROM dual; Displays only the last 4 digits of the SOC. Security number Slide 12: Tell Me / Show Me – CHARACTER-MANIPULATION FUNCTIONS Demonstrate and practice each character-manipulation function shown in the graphic function/result table. Substitute other character strings and numeric values in the SELECT clause. SELECT CONCAT('Hello', 'World') FROM DUAL; SELECT SUBSTR('HelloWorld', 1, 5) SELECT LENGTH('HelloWorld') SELECT INSTR('HelloWorld', 'W') Marge Hohly
15
Single Row Functions Function Result BC REPLACE(‘ABC’,’B’,’*’) A*C
Character Functions (Character manipulation) Function Result LPAD (salary,9,’*’) ****15000 RPAD (salary,9,’*’) 15000**** TRIM (leading ‘A’ from ‘ABCA’) trailing or both BC REPLACE(‘ABC’,’B’,’*’) A*C LPAD: Pads the left side of a character, resulting in a right-justified value. LPAD(column, total length, pad character) LPAD – pads the value right justified with the third parameter, to a total length of the second parameter. RPAD: Pads the right-hand side of a character, resulting in a left- justified value. TRIM: Removes all specified characters from either the beginning or the ending of a string. The syntax for the trim function is: trim ( [ leading | trailing | both [character(s) to be removed] ] string to trim ) If none of these is chosen (i.e., leading, trailing, both), the trim function will remove [the character(s) to be removed ] from both the front and end of [string to trim]. REPLACE: Replaces a sequence of characters in a string with another set of characters. The syntax for the REPLACE function is: replace (string1, string_to_replace, [replacement_string] ) string1 is the string that will have characters replaced in it. string_to_replace is the string that will be searched for and taken out of string1. [replacement_string] is the new string to be inserted in string1. Marge Hohly
16
Try These SELECT LPAD(salary, 9, '*') FROM employees;
SELECT TRIM(trailing 'a’ from 'abbba') FROM dual; SELECT TRIM(both 'a’ from 'abbba') FROM dual; SELECT REPLACE('ABC', 'B','*') FROM dual; SELECT last_name, LPAD(salary,10,'*') FROM employees; SELECT first_name, RPAD(salary,10,'*') Marge Hohly
17
Terminology Review DUAL- Dummy table used to view results from functions and calculations Format-The arrangement of data for storage or display. INITCAP-Converts alpha character values to uppercase for the first letter of each word, all other letters in lowercase. Slide 16 Marge Hohly
18
Terminology cont. Character functions-Functions that accept character data as input and can return both character and numeric values. TRIM-Removes all specified characters from either the beginning or the ending of a string. Expression -A symbol that represents a quantity or a relationship between quantities Marge Hohly
19
Terminology cont. Single- row functions-Functions that operate on single rows only and return one result per row UPPER-Converts alpha characters to upper case Input-Raw data entered into the computer CONCAT-Concatenates the first character value to the second character value; equivalent to concatenation operator (||). Marge Hohly
20
Terminology cont. Output-Data that is processed into information
LOWER-Converts alpha character values to lowercase. LPAD-Pads the left side of a character, resulting in a right-justified value SUBSTR-Returns specific characters from character value starting at a specific character position and going specified character positions long Marge Hohly
21
Use Alias in Functions Aliases can be used in commands to replace column name etc. SELECT LOWER(SUBSTR(first_name,1,1)) ||LOWER(last_name) AS “User Name” FROM f_staffs; Marge Hohly
22
Terminology cont. REPLACE-Replaces a sequence of characters in a string with another set of characters. INSTR-Returns the numeric position of a named string. LENGTH-Returns the number of characters in the expression RPAD-Pads the right-hand side of a character, resulting in a left- justified value. Marge Hohly
23
Substitution Variables
To keep from running the same query multiple times and needing to edit it each time use a substitution variable APEX supports substitution variables Variable format :named_variable APEX will ask you for the value each time you run the query. The use of substitution variables, what they are for, how to use them. Do remind your students that the datatypes are as always important, and if we are using character strings or dates, they need to be enclosed in single quotes, exactly the same as if the values were hardcoded into the where-clause. The quotes ‘’ should be entered into the query for ease of use, but quotes can also be entered on the Variable Input pop-up. Be sure to demonstrate the effect of a char string where-clause substitution variable with and without quotes. Marge Hohly
24
Substitution Variables Examples
SELECT first_name, last_name, salary, department_id FROM employees WHERE department_id = 10; (and then 20, 30, 40,….) Rewrite using a substitution variable SELECT first_name, last_name, salary, department_id FROM employees WHERE department_id = :dept_id; SELECT * FROM employees WHERE last_name LIKE :l_name; Run with H% and %a% %s Marge Hohly
25
Single Row Functions Number Functions
ROUND rounds a value to specified position. TRUNC truncates a value to a specified position. MOD returns the remainder of a divide operation. Marge Hohly
26
Single Row Functions Number Functions
ROUND rounds a value to specified position. ROUND(column|expression, decimal places) Default is 0 decimals SELECT ROUND(45.927, 2), ROUND(45.927, 0), ROUND(45.927), ROUND(45.927, -1) FROM dual; Demo in APEX ROUND and TRUNC can be used with dates TRUNC default is zero decimals. If the number of decimal places is a positive number, the number is rounded to that number of decimal places. + to the right of decimal, - left of Decimal – ROUND: The syntax for the ROUND … Demonstrate the ROUND function. Practice using negative and zero values for ROUND. SELECT ROUND(( * 1.75),2) AS "Total" FROM DUAL; Results ROUND(45.927, 2) = 45.93 ROUND(45.927, 0) = 46 ROUND(45.927) = 46 ROUND(45.927, -1) = 50 Marge Hohly
27
Single Row Functions TRUNC(column|expression, decimal places)
TRUNC truncates a value to a specified position. TRUNC(column|expression, decimal places) SELECT TRUNC(45.927, 2),TRUNC(45.927, 0),TRUNC(45.927),TRUNC(45.927, -1) FROM dual; TRUNC(45.927, 2) = 45.92 TRUNC(45.927, 0) = 45 TRUNC(45.927) = 45 TRUNC(45.927, -1) = 40 If the number of decimal places is a negative number, numbers to the left of the decimal are rounded. Always rounds down. TRUNC(45.927, 2) = 45.92 TRUNC(45.927, 0) = 45 TRUNC(45.927) = 45 TRUNC(45.927, -1) = 40 Marge Hohly
28
Mod demo MOD(1st value, 2nd value)
MOD returns the remainder of a divide operation. MOD(1st value, 2nd value) The 1st value is divided by the 2nd value SELECT MOD(600, 500) FROM dual; MOD(dividend, divisor) = remainder SELECT last_name, salary, MOD(salary, 2) AS “Mod Demo” FROM f_staffs WHERE staff_type IN(‘Order Taker’, ‘Cook’, ‘Manager’); – MOD Ask students what the MOD of 100/25 is. 0 Ask students what the MOD of 100/30 is. 10 Ask students what the MOD of 18.5/3 is. .5 MOD( 1600 / 300) MOD(600, 500) = 100 Can be used to determine if number is odd or even. Marge Hohly
29
Single Row Functions Working with Dates
the default display and input format for any date is DD-MON-RR. For example: 12-OCT-05 (more on RR later) SYSDATE is a date function that returns the current database server date and time. the Oracle database stores dates in an internal numeric format. Which means arithmetic operations can be performed on dates. default date DD-MON-RR. Oracle dates are between 1/1/4712 B.C. and 12/31/9999 A.D. Stores year as a 4 digit value, 2 digit century, 2 digit year Run command. RR recognizes YY Marge Hohly
30
Date Functions Example
Marge Hohly
31
Examples SELECT SYSDATE FROM DUAL;
SELECT (SYSDATE - hire_date)/7 AS "No. of Weeks“ FROM employees; SELECT MONTHS_BETWEEN(SYSDATE, '01-Jan-87') AS "no. of months“ FROM dual; SELECT ROUND(MONTHS_BETWEEN(SYSDATE, '01-Jan-87'),2) AS "no. of months“ FROM dual; SELECT NEXT_DAY('01-Sep-95','Friday') FROM dual; /7 = number of weeks Notice functions are stacked up. SELECT employee_id, (end_date – start_date)/365 AS “Tenure in last job” From job_history; SELECT last_name, hire_date + 60 FROM employees; FROM job_history; Marge Hohly
32
Date Functions Functions Description months_between
# of months between 2 dates add_months Add calendar months to date next_day Next day of the date specified (like Friday) last_date Last day of month (date) ROUND Round date TRUNC Truncate date Marge Hohly
33
Single Row Functions Working with Dates (a few examples)
SELECT last_name, hire_date + 60 AS "Review Date“ FROM employees; SELECT last_name, (SYSDATE-hire_date)/7 FROM employees; SELECT order_no,amt_due,purch_date + 30 AS "Due Date“ FROM transactions; Demonstrate in APEX 3rd command does not run. The variables don’t exists. Marge Hohly
34
Single Row Functions Date Functions
MONTHS_BETWEEN returns the number of months between two dates. ADD_MONTHS adds a number of months to a date. NEXT_DAY returns the date of the next specified day of the week. LAST_DAY returns the date of the last day of the specified month. ROUND returns the date rounded to the unit specified. TRUNC returns the date truncated to the unit specified. Demo in APEX Marge Hohly
35
Single Row Functions Date Functions (a few examples) Functions Result
MONTHS_BETWEEN(’01-SEP-92’,’01-JUN-91’) 15 ADD_MONTHS (’11-JAN-94’,6) ’11-JUL-94’ NEXT_DAY(’01-SEP-95’,’FRIDAY’) ‘08-SEP-95’ LAST_DAY(’01-FEB-95’) ’28-FEB-95’ Demonstrate the SQL in APEX (using the DUAL table) Marge Hohly
36
Single Row Functions Date Functions (a few more examples)
Assume SYSDATE = ’25-JUL-95’ Function Result ROUND(SYSDATE,’MONTH’) ’01-AUG-95’ ROUND(SYSDATE,’YEAR’) ’01-JAN-96’ TRUNC(SYSDATE,’MONTH’) ’01-JUL-95’ TRUNC(SYSDATE,’YEAR’) ’01-JAN-95’ Demonstrate in SQL in APEX Marge Hohly
37
Date Types Section 2 In some cases, Oracle server uses data of one type where it expects data of a different data type. When this happens, Oracle server makes the conversion. The dictionary defines "implicit" as something that is "implied but not directly expressed" and explicit as "clearly formulated or defined.“ Thus, we will explicitly define data-type conversions to ensure the reliability of SQL statements. Marge Hohly
38
Data Types VARCHAR2: Used for character data of variable length, including numbers, special characters, and dashes. CHAR: Used for text and character data of fixed length, including numbers, dashes, and special characters. NUMBER: Used to store variable-length numeric data. No dashes, text, or other nonnumeric data are allowed. Currency is stored as a number data type. DATE: Used for date and time values. Internally, Oracle stores dates as numbers and by default DATE information is displayed as DD-MON-YY (for example, 16-OCT-07). Marge Hohly
39
Implicit Data Type Conversion
For assignments, the Oracle serve can automatically convert the following: From To VARCHAR2 or CHAR NUMBER DATE VARCHAR2 Explain that later in the course, they will learn more about SQL data types, but for now they will be using VARCHAR2, CHAR, NUMBER, and DATE. Marge Hohly
40
Explicit Type Conversion
TO_NUMBER TO_DATE CHARACTER NUMBER DATE TO_CHAR Formatting numbers, text, and dates in databases is done by using conversion functions. These functions are able to display numbers as Best to explicitly declare data types. Begin this lesson with a review question: How can we find out what the date will be exactly five months from today? Know this slide, test questions from this concept. Answer: SELECT SYSDATE, ADD_MONTHS(SYSDATE, 5) FROM DUAL; Marge Hohly
41
Using the TO_CHAR Function with Dates
The format model: TO_CHAR(date column name, ‘format model you specify’) Must be enclosed in single quotation marks and is case sensitive Can include any valid date format element Has an fm element to remove padded blanks or suppress leading zeros Is separated from the date value by a comma Marge Hohly
42
Using the TO_CHAR Function with Dates
Use sp to spell out a number Use th to have the number appear as an ordinal Use double quotation marks to add character strings to format models Marge Hohly
43
Elements of the Date Format Model
YYYY YEAR MM MONTH MON DY DAY DD Full year in numbers Year spelled out Two-digit value for month Full name of the month Three-letter abbreviation of the month Three-letter abbreviation of the day of the week Full name of the day of the week Numeric day of the month Marge Hohly
44
Date Conversion to Character Data
HH24:MI:SS AM DD “of” MONTH DDspth Ddspth ddspth DDD or DD or D 15:45:32 PM 12 of October FOURTEENTH Fourteenth Day of year, month or week Marge Hohly
45
Examples of Date formatting
Date conversion to character data June 19th, 2004 TO_CHAR(hire_date, 'Month ddth, YYYY') January 1, 2000 TO_CHAR(hire_date, 'fmMonth dd, YYYY') MAR 5, 2001 TO_CHAR(hire_date, 'fmMON dd, YYYY') June 17th Wednesday Nineteen Eighty-Seven TO_CHAR(hire_date, 'Month ddth Day YYYYSP') SELECT id, TO_CHAR(event_date, 'MONTH DD, YYYY') FROM d_events; returns: 100 MAY 14, 2004 105 APRIL 28, 2004 Marge Hohly
46
Examples Using the current SYSDATE display it in the following format
August 6th, 2004 August 06, 2004 AUG 6, 2004 August 6th, Friday, Two Thousand Four SELECT TO_CHAR(SYSDATE, 'fmMonth ddth, YYYY' ) FROM DUAL; returns: August 6th, 2004 SELECT TO_CHAR(SYSDATE, 'Month dd, YYYY' ) returns: August 06, 2004 SELECT TO_CHAR(SYSDATE, 'fmMON dd, YYYY' ) returns: AUG 6, 2004 SELECT TO_CHAR(SYSDATE, 'fmMonth ddth, Day, YYYY' ) returns: August 6th, Friday, Two Thousand Four Marge Hohly
47
Using Date Format SELECT employee_id, TO_CHAR(hire_date,'MM/YY') Month_Hired FROM employees WHERE last_name = 'Higgins'; EMPLOYEE_ID MONTH_HIRED 205 06/94 Illustrate this in HTML DB so they can see it in use. Marge Hohly
48
Elements of the Date Format Model
Time elements format the time portion of the date. Add character strings by enclosing them in double quotation marks. Number suffixes spell out numbers. HH24:MI:SS AM 15:45:32 PM DD “of” MONTH 12 of OCTOBER Date Format Elements – Time formats Ddspth fourteenth Marge Hohly
49
Using the TO_CHAR Function with Dates
SELECT last_name, TO_CHAR(hire_date, 'fmDD Month YYYY') AS HIREDATE FROM employees; LAST_NAME HIREDATE King 17 June 1987 Kochhar 21 September 1989 De Haan 13 January 1993 Whalen 17 September 1987 Higgins 7 June 1994 Gietz The TO_CHAR function with Dates Marge Hohly
50
Using the TO_CHAR Function with Numbers
TO_CHAR (number, ‘format_model’) These are some of the format elements you can use with the TO_CHAR function to display a number value as a character: 9 Represents a number Forces a zero to be displayed $ Places a floating dollar sign L Uses the floating local currency symbol . Prints a decimal point , Prints a thousand indicator B Display zero values as blanks not 0 The TO_CHAR Functions with Numbers B is leading zero B = Marge Hohly
51
Number conversions to Character (VARCHAR2)
Can you identify the format models used to produce the following output? $ 4,500 9,000.00 $ TO_CHAR(salary, '$ ') 4,500 TO_CHAR(salary, '9,999') 9, TO_CHAR(salary, '9,999.99') TO_CHAR(salary, ' ') SELECT TO_CHAR(cost, '$99,999') COST FROM d_events; Marge Hohly
52
Using the TO_CHAR Function with Numbers
SELECT TO_CHAR(salary, '$99,999.00') SALARY FROM employees WHERE last_name = 'Ernst‘; SALARY $6,000.00 Guidelines Marge Hohly
53
Using the TO_NUMBER and TO_DATE Functions
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 a fx modifier. This modifier specifies the exact matching for the character argument and date format model of a TO_DATE function The TO_NUMBER and TO_DATE functions SELECT TO_NUMBER(‘450’) AS “Number Change” FROM Dual; converts varchar2 to number SELECT TO_NUMBER(‘450', '9999') + 10 AS "Number Change" FROM Dual Note that format is to small and an error is returned in APEX and in SQL *Plus it would be #### indicating format to small for digit to be displayed. SELECT TO_NUMBER(‘450', '99') + 10 AS "Number Change" Once converted to either a date or number mathematical operations can occur See next slide to practice fx formatting. Marge Hohly
54
Using fx modifier Use the fx modifier to format dates exactly as follows June19 2004 July312004 Format your birth date use DUAL Example June 19, 1990 SELECT TO_DATE(‘October 18, 2011’, ‘Month dd, RRRR’) FROM DUAL; The fx format may require more practice. Remind students to think of fx as "format exact" so the fxdate of the format model must exactly match the format of the date being converted. Ask students to use the fx modifier to convert each of the following to the default date format. June19 2004 SELECT TO_DATE('June19 2004', 'fxMonthDD RRRR')AS Convert July312004 SELECT TO_DATE('July312004', 'fxMonthDDRRRR')AS Convert Using the DUAL table, ask students to format their birthday in five different ways. Remind students that they will first have to convert their "character" data to date data and then format it. If they were using a DATE data-type column from a table such as hire_date, the conversion TO_DATE before formatting would not be necessary. SELECT TO_CHAR(TO_DATE('June 19, 1990','Month dd, YYYY'), 'MON DD YYYY’) AS Birthday Marge Hohly
55
RR Date Format-dates over 2 centuries
Current Date Specified Date RR Format YY Format 1995 27-OCT-95 27-OCT-17 2017 1917 2008 2095 If the specified two-digit year is: 0-49 50-99 If two digits of the current year are: The return date is in the current century The return date is in the century before the current one The return date is in the century after the current one KNOW – Test questions Oracle database stores dates in an internal numeric format: century, year, month, day, hours, minutes, seconds. If Formatted YY or YYYY it returns the current century SELECT TO_CHAR(TO_DATE('15 JUNE 95', 'DD-MON-YY'), 'DD MON YYYY') FROM DUAL; SELECT TO_CHAR(TO_DATE(hire_date, 'DD-MON-YY'),'DD MON YYYY') FROM employees; SELECT hire_date, TO_CHAR(TO_DATE(hire_date, 'DD-MON-rr'),'DD MON YYYY') RR,TO_CHAR(TO_DATE(hire_date, 'DD-MON-yy'),'DD MON YYYY') YY Marge Hohly
56
RR or RRRR Simple Rules Marge Hohly
57
Example of RR Date Format
To find employees hired prior to 1990, use the RR format, which produces the same results whether the commands 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'); LAST_NAME TO_CHAR(HIRE_DATE,'DD-MON-YYYY') King 17-Jun-87 Kochhar 21-Sep-89 Whalen 17-Sep-87 SELECT last_name, hire_date, TO_CHAR(hire_date, ’ DD-Mon-RRRR') FROM employees WHERE TO_DATE(hire_date, 'dd-mon-RR') < '01 Jan 1999‘; SELECT last_name, hire_date, TO_CHAR(hire_date, 'DD-Mon-RRRR') WHERE TO_DATE(hire_date, 'dd-mon-RR') > '01 Jan 1999'; Returns 16 rows Now 20 rows were returned. Again, examine the format model in the WHERE clause. Using the YY format causes the date to default to the current century, and since we are in the 2000s, 01-JAN-90 is seen as 01-JAN Everyone was hired before that date, right? Ask students to research the "Millennium Bug" or "Y2K" and the concern people had about how databases recorded their information. Expect students to be a bit confused learning the RR and YY formats. Emphasize that the problem exists when character data such as 01-Jan-90 is being formatted into a default date format. Instead of using RR in the format model, YY is used. Because we are in the 21st century, the YY is interpreted in the current century as Provide additional practice by choosing a random date in either the 20th or 21st century, and ask students to provide the correct result. Marge Hohly
58
Try this SELECT last_name, hire_date, TO_CHAR(hire_date, 'DD-Mon-RRRR') FROM employees WHERE TO_DATE(hire_date, 'dd-mon-RR') < '01 Jan 1999‘; Marge Hohly
59
YY and RR SELECT TO_CHAR(TO_DATE(hire_date, 'DD-Mon-RR'),'DD Mon YYYY') AS "RR Example“ FROM employees; SELECT TO_CHAR(TO_DATE(hire_date, 'DD-Mon-YY'),'DD Mon YYYY') AS "YY Example“ FROM employees; YY Example 17 Jun Sep Jan 2093 RR Example 17 Jun Sep Jan 1993 The reason to TO_CHAR is used so the expression is to be able to display the full date 2087 not just 87. SELECT hire_date,TO_CHAR(TO_DATE(hire_date, 'DD-Mon-RR'),'DD Mon YYYY') AS "RR Example",TO_CHAR(TO_DATE(hire_date, 'DD-Mon-YY'),'DD Mon YYYY') AS "YY Example" FROM employees; Marge Hohly
60
Examples 2. Convert January 3, 2004, to the default date format 03-JAN-04. 4. Convert today's date to a format such as: "Today is the Twentieth of March, Two Thousand Four“ 8. Create one query that will convert 25-DEC-04 into each of the following (you will have to convert 25-DEC-04 to a date and then to character data): December 25th, 2004 DECEMBER 25TH, 2004 december 25th, 2004 2. SELECT TO_DATE('January 3, 2004', 'Month dd, YYYY')as "Date" FROM DUAL; 4. SELECT 'Today is the ' ||TO_CHAR(SYSDATE, 'Ddspth "of" Month, Yyyysp') 8. SELECT TO_CHAR(TO_DATE('25-DEC-04','dd-MON-yy'),'Month ddth, YYYY')Convert,TO_CHAR(TO_DATE('25-DEC-04','dd-MON-yy'),'MONTH DDth, YYYY')Convert,TO_CHAR(TO_DATE('25-DEC-04','dd-MON-yy'),'month ddth, YYYY')AS Convert Marge Hohly
61
Nested Functions Nesting is allowed to any depth
Evaluate from the inside out Marge Hohly
62
Run command and examine the nesting from the inner most to the outside.
SELECT TO_CHAR(NEXT_DAY(ADD_MONTHS(hire_date,6), 'FRIDAY'), 'fmDay, Month DDth, YYYY') AS "Next Evalution" From employees Where employee_id=100; SELECT hire_date, ADD_MONTHS(hire_date,6) "6 MONTH",NEXT_DAY(ADD_MONTHS(hire_date,6), ‘MONDAY') NEXT, TO_CHAR(NEXT_DAY(ADD_MONTHS(hire_date,6), ‘MONDAY'), 'fmDay, Month DDth, YYYY') AS "Next Evalution" Marge Hohly
63
Null Functions Null is unavailiable, unassigned, unknown, or inapplicable. NVL NVL2 NULLIF COALESCE Marge Hohly
64
NVL FUNCTION NVL function converts a null value to a date, a character, or a number. The data types of the null value column and the new value must be the same. NVL (value that may contain a null, value to replace the null) can be used to convert column values containing nulls to a number before doing calculations. When arithmetic calculation is performed with null, the result is null. Marge Hohly
65
NVL FUNCTION examples SELECT NVL(auth_expense_amt,0) FROM d_partners;
SELECT NVL(hire_date,'01-JAN-97') FROM employees; SELECT NVL(specialty,'None Yet') FROM d_partners; SELECT first_name, last_name,NVL(auth_expense_amt, 0) * 1.05 AS Expenses FROM D_Partners; SELECT NVL(comments, 'no comment') FROM D_PLAY_LIST_ITEMS; Marge Hohly
66
NVL2 FUNCTION NVL2 (expression 1 value that may contain a null, expression 2 value to return if expression 1 is not null, expression 3 value to replace if expression 1 is null) SELECT last_name, salary, NVL2(commission_pct, salary + (salary * commission_pct), salary) income FROM employees; The NVL2 sample code illustrates a SQL statement returning an employee's salary and income. For employees who work on commission, the income is equivalent to the salary plus the salary multiplied by the commission percentage. For those who do not work on commission, the income is equivalent to the salary. Marge Hohly
67
NULLIF FUNCTION NULLIF function compares two functions.
If they are equal, the function returns null. If they are not equal, the function returns the first expression. The NULLIF function is: NULLIF(expression 1, expression 2) SELECT first_name, LENGTH(first_name) "Expression 1",last_name, LENGTH(last_name) "Expression 2", NULLIF(LENGTH(first_name), LENGTH(last_name)) AS "Compare Them“ FROM D_PARTNERS; Try the example in APEX Marge Hohly
68
COALESCE FUNCTION The COALESCE function is an extension of the NVL function, except COALESCE can take multiple values. If the first expression is null, the function continues down the line until a not null expression is found. Returns the first not null expression If the first expression has a value, the function returns the first expression and the function stops. SELECT last_name, COALESCE(commission_pct, salary, 10) comm FROM employees ORDER BY commission_pct; Marge Hohly
69
Examples Section 2 Lesson 2
Not all Global Fast Foods staff members receive overtime pay. Instead of displaying a null value for these employees, replace null with zero. Include the employee's last name and overtime rate in the output. Label the overtime rate as "Overtime Status." Not all Global Fast Foods staff members have a manager. Create a query that displays the employee last name and 9999 in the manager ID column for these employees. 2. SELECT last_name,NVL(overtime_rate,0)AS "Overtime Status" FROM f_staffs; 4. SELECT last_name, NVL(manager_id, 9999) Marge Hohly
70
Conditional Expressions
Provide the use of IF-THEN-ELSE logic within a SQL statement Use two methods: CASE expressions DECODE function Section 2 Lesson 3 Marge Hohly
71
Note syntax of the case statement. Note example:
SELECT id, loc_type,rental_fee, CASE loc_type WHEN 'Private Home' THEN 'No Increase' WHEN 'Hotel' THEN 'Increase 5%' ELSE rental_fee END AS "Revised_Fees" FROM d_venues; If-Then-Else is not used in Sequel (SQL) it is used in PL SQL (PL Sequel), which is not this class but CIS 208A CASE statements are ANSI standard and work with other relational databases DECODE is Oracle Proprietary and works only with ORACLE Marge Hohly
72
CASE Function – when – then - else
Facilitates conditional inquiries by doing the work of an IF-THEN-ELSE statement: 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; In the preceding SQL statement, the value of JOB_ID is decoded. If JOB_ID is IT_PROG, the salary is increased by 10 %. or if ST_CLERK, the salary is increased by 15%,or if SA_REP, the salary is increased by 20%, or if none of these the salary is not revised. Marge Hohly
73
DECODE format DECODE (column1|expression, search1, result1, search2, result2,….., default) SELECT id, loc_type,rental_fee, DECODE(loc_type,’Private Home’, ‘No increase’, ’Hotel’,’Increase 5%’, rental_fee) AS “Revised_Fees” FROM d_venues; Marge Hohly
74
DECODE Function Facilitates conditional inquires by doing the work of a CASE or IF_THEN_ELSE statement: 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; In the preceding SQL statement, the value of JOB_ID is tested. If Job_id is IT_PROG, the salary is increased by 10% **Test question. If there is no default value then a NULL is returned. Students will have difficulty distinguishing between CASE and DECODE. The CASE expression is a more flexible version of the DECODE function. The CASE expression complies with ANSI SQL; DECODE is specific to Oracle syntax. Marge Hohly
75
DECODE Example SELECT last_name, salary, DECODE
(TRUNC(salary/2000, 0), 0,0.00, 1,0.09, 2,0.20, 3,0.30, 4,0.40, 5,0.42, 6,0.44, 0.45) TAX_RATE FROM employees WHERE department_id = 80; Monthly Salary Range Rate $0.00 – % $2, – 3, % $4, – 5, % $6, – 7, % $8, – 9, % $10, – 11, % $12, – 13, % $14, or greater 45% In this example, we determine the tax Marge Hohly
76
Practice 1. For each Global Fast Foods promotional menu, display the event name, and calculate the number of months between today and the ending date of the promotion. Round the months to a whole number. Label the column "Past Promos." 2. Use the Oracle database to write a query that returns the salary for employee 174 as: Ellen Abel earns $ monthly but wants $ Answers: 1. SELECT name,ROUND(MONTHS_BETWEEN(SYSDATE, end_date),0) AS "Past Promos" FROM f_promotional_menus; 2. SELECT INITCAP(first_name) ||' ' ||INITCAP(last_name)||' '||'earns'||TO_CHAR(salary, '$ ')||' ' ||'but wants ' ||TO_CHAR((salary ),'$ ') as "Wish Salary" FROM employees WHERE last_name LIKE 'Abel'; Marge Hohly
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.