Professional Documents
Culture Documents
After completion of this chapter you will be able to: Explain the purpose of SQL Explain the concept of NULL in SQL Query the database by simple select statements Use different operators in SQL Explain the utility of iSQL *Plus Use iSQL*Plus Use order by and case expressions in SQL
Introduction
SQL is the language used to access the data and structures within a relational database. Most RDBMS vendors have a similar set of extensions or allow SQL statements to be embedded within a normal development package such as Visual Basic or C++.
Features of SQL
It is meant to be an English like language It is non-procedural. When you query data, all the rows affected by your statement are dealt with in one go as a set; they are not dealt with separately. The work area that holds the set is known as a CURSOR.
Datatypes
Each literal or column value manipulated by Oracle has a data type. A value's data type associates a fixed set of properties with the value. These properties cause Oracle to treat values of one data type differently from values of another. For example, you can add values of NUMBER datatype, but not values of RAW data type.
Nulls
If a column in a row has no value, then column is said to be null, or to contain a null. Nulls can appear in columns of any datatype that are not restricted by NOT NULL or PRIMARY KEY constraints. Use a null when the actual value is not known or when a value would not be meaningful.
Default Columns Headings In iSQL *Plus default heading is upper case and center justified. In SQL *Plus headings are displayed in uppercase. Character and date columns headings are left justified whereas number headings are right justified.
Arithmetic Operators
Operator Precedence 1. If an arithmetic expression contains more than one operator, multiplication and division are evaluated first. If operators within an expression are of same priority, then evaluation is done from left to right. You can use parentheses to force the expression within parentheses to be evaluated first.
2.
3.
Columns ALIAS
Alias is a way of giving a temporary name to something with the scope of the SQL statement. A column alias is often used to give a nice name to a virtual or calculated column. Historically, the column alias comes immediately after the column specification, separated only by whitespace as follows: Select SAL*12 ANNUAL_SALARY, ENAME from EMP;
Concatenation Operator
The concatenation operator '||' manipulates character strings. SELECT 'Name is ' || ename as "Name" FROM emp;
14 rows selected
Duplicate Rows
To eliminate duplicate rows from the result we have to include distinct keyword immediately after the select keyword. Select the following query shows all the duplicate department number from the emp table: Select deptno from emp;
14 rows selected
What is iSQL*Plus?
iSQL*Plus is a browser-based interface to SQL*Plus. iSQL*Plus enables you to use a web browser to connect to Oracle9i and perform the same actions as you would through the command line version of SQL*Plus
2. 3. 4. 5.
Each successful login is uniquely identified, so you can have multiple iSQL*Plus sessions running from the same machine, or from multiple client machines. Enter your Username, Password and Connection Identifier. Select the Privilege level you want to use to connect to Oracle9i. Click the Log In button. The iSQL*Plus Work screen is displayed.
Login Screen
The WHERE clause is used to specify which rows of data are to be displayed when using a select statement.
Compound Conditions
The AND operator means that every condition must be true in order for the data to be displayed. Select cust_name, balance, credit_limit from accounts where balance > credit_limit and zip = 4000; This means that both the credit limit must be exceeded and also the customers zip code must be '4000'. The OR operator joins two or more conditions and returns a row if any of the listed conditions is true. Select cust_name, balance, credit_limit from accounts where balance > credit_limit or zip = 4000; This means that either the credit limit must be exceeded or the customer zip code = '4000'.
LIKE Operator
The LIKE operator is used when we want to select rows to display that are similar to another field or constant. Select ename from emp where ename like 'S%'; In the above example we will select all the employees where the ename begins with the letter 'S'. The '%' is referred to as a wildcard. The remaining characters of the ename can consist of any other characters and the row will be returned in the query.
IN Operator
The IN operator can be used in some instances instead of the OR operator. Select ename, sal from emp where ename in ('SMITH','ANDREWS','GREEN');
BETWEEN Operator
The BETWEEN operator can be seen as an extension of the IN operator. For example: Select cust_id, cust_name, date_opened from customers where date_opened BETWEEN '01-JAN-90' and '31-DEC-90';
Precedence of Operators
ORDER BY Clause ORDER BY clause is used to order the rows selected by a query. Without an ORDER BY clause, it is not guaranteed that the same query executed more than once will retrieve rows in the same order. The clause specifies either expressions or positions or aliases of expressions in the select list of the statement. Oracle first sorts rows based on their values for the first expression. Rows with the same value for the first expression are then sorted based on their values for the second expression, and so on. Oracle sorts nulls following all others in ascending order and preceding all others in descending order. To select the employees from EMP ordered first by ascending department number and then by descending salary, issue the following statement: SELECT ename, deptno, sal FROM emp ORDER BY deptno ASC, sal DESC;
CASE Expressions
CASE expressions let you use IF ... THEN ... ELSE logic in SQL statements without having to invoke procedures. The syntax is: CASE expr WHEN comparison_expr1 THEN return_expr1 [WHEN comparison_expr2 THEN return_expr2 WHEN comparison_exprn THEN return_exprn ELSE else_expr] END In a simple CASE expression, Oracle searches for the first WHEN ... THEN pair for which expr is equal to comparison_expr and returns return_expr. If none of the WHEN ... THEN pairs meet this condition, and an ELSE clause exists, then Oracle returns else_expr. Otherwise, Oracle returns null.
14 rows selected
Objectives
After completion of this chapter you will be able to: Create tables in Oracle Explain different datatypes of Oracle Create tables with constraints and comments Rename a table Alter and Drop tables Put data into a table Use datetime datatypes of Oracle Use simple DML commands Use simple TCL commands
Creating Tables
The general syntax for Create Table command is: CREATE TABLE [schema.]table ( { column datatype [DEFAULT expr] [column_constraint] ... | table_constraint} [, { column datatype [DEFAULT expr] [column_constraint] ... | table_constraint} ]...) [AS subquery]
Datatypes Revisited
Each literal or column value manipulated by Oracle has a datatype. A value's datatype associates a fixed set of properties with the value. These properties cause Oracle to treat values of one datatype differently from values of another.
Character Datatypes
Character datatypes store character (alphanumeric) data-words and free-form text in the database. Oracle supports both single-byte and multibyte character sets. These datatypes are used for character data: CHAR Datatype NCHAR Datatype NVARCHAR2 Datatype VARCHAR2 Datatype
Number Datatype The NUMBER datatype stores zero, positive and negative fixed and floating-point numbers with magnitudes between 1.0 x 10-130 and 9.9...9 x 10125 (38 nines followed by 88 zeroes) with 38 digits of precision.
LONG Datatype
LONG columns store variable length character strings containing up to 2 gigabytes, or 2311 bytes. LONG columns have many of the characteristics of VARCHAR2 columns. You can use LONG columns to store long text strings. You can reference LONG columns in SQL statements in these places: SELECT lists SET clauses of UPDATE statements VALUES clauses of INSERT statements
DATE Datatype
The DATE datatype stores date and time information. Although date and time information can be represented in both character and number datatypes, the DATE datatype has special associated properties. For each DATE value, Oracle stores the following information: century, year, month, date, hour, minute, and second. You can specify a date value as a literal, or you can convert a character or numeric value to a date value with the TO_DATE function.
TIMESTAMP Datatype
The TIMESTAMP datatype is an extension of the DATE datatype. It stores the year, month, and day of the DATE datatype, plus hour, minute, and second values. Specify the TIMESTAMP datatype as follows: TIMESTAMP [ (fractional_seconds_precision)] where fractional_seconds_precision optionally specifies the number of digits in the fractional part of the SECOND datetime field and can be a number in the range 0 to 9. The default is 6.
TIMESTAMP WITH TIME ZONE Datatype contd.. Two TIMESTAMP WITH TIME ZONE values are considered identical if they represent the same instant in UTC, regardless of the TIME ZONE offsets stored in the data. For example: TIMESTAMP '1999-04-15 8:00:00 -8:00' is the same as TIMESTAMP '1999-04-15 11:00:00 -5:00' That is, 8:00 a.m. Pacific Standard Time is the same as 11:00 a.m. Eastern Standard Time. TIMESTAMP WITH LOCAL TIME ZONE Datatype TIMESTAMP WITH LOCAL TIME ZONE is another variant of TIMESTAMP that includes a time zone displacement in its value. When users retrieve the data, Oracle returns it in the users' local session time zone. The time zone displacement is the difference (in hours and minutes) between local time and UTC (Coordinated Universal Time--formerly Greenwich Mean Time). Specify the TIMESTAMP WITH LOCAL TIME ZONE datatype as follows: TIMESTAMP [ (fractional_seconds_precision) ] WITH LOCAL TIME ZONE
LOBs
CLOB: A character large object containing single-byte characters. Variable-width character sets are not supported. Maximum size is 4 gigabytes. NCLOB: A character large object containing fixed-width multibyte characters. Variablewidth character sets are not supported. Maximum size is 4 gigabytes. Stores national character set data. BLOB: A binary large object. Maximum size is 4 gigabytes. BFILE: Contains a locator to a large binary file stored outside the database. Enables byte stream I/O access to external LOBs residing on the database server. Maximum size is 4 gigabytes.
ROWID
ROWID Hexadecimal string representing the unique address of a row in its table. This datatype is primarily for values returned by the ROWID pseudocolumn. Each row in the database has an address of the type Data Object Number.Relative File Number.Block Number.Slot Number: Data Object Number: Assigned to each data object (table, index, and so on) when it is created and is a unique number. Relative File Number: Assigned for each file in a tablespace relative to that tablespace. Block Number: Represents the data block address of the database block containing the row. Slot Number: Identifies the position of the row in the block.
Constraint
Constraints are used to enforce table rules and prevent data dependent deletion (enforce database integrity). You may also use them to enforce business rules. Table level constraints go after the last column definition. Table level constraints are normally used (and must be used) for compound (multi column) foreign and prime key definitions. You may omit the CONSTRAINT keyword and constraint name if you wish but you will then have no easy way of enabling / disabling the constraint without deleting the table and rebuilding it.
Comment
It is possible to record a description or comment against a newly created or existing table or individual column by using the COMMENT command. The comment command writes your table / column description into the data dictionary. You can query column comments by selecting against dictionary views ALL_COL_COMMENTS and USER_COL_COMMENTS.
You can modify a table as follows: Add new columns Modify existing columns You cannot delete an existing column
An example of adding a column to a table is given below: ALTER TABLE BOOK ADD (REVIEW VARCHAR2(200)) If we want to add a constraint to our new column we can use the following ALTER statement:ALTER TABLE BOOK MODIFY (REVIEW NOT NULL)
Since full-table scans and index fast full scans read all data blocks up to the high-water mark, full-scan performance after a DELETE will not improve; after a TRUNCATE, it will be very fast. TRUNCATE does not fire any DELETE triggers. There is no object privilege that can be granted to allow a user to truncate another user's table. The DROP ANY TABLE system privilege is required to truncate a table in another schema. When a table is truncated, the storage for the table and all indexes can be reset back to the initial size. A DELETE will never shrink the size of a table or its indexes. You cannot truncate the parent table from an enabled referential integrity constraint. You must first disable the foreign key constraints that reference the parent table, and then you can truncate the parent table.
Inserting New Rows into a Table We insert new rows into a table with the INSERT INTO command. A simple example is given below. INSERT INTO SECTION VALUES (2, 'Computing', 0) The INSERT INTO command is followed by the name of the table, this in turn is followed by the VALUES keyword which denotes the start of the value list. The value list comprises all the values to insert into the specified columns.
The general syntax of the Update command is: UPDATE [schema.]{table | view | subquery} SET { (column [, column] ...) = (subquery) | column = { expr | (subquery) } } [, { (column [, column] ...) = (subquery) | column = { expr | (subquery) } } ] ... [WHERE condition]
Transactions
A transaction is a unit of work. What the unit is will depend on your application but generally it defines some sequence of statements that accomplish something both useful and atomic. Transactions are made up of any number of DML commands (commands that update database data). SELECT statements do not effect the status of a transaction but DDL commands do. Any DDL command will implicitly save all unsaved updates to the database so don't mix these command types together as you will find it difficult to exercise any transactional control.
Objectives
After completion of this chapter you will be able to: Explain different types of functions of Oracle Explain and Use format model Use functions in SQL
Introduction
A SQL function manipulates data items and returns a result. SQL functions are of these general types: Single-row (or scalar) functions Group (or aggregate) functions
The two types of SQL functions differ in the number of rows upon which they act. A single-row function returns a single result row for every row of a queried table or view; a group function returns a single result row for a group of queried rows.
INITCAP
Syntax: Initcap(Char) Purpose: Returns char, with the first letter of each word in uppercase, all other letters in lowercase. Words are delimited by white space or characters that are not alphanumeric.
LOWER
Syntax: Lower(Char) Purpose: Returns char, with all letters lowercase. The return value has the same datatype as the argument char (CHAR or VARCHAR2).
UPPER
Syntax: UPPER(char) Purpose: Returns char, with all letters uppercase. The return value has the same datatype as the argument char.
LPAD
Syntax: LPAD(char1, n ,char2) Purpose: Returns char1, left-padded to length n with the sequence of characters in char2; char2 defaults to a single blank. If char1 is longer than n, this function returns the portion of char1 that fits in n. The argument n is the total length of the return value as it is displayed on your terminal screen.
LTRIM
Syntax: LTRIM(char [,set]) Purpose: Removes characters from the left of char, with all the leftmost characters that appear in set removed; set defaults to a single blank. Oracle begins scanning char from its first character and removes all characters that appear in set until reaching a character not in set and then returns the result.
REPLACE
Syntax: REPLACE(char,search_string[,replacement_string]) Purpose: Returns char with every occurrence of search_string replaced with replacement_string. If replacement_string is omitted or null, all occurrences of search_string are removed. If search_string is null, char is returned.
RPAD
Syntax: RPAD(char1, n [,char2]) Purpose: Returns char1, right-padded to length n with char2, replicated as many times as necessary; char2 defaults to a single blank. If char1 is longer than n, this function returns the portion of char1 that fits in n. The argument n is the total length of the return value as it is displayed on your terminal screen.
RTRIM
Syntax: RTRIM(char [,set] Purpose: Returns char, with all the rightmost characters that appear in set removed; set defaults to a single blank. RTRIM works similarly to LTRIM.
SUBSTR
Syntax: SUBSTR(char, m [,n]) Purpose: Returns a portion of char, beginning at character m, n characters long. If m is 0, it is treated as 1. If m is positive, Oracle counts from the beginning of char to find the first character. If m is negative, Oracle counts backwards from the end of char. If n is omitted, Oracle returns all characters to the end of char. If n is less than 1, a null is returned. Floating-point numbers passed as arguments to substr are automatically converted to integers.
SOUNDEX
select * from weather where soundex(city) = soundex('sidney'); CITY TEMPERATURE HUMIDITY CONDITION ------------------------------------SYDNEY 29 12 SNOW
INSTR
Syntax: INSTR (char1,char2 [,n[,m]]) Purpose: Searches char1 beginning with its nth character for the mth occurrence of char2 and returns the position of the character in char1 that is the first character of this occurrence. If n is negative, Oracle counts and searches backward from the end of char1. The value of m must be positive. The default values of both n and m are 1, meaning Oracle begins searching at the first character of char1 for the first occurrence of char2. The return value is relative to the beginning of char1, regardless of the value of n, and is expressed in characters. If the search is unsuccessful (if char2 does not appear m times after the nth character of char1) the return value is 0.
LENGTH
Syntax: LENGTH(char) Purpose: Returns the length of char in characters. If char has datatype CHAR, the length includes all trailing blanks. If char is null, this function returns null.
Date Functions
Date functions operate on values of the DATE datatype. All date functions return a value of DATE datatype, except the MONTHS_BETWEEN function, which returns a number.
ADD_MONTHS
Syntax: ADD_MONTHS(d,n) Purpose: Returns the date d plus n months. The argument n can be any integer. If d is the last day of the month or if the resulting month has fewer days than the day component of d, then the result is the last day of the resulting month. Otherwise, the result has the same day component as d.
LAST_DAY
Syntax: LAST_DAY(d) Purpose: Returns the date of the last day of the month that contains d. You might use this function to determine how many days are left in the current month.
MONTHS_BETWEEN
Syntax: MONTHS_BETWEEN(d1, d2) Purpose: Returns number of months between dates d1 and d2. If d1 is later than d2, result is positive; if earlier, negative. If d1 and d2 are either the same days of the month or both last days of months, the result is always an integer; otherwise Oracle calculates the fractional portion of the result based on a 31-day month and considers the difference in time components of d1 and d2.
NEXT_DAY
Syntax: NEXT_DAY(d, char) Purpose: Returns the date of the first weekday named by char that is later than the date d. The argument char must be a day of the week in your session's date language-either the full name or the abbreviation. The minimum number of letters required is the number of letters in the abbreviated version; any characters immediately following the valid abbreviation are ignored. The return value has the same hours, minutes, and seconds component as the argument d.
SYSDATE
Syntax: SYSDATE Purpose: Returns the current date and time. Requires no arguments. In distributed SQL statements, this function returns the date and time on your local database. You cannot use this function in the condition of a CHECK constraint.
Number Functions
Number functions accept numeric input and return numeric values. This section lists the SQL number functions. Most of these functions return values that are accurate to 38 decimal digits.
ABS
Syntax: ABS(n) Purpose: Returns the absolute value of n.
CEIL
Syntax: CEIL(n) Purpose: Returns smallest integer greater than or equal to n.
COS
Syntax: COS(n) Purpose: Returns the cosine of n (an angle expressed in radians).
COSH
Syntax: COSH(n) Purpose: Returns the hyperbolic cosine of n.
EXP
Syntax: EXP(n) Purpose: Returns e raised to the nth power; e = 2.71828183 ...
FLOOR
Syntax: FLOOR(n) Purpose: Returns largest integer equal to or less than n.
LN
Syntax: LN(n) Purpose: Returns the natural logarithm of n, where n is greater than 0.
LOG
Syntax: LOG(m,n) Purpose: Returns the logarithm, base m, of n. The base m can be any positive number other than 0 or 1 and n can be any positive number.
MOD
Syntax: MOD(m,n) Purpose: Returns remainder of m divided by n. Returns m if n is 0.
POWER
Syntax: POWER(m,n) Purpose: Returns m raised to the nth power. The base m and the exponent n can be any numbers, but if m is negative, n must be an integer.
SIGN
Syntax: SIGN(n) Purpose: If n<0, the function returns -1; if n=0, the function returns 0; if n>0, the function returns 1.
SIN
Syntax: SIN(n) Purpose: Returns the sine of n (an angle expressed in radians).
SINH
Syntax: SINH(n) Purpose: Returns the hyperbolic sine of n.
SQRT
Syntax: SQRT(n) Purpose: Returns square root of n. The value n cannot be negative. SQRT returns a "real" result.
TAN
Syntax: TAN(n) Purpose: Returns the tangent of n (an angle expressed in radians).
TRUNC
Syntax: TRUNC(n[,m]) Purpose: Returns n truncated to m decimal places; if m is omitted, to 0 places. m can be negative to truncate (make zero) m digits left of the decimal point.
In case of Date
ROUND Syntax: ROUND(d[,fmt]) Purpose: Returns d rounded to the unit specified by the format model fmt. If you omit fmt, d is rounded to the nearest day..
TRUNC
Syntax: TRUNC(d,[fmt]) Purpose: Returns d with the time portion of the day truncated to the unit specified by the format model fmt. If you omit fmt, d is truncated to the nearest day.
Data Conversion
ORACLE supports both implicit and explicit conversion of values from one datatype to another. In this statement, ORACLE implicitly converts '12-MAR-1993' to a DATE value using the default date format 'DD-MON-YYYY': SELECT ename FROM emp WHERE hiredate = '12-MAR-1993' You can also explicitly specify datatype conversions using SQL conversion functions.
In a number format element of a TO\_CHAR function, this modifier suppresses blanks added to the left of the number in the result to right-justify it in the output buffer. Without FM, the result is always right justified in the buffer, resulting in blank-padding to the left of the number.
FX - ''Format Exact''
This modifier specifies exact matching for the character argument and date format model of a TO\_DATE function. Punctuation and quoted text in the character argument must exactly match (except for case) the corresponding parts of the format model. Without FX, punctuation and quoted text in the character argument need only match the length and position of the corresponding parts of the format model. The character argument cannot have extra blanks. Without FX, ORACLE ignores extra blanks. Numeric data in the character argument must have the same number of digits as the corresponding element in the format model. Without FX, numbers in the character argument can omit leading zeroes. When FX is enabled, you can disable this check for leading zeros by using the FM modifier as well.
Group Functions
Unlike single-row functions, group functions operate on sets of rows to give one result per group. These sets may be the whole table or the table split into groups. Many group functions accept these options: DISTINCT: This option causes a group function to consider only distinct values of the argument expression. ALL: This option causes a group function to consider all values including all duplicates
AVG
Syntax: AVG([DISTINCT|ALL] n) Purpose: Returns average value of n.
COUNT
Syntax: COUNT({* | [DISTINCT|ALL] expr}) Purpose: Returns the number of rows in the query. If you specify expr, this function returns rows where expr is not null. You can count either all rows, or only distinct values of expr. If you specify the asterisk (*), this function returns all rows, including duplicates and nulls.
MAX
Syntax: MAX([DISTINCT|ALL] expr) Purpose: Returns maximum value of expr.
MIN
Syntax: MIN([DISTINCT|ALL] expr) Purpose: Returns minimum value of expr.
STDDEV
Syntax: STDDEV([DISTINCT|ALL] x) Purpose: Returns standard deviation of x, a number. Oracle calculates the standard deviation as the square root of the variance defined for the VARIANCE group function.
SUM
Syntax: SUM([DISTINCT|ALL] n) Purpose: Returns sum of values of n.
VARIANCE
Syntax: VARIANCE([DISTINCT|ALL]x) Purpose: Returns variance of x, a number.
NVL
Syntax: NVL(expr1, expr2) If expr1 is null, NVL returns expr2. If expr1 is not null, NVL returns expr1. The arguments expr1 and expr2 can have any datatype. If their datatypes are different, Oracle converts expr2 to the datatype of expr1 before comparing them. The datatype of the return value is always the same as the datatype of expr1, unless expr1 is character data, in which case the return value's datatype is VARCHAR2 and is in the character set of expr1.
NVL2
Synyax: NVL2(expr1, expr2, expr3) If expr1 is not null, NVL2 returns expr2. If expr1 is null, NVL2 returns expr3. The argument expr1 can have any datatype. The arguments expr2 and expr3 can have any datatypes except LONG. If the datatypes of expr2 and expr3 are different, Oracle converts expr3 to the datatype of expr2 before comparing them unless expr3 is a null constant. In that case, a datatype conversion is not necessary. The datatype of the return value is always the same as the datatype of expr2, unless expr2 is character data, in which case the return value's datatype is VARCHAR2.
COALESCE
Syntax: Coalesce(expr1, expr2, .. exprn) The COALESCE function returns the first non-null expr in the expression list. At least one expr must not be the literal NULL. If all occurrences of expr evaluate to null, the function returns null. NULLIF Syntax: Nullif(expr1, expr2) The NULLIF function compares expr1 and expr2. If they are equal, the function returns null. If they are not equal, the function returns expr1. You cannot specify the literal NULL for expr1.
DECODE
The DECODE function decodes an expression in a way similar to the IF-THEN-ELSE logic used in various languages. The DECODE function decodes expression after comparing it to each search value. If the expression is the same as search, result is returned.
Objectives
After completion of this chapter you will be able to: Use group by clause Use for update clause Use hierarchical queries Use set operators
HAVING Clause
HAVING clause is used to restrict which groups of rows defined by the GROUP BY clause are returned by the query. Oracle processes the WHERE, GROUP BY, and HAVING clauses in the following manner: 1. 2. 3. If the statement contains a WHERE clause, Oracle eliminates all rows that do not satisfy it. Oracle calculates and forms the groups as specified in the GROUP BY clause. Oracle removes all groups that do not satisfy the HAVING clause.
To return the minimum and maximum salaries for the clerks in each department whose lowest salary is below 1,000, issue the following statement: SELECT deptno, MIN(sal), MAX (sal) FROM emp WHERE job = 'CLERK' deptno HAVING MIN(sal) < 1000; GROUP BY
Hierarchical Queries Using hierarchical queries, you can retrieve data based on a natural hierarchical relationship between rows in a table. A relational database does not store records in a hierarchical way. However, where a hierarchical relationship exists between the rows of a single table, a process called tree walking enables the hierarchy to be constructed. If a table contains hierarchical data, you can select rows in a hierarchical order using the following clauses: START WITH: specifies the root row(s) of the hierarchy CONNECT BY: specifies the relationship between parent rows and child rows of the hierarchy WHERE: restricts the rows returned by the query without affecting other rows of the hierarchy
CONNECT BY Clause
The CONNECT BY clause specifies the relationship between parent and child rows in a hierarchical query. Some part of the condition must use the PRIOR operator to refer to the parent row. The part of the condition containing the PRIOR operator must have one of the following forms: PRIOR expr comparison_operator expr expr comparison_operator PRIOR expr To find the children of a parent row, Oracle evaluates the PRIOR expression for the parent row and the other expression for each row in the table. Rows for which the condition is true are the children of the parent. The CONNECT BY clause cannot contain a subquery.
Set Operators
Set operators combine the results of two component queries into a single result. Queries containing set operators are called compound queries. The list of SQL set operators are given below:
All set operators have equal precedence. If a SQL statement contains multiple set operators, Oracle evaluates them from the left to right if no parentheses is present. You should use parentheses to specify order of evaluation in queries that use multiple set operators. The corresponding expressions in the select lists of the component queries of a compound query must match in number and datatype. Restrictions on Set Operators The set operators are not valid on columns of type BLOB, CLOB, BFILE, varray, or nested table. The UNION, INTERSECT, and MINUS operators are not valid on LONG columns. To reference a column, you must use an alias to name the column. You cannot also specify the for_update_clause with these set operators. You cannot specify the order_by_clause in the subquery of these operators. The following examples combine the two query results with each of the set operators. UNION UNION ALL INTERSECT MINUS
14 rows selected.
Objectives After completion of this chapter you will be able to: Explain and Use the concepts of joins in Oracle Explain and Use concepts of subqueries in Oracle Use single and multiple columns subqueries Use pairwise and nonpairwise subqueries Use correlated subqueries
Joins
A join is a query that combines rows from two or more tables, views, or snapshots. Oracle performs a join whenever multiple tables appear in the query's FROM clause. The query's select list can select any columns from any of these tables. If any two of these tables have a column name in common, you must qualify all references to these columns throughout the query with table names to avoid ambiguity. Most of the join queries contain WHERE clause that compare two columns, each from a different table. Such a condition is called a join condition. The columns in the join conditions need not also appear in the select list. To execute a join of three or more tables, Oracle first joins two of the tables based on the join conditions comparing their columns and then joins the result to another table based on join conditions containing columns of the joined tables and the new table. Oracle continues this process until all tables are joined into the result.
Equijoins
An equijoin is a join with a join condition containing an equality operator. An equijoin combines rows that have equivalent values for the specified columns. The basic syntax is: SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column1 = table2.column2;
Self Joins
A self join is a join of a table to itself. This table appears twice in the FROM clause and is followed by table aliases that qualify column names in the join condition. To perform a self join, Oracle combines and returns rows of the table that satisfy the join condition. Qualifying Ambiguous Column Names You need to qualify the names of the columns in the WHERE clause with the table name to avoid ambiguity. If there are no common column names between the two tables, there is no need to qualify the columns. However, using the table prefix improves performance, because you tell the Oracle Server exactly where to find the columns Cartesian Products If two tables in a join query have no join condition, Oracle returns their Cartesian product. Oracle combines each row of one table with each row of the other. A Cartesian product always generates many rows and is rarely useful. For example, the Cartesian product of two tables, each with 100 rows, has 10,000 rows. Always include a join condition unless you specifically need a Cartesian product.
Outer Joins The outer join extends the result of a simple join. An outer join returns all rows that satisfy the join condition and those rows from one table for which no rows from the other satisfy the join condition. Such rows are not returned by a simple join. This is the basic syntax of an outer join of two tables: SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column(+) = table2.column; SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column = table2.column(+); Outer join queries are subject to the following rules and restrictions: The (+) operator can appear only in the WHERE clause, not in the select list, and can be applied only to a column of a table or view. If A and B are joined by multiple join conditions, the (+) operator must be used in all of these conditions. A condition containing the (+) operator cannot be combined with another condition using the OR logical operator. A condition cannot use the IN comparison operator to compare with another expression a column marked with the (+) operator. A condition cannot compare with a subquery any column marked with the (+) operator. This query uses an simple outer join: SELECT ename, job, dept.deptno, dname FROM emp, dept WHERE emp.deptno (+) = dept.deptno; Joins ANSI/ISO Standard A range of new join syntax are available that comply with the ANSI/ISO SQL: CROSS JOIN NATURAL JOIN USING clause ON clause Mutable Joins Outer Join
ANSI/ISO Syntax for Cross Join available in Oracle9i is given below: SELECT first_name,last_name, department_name FROM employees CROSS JOIN departments; ANSI/ISO Syntax for Natural Join available in Oracle9i is given below: SELECT d.department_name, l.city FROM departments d NATURAL JOIN locations l;
Subqueries
Types of SubQueries: Subqueries are primarily defined based on the number of rows returned. They are either Single-row or Multiple-row. Secondarily, subqueries are defined by the number of columns. They are either singlecolumn or multiple column.
ANY
The ANY operator (and its synonym SOME operator) compares a value to each value returned by a subquery. <ANY means less than the maximum. >ANY means more than the minimum. =ANY is equivalent to IN. SELECT empno, ename, job FROM emp WHERE sal < ANY (SELECT sal FROM emp WHERE job = 'CLERK') AND job <> 'CLERK';
ALL
The ALL operator compares a value to every value returned by a subquery. >ALL means more than the maximum and <ALL means less than the minimum. SELECT empno, ename, job FROM emp WHERE sal > ALL (SELECT avg(sal) FROM emp GROUP BY deptno);
NOT
The NOT operator can be used with IN, ANY, and ALL operators.
Pairwise vs Non-Pairwise
Column comparisons in a multiple-column subquery can be pairwise comparisons or nonpairwise comparisons.
Column Comparisons For example, product 102130 appears in other orders, one order matching the quantity in order 605 (10), another order having a quantity of 500. The arrows show a sampling of the various quantities ordered particular product. SELECT ordid, prodid, qty FROM item WHERE prodid IN (SELECT prodid FROM item WHERE ordid = 605) AND qty IN (SELECT qty FROM item WHERE ordid = 605) AND ordid <> 605; Using a Subquery in the FROM Clause You can use a subquery in the FROM clause of a SELECT statement, which is very similar to how views are used. A subquery in the FROM clause of a SELECT statement defines a data source for that particular SELECT statement, and only that SELECT statement. The example below displays employee names, salaries, department numbers, and average salaries for all the employees who make more than the average salary in their department. SELECT a.ename, a.sal, a.deptno, b.salavg FROM emp a, (SELECT deptno, avg(sal) salavg FROM emp GROUP BY deptno) b WHERE a.deptno = b.deptno AND a.sal > b.salavg; Using Subquery in DDL and DML To give all employees in the EMP table a 10% raise if they have not already been issued a bonus, issue the following statement: UPDATE emp SET sal = sal * 1.1 WHERE empno NOT IN (SELECT empno FROM bonus);
Correlated Subqueries
Oracle performs a correlated subquery when the subquery references a column from a table referred to in the parent statement. A correlated subquery is evaluated once for each row processed by the parent statement. The following examples show the general syntax of a correlated subquery:
SELECT select_list FROM table1 t_alias1 WHERE expr operator (SELECT column_list FROM table2 t_alias2 WHERE t_alias1.column operator t_alias2.column); UPDATE table1 t_alias1 SET column = (SELECT expr FROM table2 t_alias2 WHERE t_alias1.column = t_alias2.column); DELETE FROM table1 t_alias1 WHERE column operator (SELECT expr FROM table2 t_alias2 WHERE t_alias1.column = t_alias2.column);
Objectives
After completion of this chapter you will be able to: Explain the concept of Index Create and Use indexes in Oracle Explain the concept of Sequences Create and Use sequences in Oracle Explain the concept of Views Create and Use Views in Oracle Explain the concept of Synonyms Create and Use Synonyms in Oracle
Indexes
Indexes are used to speed up row retrieval and enforce column uniqueness. Oracle automatically creates an index on any column with the UNIQUE or Primary Key constraint. Oracle stores indexes in index segments attached to the user's default tablespace. You may attach the index segment to another tablespace when you create an index. To create an index in your own schema, you must have either space quota on the tablespace to contain the index or UNLIMITED TABLESPACE system privilege. Syntax: Create index schema.index on schema.table(column, ..) [ASC/DESC] [NO SORT] [NOLOGGING] There are four types of index, they are: UNIQUE - ensures that values in specified column(s) are unique. NON UNIQUE - Ensures fastest possible results when querying / ordering data. SINGLE COLUMN - Only a single column makes up the index. CONCATENATED - Up to 16 columns make up the index. Indexes can be created on-line, an example follows: CREATE INDEX IDX_SECT_SECT ON SECTION(SECTION_NAME) This index will speed up SELECT statements using the section name as the WHERE clause parameter. The next statement removes the index. DROP INDEX IDX_SECT_SECT
Bitmap Indexes
Bitmap indexes store the ROWIDs associated with a key value as a bitmap. Each bit in the bitmap corresponds to a possible ROWID, and if the bit is set, it means that the row with the corresponding ROWID contains the key value. The internal representation of bitmaps is best suited for applications with low levels of concurrent transactions, such as data warehousing. To create a bitmap index on a table, issue the following statement: CREATE BITMAP INDEX partno_ix ON lineitem(partno) TABLESPACE ts1 Confirming Indexes The USER_INDEXES data dictionary view contains the name of the index and its uniqueness. The USER_IND_COLUMNS view contains the index name, the table name, and the column name.
Function-Based Indexes A function-based index is based on an expression. The index expression is build from the table columns, constants, functions and user-defined functions. For example, consider the following command: CREATE INDEX i1 ON emp (UPPER(ename)); This command will create an index i1 based on an expression - (UPPER(ename)).
Sequences
A sequence is a construct used to generate sequential unique numbers, it is usually used to produce table key values where the table data has no clearly identifiable prime key or where the identification of rows within a table would involve a large, unwieldy compound primary key. You can use sequences to automatically generate primary key values. To create a sequence in your own schema, you must have CREATE SEQUENCE privilege. To create a sequence in another user's schema, you must have CREATE ANY SEQUENCE privilege. We will now create a sequence to be used with our SECTION table; it will be used to generate the unique section numbers. CREATE SEQUENCE SECIDNUM INCREMENT BY 1 START WITH 1 MAXVALUE 100 NOCACHE. The value following the SEQUENCE key word is the name of the sequence generator, you will use this from now on to refer to the sequence. You may alter the INCREMENT BY, MINVALUE and MAXVALUE values of a sequence by using the ALTER command. ALTER SEQUENCE SECIDNUM INCREMENT BY 2 ALTER SEQUENCE SECIDNUM MINVALUE 10 ALTER SEQUENCE SECIDNUM MAXVALUE 2500 You can remove a sequence by using the DROP command. DROP SEQUENCE SECIDNUM
Confirming Sequences
Once you have created your sequence, it is documented in the data dictionary. Because a sequence is a database object, you can identify it in the USER_OBJECTS data dictionary table. You can also confirm the settings of the sequence by selecting from the USER_SEQUENCES data dictionary view.
Views
A view is a method of organizing table data to meet a specific need. Views are based on SELECT statements, which derive their data from real tables. A view allows you to reorganize the database data, you might want to do this so that you can restrict data access, reduce selection complexity, provide improved data independence or allow disparate users to view the same data in different ways. Most of the Oracle data dictionary is readable via views, which interpret internal Oracle tables. Views come in simple and complex forms. Simple views are based on a single table and data can be updated via DML commands (privilege issues aside), complex views are derived from multiple tables and DML commands cannot be used to update data. To create a view in your own schema, you must have CREATE VIEW system privilege. To create a view in another user's schema, you must have CREATE ANY VIEW system privilege. The general syntax for Create View command is: CREATE [OR REPLACE] [FORCE | NOFORCE] VIEW [schema.]view [(alias [,alias]...)] AS subquery [WITH CHECK OPTION [CONSTRAINT constraint]] Views are used for these purposes: To provide an additional level of table security, by restricting access to a predetermined set of rows and /or columns of a base table. To hide data complexity. To present data from another perspective.
Synonym
A synonym is an alternative name for a table, view, sequence, procedure, stored function, package, snapshot, or another synonym. To create a private synonym in your own schema, you must have CREATE SYNONYM system privilege. To create a private synonym in another user's schema, you must have CREATE ANY SYNONYM system privilege. To create a PUBLIC synonym, you must have CREATE PUBLIC SYNONYM system privilege. Syntax: CREATE [PUBLIC] SYNONYM synonym FOR object; Synonyms are used for security and convenience. Creating a synonym for an object allows you to: reference the object without specifying its owner reference the object without specifying the database on which it is located provide another name for the object Synonyms provide both data independence and location transparency; synonyms permit applications to function without modification regardless of which user owns the table or view and regardless of which database holds the table or view.
Scope of Synonyms
A private synonym name must be unique in its schema. Oracle attempts to resolve references to objects at the schema level before resolving them at the PUBLIC synonym level. Oracle uses a public synonym only when resolving references to an object if both of the following cases are true: the object is not prefaced by a schema the object is not followed by a database link
For example, assume the schemas SCOTT and BLAKE each contain tables named DEPT and the user SYSTEM creates a PUBLIC synonym named DEPT for BLAKE.DEPT. If the user SCOTT then issues the following statement, Oracle returns rows from SCOTT.DEPT: SELECT * FROM dept; To retrieve rows from BLAKE.DEPT, the user SCOTT must preface DEPT with the schema name: SELECT * FROM blake.dept;
SQL> DESC AFPFMSTR Name Null? Type ------------------------------- -------- ---ACCOUNTUNIT VARCHAR2(3) PAYCATEGORY VARCHAR2(1) BILLUNIT VARCHAR2(5) EMPCODE NOT NULL VARCHAR2(8) EMPNAME VARCHAR2(40) DEPARTMENT VARCHAR2(6) DATEOFJOIN DATE DATEOFAPPOINTMENT DATE BASICRATE NUMBER(15,2) VPFPERCENTAGE NUMBER(5,2) SCALECODE VARCHAR2(11) DESIGNATION VARCHAR2(6) DATEOFBIRTH DATE FATHER_HUSBAND VARCHAR2(40) SEX VARCHAR2(1) SQL> select EMPCODE,EMPNAME from afpfmstr where empcode='10000001'; EMPCODE EMPNAME -------- ---------------------------------------10000001 REKHABAI RAZAK SQL> select EMPCODE,EMPNAME from afpfmstr where empcode like '100000%' 2 AND ROWNUM<5; EMPCODE EMPNAME -------- ---------------------------------------10000001 REKHABAI RAZAK 10000003 INDIRABAI HARINARAYAN 10000004 G.BABJI RAO 10000005 BHARATI KAMALSINGH
SQL> desc afpftran Name Null? Type ------------------------------- -------- ---BILLUNIT VARCHAR2(5) EMPCODE NOT NULL VARCHAR2(8) TRANSACTIONDATE NOT NULL DATE TRANSACTIONTYPE NOT NULL VARCHAR2(2) DEBITCREDIT VARCHAR2(1) AMOUNT NUMBER(15,2) UPD VARCHAR2(1) REFERENCENUMBER VARCHAR2(15) REFERENCEDATE DATE SUBTYPE VARCHAR2(2) PRINTEDINDICATOR VARCHAR2(1) RECONSILE VARCHAR2(1) SQL> select BILLUNIT,EMPCODE,TRANSACTIONDATE,TRANSACTIONTYPE,D EBITCREDIT,AMOUNT 2 from afpftran 3 where 4 EMPCODE='10004403'; BILLU EMPCODE TRANSACTI TR D AMOUNT ----- -------- --------- -- - --------05004 10004403 01-APR-08 LR C 883 05004 10004403 01-APR-08 SR C 797 05004 10004403 01-MAY-08 LR C 883 05004 10004403 01-MAY-08 SR C 797 05004 10004403 01-JUN-08 LR C 883 05004 10004403 01-JUN-08 SR C 797 05004 10004403 01-JUL-08 LR C 883 05004 10004403 01-JUL-08 SR C 797 05004 10004403 01-AUG-08 LR C 883 05004 10004403 01-AUG-08 SR C 797 10 rows selected.
SQL> select sum(amount) from afpftran 2 where 3 empcode='10004403' 4 and 5 debitcredit='C'; SUM(AMOUNT) ----------8400
SQL> select max(amount) from afpftran; MAX(AMOUNT) ----------2255770 SQL> select min(amount) from afpftran; MIN(AMOUNT) -----------80283 SQL> select max(AMOUNT)-min(amount) as difference 2 from afpftran; DIFFERENCE ---------2336053
SQL> select avg(AMOUNT) as Average from afpftran; AVERAGE --------2553.1902 SQL> select round(avg(AMOUNT),2) as Average from afpftran; AVERAGE --------2553.19 SQL> select ceil(avg(AMOUNT)) as Average from afpftran; AVERAGE --------2554 SQL> select floor(avg(AMOUNT)) as Average from afpftran; AVERAGE --------2553 SQL> select max(TRANSACTIONDATE) from afpftran; MAX(TRANS --------05-AUG-08 SQL> select add_months(max(TRANSACTIONDATE),60) from afpftran; ADD_MONTH --------05-AUG-13