chapter 8a relational set operators1 chapter 8a objectives: to learn • the relational set...
TRANSCRIPT
1
Chapter 8a
Objectives: to learn
• the relational set
operators – UNION,
– UNION ALL,
– INTERSECT, and
– MINUS
• How to create and use
Sequence objects as
an ‘autonumber’
• SQL functions to
manipulate dates,
strings, and other data
Outline
• Relational Set
Operators
• SEQUENCE Objects
• SQL Built-in Functions – Numeric
– String
– Date
– Misc
– Pseudo Columns
1Fall 2010 - CS275
Relational Set Operators
• Based on relational algebra/ set operations
• Work properly if relations are union-compatible
– Names of relation attributes must be the same and
their data types must be identical
• SQL-’99 ANSI Standard commands
– UNION
– INTERSECT
– MINUS (called ‘EXCEPT’ in the 99 standards)
• Some DMS’s may not implement these.
2Fall 2010 - CS275
UNION
• Combines tables eliminating duplicate rows.
• Can be used to unite more than two queriesSELECT CUS_LNAME, CUS_FNAME, CUS_INITIAL,
CUS_AREACODE, CUS_PHONE
FROM CUSTOMER
UNION
SELECT CUS_LNAME, CUS_FNAME,CUS_INITIAL,
CUS_AREACODE, CUS_PHONE
FROM CUSTOMER_2;
3Fall 2010 - CS275
UNION ALL
• Combines tables retaining duplicate rows.SELECT CUS_LNAME, CUS_FNAME, CUS_INITIAL,
CUS_AREACODE, CUS_PHONE
FROM CUSTOMER
UNION ALL
SELECT CUS_LNAME, CUS_FNAME, CUS_INITIAL,
CUS_AREACODE, CUS_PHONE
FROM CUSTOMER_2;
4Fall 2010 - CS275
2
INTERSECT
• Combines rows from two queries, returning only
the rows that appear in both sets.
• Example:SELECT CUS_LNAME, CUS_FNAME, CUS_INITIAL,
FROM CUSTOMER
INTERSECT
SELECT CUS_LNAME, CUS_FNAME, CUS_INITIAL,
CUS_AREACODE, CUS_PHONE
FROM CUSTOMER_2;
5Fall 2010 - CS275
INTERSECT
SELECT CUS_CODE
FROM CUSTOMER WHERE CUS_AREACODE = ‘615’
INTERSECT SELECT DISTINCT CUS_CODE
FROM CUSTOMER;
6Fall 2010 - CS275
Syntax Alternatives - Intersect
• Generalized Syntax:
Select <columns>
from t1 where t1.fieldA in (select t2.fieldA from t2);
• Example: solving the previous problem:
Select cus_code
from customer
where cus_areacode = ‘615’ and
cus-code in (select distinct cus_code from
Invoice)
7Fall 2010 - CS275
MINUS
• Combines rows from two queries, returning only
the rows that appear in the first set but not in the
second
– Example:
SELECT CUS_LNAME, CUS_FNAME, CUS_INITIAL,
CUS_AREACODE,
FROM CUSTOMER
MINUS
SELECT CUS_LNAME, CUS_FNAME, CUS_INITIAL,
CUS_AREACODE,
FROM CUSTOMER_2
8Fall 2010 - CS275
3
MINUS
9
Example reversing the tables:SELECT CUS_LNAME, CUS_FNAME, CUS_INITIAL,
CUS_AREACODE, CUS_PHONE FROM CUSTOMER_2MINUSSELECT CUS_LNAME, CUS_FNAME, CUS_INITIAL,
CUS_AREACODE, CUS_PHONE FROM CUSTOMER
Fall 2010 - CS275
Syntax Alternatives -Minus
• Generalized Syntax
Select <columns> from t1 where t1.key not in (select
t2.key from t2);
• Example starting with previous problem, but using
another table(non-union compatiable):Select cus_code from customer
where cus_areacode = ‘615’ and cus_code not in
(select distinct cus_code from Invoice);
• IN and NOT IN subqueries can be used in place of INTERSECT & MINUS
10Fall 2010 - CS275
Oracle Sequences
• Sequence Numbers: allows establishing an
“autonumber” sequence
• Oracle sequences
– Independent object in the database
– Are named and used anywhere a numeric value is
expected
– Not tied to a table or column
– Generates new numeric values that can be
assigned to any column in any table
– A named sequence can be created and deleted at
any time11Fall 2010 - CS275
Oracle Sequence
• Create sequence <seq_name> start with <n>
Increment by <n>;
– Examples:
Create sequence cust_code start with 100
increment by 1;
Create sequence product_num NOCACHE;
• Viewing your sequences
Select * from user_sequences;
12Fall 2010 - CS275
4
Oracle Sequence
Create sequence cus_code_seq start with 20010
nocache;
Create sequence inv_number_seq start with 4010
nocache;
13Fall 2010 - CS275
Oracle Sequence
• Sequence numbers are used via a keyword– NEXTVAL
• used to generate a new number
• Often used as a primary key for a table row
• Example:
Insert into table invoice values
(inv_sequence.NEXTVAL, 20010, sysdate);
– CURRVAL• Used to retrieve the current value of the sequence.
• Cannot directly retrieve attributes from a sequence.
• Example:
Select inv_sequence.CURRVAL from dual;
14Fall 2010 - CS275
Oracle Sequences
Insert into customer values ( cus_code_seq.nextval, ‘Connery’, ‘Sean’, NULL, ‘615’, ‘898-2007’, 0.00);
Insert into Invoice values ( inv_number_seq.nextval, 20010, sysdate);
Insert into Line values (inv_number_seq.currval, 1, ’13-Q2/P2’, 1, 14.99);
Insert into line values( inv_number_seq.currval, 2,
‘23109-HB’, 1, 9.95);
15
inserting a series of rows with auto sequence
numbers.
Fall 2010 - CS275
SQL (non-aggregate) Functions
• Functions manipulate data items and return a
single result. (i.e. SQL functions are similar to
functions in programming languages.)
• Oracle has more than 150 different functions. (See
link on our resource page to the Oracle
documentation )
• Functions use numerical, date, or string values, which may be part of a command or a table attribute.
• The Function may appear anywhere in an SQL statement
16Fall 2010 - CS275
5
Numeric Functions
• Grouped in different
ways
– Algebraic,
trigonometric,
logarithmic, etc.
• Do not confuse with
aggregate functions
– Aggregate functions
operate over sets
– Numeric functions
operate over single row
17Fall 2010 - CS275
SQL Functions - Numeric
ABS(n) -Absolute value of n
CEIL(n) -Smallest integer greater or equal to n
FLOOR(n) -Largest integer equal to or less than n
MOD(m,n) -Remainder of m divided by n
POWER(m,n) -m raised to the nth power
ROUND(n,[m]) -n rounded to m decimal places.
SIGN(n) -If n<0 returns -1, if n= 0 returns 0, if
n>0 returns 1
SQRT(n) -Square root of n, if n<0 returns NULL
TRUNC(c[m]) -n truncated to m decimal places
18Fall 2010 - CS275
String Functions
19
• The most used functions are the String functions
• Examples:Upper/LowerSubstrLength|| - or Concat
Fall 2010 - CS275
SQL Functions - String
ASCII(str)
CHR(n)
CONCAT(str1,str2)
INITCAP(str)
INSTR(str1,str2[,n[m]])
SUBSTR(str, start, length)
LENGTH(str)
LOWER(str)
L/RPAD(str1,n[,str2])
– Returns ASCII value of first character in str
– Character with ASCII value n
– Returns the combined data items.
– Capitalizes the first letter of each word
– Returns the position of the mthoccurrence
of str2, begins search at position n.
– Returns substring of str
– Returns the length of str
– Forces all letters to lower case
– Left or Right pads str1 to length n with
sequence of characters in str2 (if
unspecified, pads with blanks)
20Fall 2010 - CS275
6
SQL Functions – String
L/RTRIM(str,set)
REPLACE(str,’literal1’,’literal2’)
SOUNDEX(str)
SUBSTR(str,m[,n])
TRANSLATE(str,frm,to)
UPPER(str)
USERENV(str)
– Removes characters starting from the Left or
Right in str up to the first character not in
set.
– Search str for 1st string and replace w/2nd
string. Similar to translate.
– Returns a str value representing the sound of
the word(s) in str.
– Returns substring of str, beginning at
character m, for length of n.
– str is translated from the character set frm
to the character set to.
– Forces all letters to upper case.
– Returns user information for writing audit
trails.21Fall 2010 - CS275
SQL Functions – Date & Time
• All SQL-standard DBMSs support date and time functions
• Date functions take one parameter
• Commonly used Functions:
22
ADD_MONTHS(d,n)
LAST_DAY(d)
MONTHS_BETWEEN(d,e)
NEW_TIME(d,a,b)
NEXT_DAY(d,char)
TRUNC(date)
– Date d plus n months
– Date of last day of month containing d
– Number of months between dates d & e
– Date and time in timezone b when d is
from timezone a.
– Date of first day of week named by char
=> d
– Date with time of day removed. Fall 2010 - CS275
SQL Functions - Data Conversions
CHARTOROWID(char)
HEXTORAW(char)
RAWTOHEX(raw)
ROWIDTOCHAR(rowid)
TO_CHAR(expr[,fmt])
TO_DATE(char[,fmt])
TO_DATE(n, fmt)
TO_NUMBER(char)
– Converts char to a row ID
– Converts char, which must contain a
hexadecimal number to a binary value
– Converts raw to char value containing a
hex number.
– Converts a row ID to a char value
– Converts expr, a number or date value to
a char value. Format may be used to
convert dates.
– Converts from char value to a date value.
fmt specifies the format of the parameter
char
– Converts a number into a date
– Converts a char value to a number.
23Fall 2010 - CS275
Data Conversion Examples
24
TO_DATE :using character
formats to return a date.
TO_CHAR: using a date and
returning pieces of the date
as character values.
Fall 2010 - CS275
7
Data Conversion Examples
25
TO_CHAR: converting a number to a
character string
TO_NUMBER: converting a character
string to a number
NVL: converts a null to a string
DECODE: returns associated value
when matched or a default value
Fall 2010 - CS275
SQL Functions - Miscellaneous
• Misc. Functions- data type on item returned is variable
DECODE (expr, search1, return1, search2, return2,…[default])
If expr equals any search, returns the
following return;
if not, returns default
DUMP (expr[, radix[,start-positions[,bytes]]])
Display the contents of internal data areas
GREATEST (expr,expr,..) Returns greatest of a list of values
LEAST (expr,expr,…) Returns the least of a list of values
NVL (expr1,expr2) If expr1 is null, returns expr2; if expr1 is not
null, returns expr1
VSIZE (expr) Returns the number of bytes in ORACLE’s
internal representation of expr
26Fall 2010 - CS275
SQL Functions -Pseudo-Columns
Level - 1 for root node, 2 for child - used in
..Select...Connect By
Null - Returns a null value - used in Insert
statements for blank data
RowID - ID for each row in a table
RowNum - Order in which the row was extracted
Sysdate - Current date and time
UID - User ID
USER - Name of current user (Login name)
27Fall 2010 - CS275
Chapter 8A Summary
• Relational set operators combine output of two
queries to generate new relation
• Set operations using the key words UNION,
UNION ALL, INTERSECT, and MINUS are part of
the new SQL-’99 extensions.
• Oracle sequences may be used to generate values
to be assigned to a record
• SQL functions are used to extract or transform
data
• SQL has Numeric, String (Character), Date,
Misc./Conversion functions, and Pseudo columns28
Fall 2010 - CS275