Você está na página 1de 41

Objectives

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.

Elements of SQL Literals


The terms literal and constant value are synonymous and refer to a fixed data value. For example, 'JACK', 'BLUE ISLAND', and '101' are all character literals; 5001 is a numeric literal.

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.

Basic Select Statement


The simplest form of a select statement is: SELECT *|{[DISTINCT] column |expression [alias]} FROM table; While writing the select statements the following things should noted: SQL statement are case insensitive and can be entered in one or more lines. Clauses are usually placed in separate lines for better readability. Keywords cannot be abbreviated or split across lines. The following example shows all columns and all records from the dept table: Select * from dept; The output of the above command may be as follows:

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

Finding Out the Structure of a Table


Describe command is used to know what columns are contained in a table. The describe command can be shortened to desc. Entering the command: desc customers will produce the following output

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

iSQL*Plus uses a three-tier architectural model comprising:


Client Tier (iSQL*Plus user interface, typically a web browser) Middle Tier (iSQL*Plus Server, Oracle Net, and Oracle HTTP Server) Database Tier (Oracle9i)

iSQL Architecture Running iSQL*Plus


The Oracle HTTP Server and the iSQL*Plus Server must be running on the middle tier before you can run iSQL*Plus. 1. Enter the Uniform Resource Identifier (URI) of iSQL*Plus in the Location field of your web browser, for example: http://host.domain/isqlplus where host.domain is the URI for the Oracle HTTP Server you want to use. The iSQL*Plus Log In screen is displayed.

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

Work Screen Oracle Relational Operators


There are six relational operators in Oracle, they are = Equal <> or != Not Equal < Less than <= Less than or equal to > Greater than >= Greater than or equal to

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.

Simple CASE Example


SELECT ename, CASE sal WHEN 100 THEN 'Low' WHEN 5000 THEN 'High' ELSE 'Medium' END FROM emp;

14 rows selected

Searched CASE Example


SELECT AVG(CASE WHEN e.sal > 2000 THEN e.sal ELSE 2000 END) "Average Salary" from emp e;

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

Datetime and Interval Datatypes


The datetime datatypes are DATE, TIMESTAMP, TIMESTAMP WITH TIME ZONE and TIMESTAMP WITH LOCAL TIME ZONE. Values of datetime datatypes are sometimes called "datetimes". The interval datatypes are INTERVAL YEAR TO MONTH and INTERVAL DAY TO SECOND. Values of interval datatypes are sometimes called "intervals".

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


TIMESTAMP WITH TIME ZONE is a variant of TIMESTAMP that includes a time zone displacement in its value. 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 TIME ZONE datatype as follows: TIMESTAMP [ (fractional_seconds_precision) ] WITH TIME ZONE

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

INTERVAL YEAR TO MONTH Datatype


INTERVAL YEAR TO MONTH stores a period of time using the YEAR and MONTH datetime fields. Specify INTERVAL YEAR TO MONTH as follows: INTERVAL YEAR [(year_precision)] TO MONTH where year_precision is the number of digits in the YEAR datetime field. The default value of year_precision is 2.

INTERVAL DAY TO SECOND Datatype


INTERVAL DAY TO SECOND stores a period of time in terms of days, hours, minutes, and seconds. Specify this datatype as follows: INTERVAL DAY [(day_precision)] TO SECOND [(fractional_seconds_precision)]

RAW and LONG RAW Datatypes


These datatypes are intended for binary data or byte strings. For example, you can use LONG RAW to store graphics, sound, documents, or arrays of binary data.

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.

Renaming Database Objects


Use the RENAME command to change the name of tables, views and synonyms. Note that if you change an object's name you will have to update any references to it in any application or other database object that uses it. It is wise to decide on an object's name then stick with it, even if you don't like the name you will probably save yourself a lot of work if you just live with it. RENAME BOOK TO LIBRARY_BOOK

Altering Tables and Constraints


Modification of database object structure is executed with the ALTER statement. You can modify a constraint as follows: Add new constraint to column or table Remove constraint Enable / disable constraint You cannot change a constraint definition.

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)

Dropping Tables and Constraints


To drop a constraint from a table we use the ALTER statement with a DROP clause. Some examples follow: ALTER TABLE BOOK DROP CONSTRAINT B_AUTH The above statement will remove the not null constraint (defined at table creation) from the AUTHOR column. The value following the CONSTRAINT keyword is the name of constraint.

TRUNCATE versus DELETE


The TRUNCATE statement is similar to a DELETE statement without a WHERE clause, except for the following: TRUNCATE is very fast on both large and small tables. DELETE will generate undo information, in case a rollback is issued, but TRUNCATE will not generate undo. TRUNCATE is DDL and, like all DDL, performs an implicit commit you cannot roll back a TRUNCATE. Any uncommitted DML changes will also be committed with the TRUNCATE. TRUNCATE resets the high-water mark in the table and all indexes.

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.

TRUNCATE versus DROP TABLE


Using TRUNCATE is also different from dropping and re-creating a table. Compared to dropping, and recreating a table, TRUNCATE does not do the following: Invalidate dependent objects Drop indexes, triggers, or referential integrity constraints Require privileges to be regranted

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.

Copying Rows from Another Table


To copy rows from one table to another we can use a form of the insert command. Obviously the new table must support at least the columns that were present in the old table. This is a good method of updating a table structure, if for instance we wanted to remove the BOOK_COUNT column from the SECTION table. We could create a new table (SECTIONNEW) and populate it with the contents of the old table (SECTION). We could then drop the old table and rename the new table. An example of the INSERT command that accomplishes this is shown in the next slide: INSERT INTO SECTIONNEW (SECTION_NAME, SECTION_ID) SELECT SECTION_NAME, SECTION_ID FROM SECTION You can see we are using a SELECT statement to provide the values for an INSERT command.

Datetime and Interval Examples and illustration


The following example shows how to declare some datetime and interval datatypes. CREATE TABLE my_table ( start_time TIMESTAMP, duration_1 INTERVAL DAY (6) TO SECOND (5), duration_2 INTERVAL YEAR TO MONTH); The start_time column is of type TIMESTAMP. The implicit fractional seconds precision of TIMESTAMP is 6. The duration_1 column is of type INTERVAL DAY TO SECOND. The maximum number of digits in field DAY is 6 and the maximum number of digits in the fractional second is 5. (The maximum number of digits in all other datetime fields is 2.) The duration_2 column is of type INTERVAL YEAR TO MONTH. The maximum number of digits of the value in each field (YEAR and MONTH) is 2. Changing Row Values with UPDATE The UPDATE command allows us to change the values of rows in a table. We can include a WHERE clause in the same fashion as the SELECT statement to indicate which row(s) we want values changed in. The UPDATE command can change multiple rows so you should take care that you are updating only the values you want changed (see the transactions discussion for methods of limiting damage from accidental updates).

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]

Using Subqueries in an UPDATE Command


Using subqueries within UPDATE commands is similar to using them in SELECT statements. UPDATE SECTION SET BOOK_COUNT = (SELECT COUNT(*) FROM BOOK WHERE BOOK.SECTION_ID = SECTION.SECTION_ID) WHERE SECTION_ID IN (SELECT SECTION_ID FROM BOOK)

Deleting Rows with DELETE


The DELETE command allows you to remove rows from a table, you can include a WHERE clause in the same fashion as the SELECT statement to indicate which row(s) you want deleted - in nearly all cases you should specify a WHERE clause, running a DELETE without a WHERE clause deletes ALL rows from the table. Unlike the INSERT command the DELETE command can change multiple rows so you should take great care that you are deleting only the rows you want removed. The general syntax for delete command is: DELETE [FROM] [schema.]{table | view} [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.

The COMMIT Command


The general syntax for commit: COMMIT [WORK] [ COMMENT 'text' | FORCE 'text' [, integer] ] The COMMIT command saves any unsaved updates to the database and all savepoints and locks are released. You should always issue a COMMIT or ROLLBACK command to finish a unit of work, this will prevent your application leaving the database in an indeterminate state.

The SAVEPOINT Command


The SAVEPOINT command divides a transaction into smaller sub units. The SAVEPOINT command has a parameter, which is the name of the savepoint. This name can be used to rollback all updates from the time when you issued the named savepoint. You can reuse the savepoint name, each time you redeclare an existing savepoint the old savepoint of that name is deleted.

The ROLLBACK Command


The general syntax for Rollback is: ROLLBACK [WORK] [ TO [SAVEPOINT] savepoint | FORCE 'text' ] The ROLLBACK command removes pending database updates. Issuing a ROLLBACK without specifying a savepoint name removes all pending updates since the last transaction start event whereas issuing a ROLLBACK with a savepoint name parameter removes all pending updates since the time the specified savepoint was created.

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.

Character Functions Returning Character Values


CONCAT Syntax: CONCAT(char1, char2) Purpose: Returns char1 concatenated with char2. This function is equivalent to the concatenation operator (||). It takes only two parameters.

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

Character Functions Returning Number Values


ASCII Syntax: ASCII(char) Purpose: Returns the decimal representation in the database character set of the first character of char. If your database character set is 7-bit ASCII, this function returns an ASCII value. If your database character set is EBCDIC Code, this function returns an EBCDIC value. Note that there is no similar EBCDIC character function.

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).

Round and Trunc Functions In Case of a Number


ROUND Syntax: ROUND(n[,m]) Purpose: Returns n rounded to m places right of the decimal point; if m is omitted, to 0 places. m can be negative to round off digits left of the decimal point. m must be an integer.

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.

The TO_CHAR Conversion Function


TO_CHAR converts a number / date to a string. The function accepts 2 parameters, the first is the name of a column value or a literal value and the second is a format picture (which consists of one or many defined keywords). The format picture dictates what the result will look like. Some examples follow: SELECT TO_CHAR(SYSDATE, 'DAY, DDTH MONTH YYYY') FROM DUAL Format Models A format model is a character literal that describes the format of DATE or NUMBER data stored in a character string. You can use a format model as an argument of the TO_CHAR or TO_DATE function for the following purposes: to specify the format for ORACLE to use to return a value from the database to you to specify the format for a value you have specified for ORACLE to store in the database

Number Format Models


You can use number format models in these places: In the TO_CHAR function to translate a value of NUMBER datatype to VARCHAR2 datatype In the TO_NUMBER function to translate a value of CHAR or VARCHAR2 datatype to NUMBER datatype All number format models cause the number to be rounded to the specified number of significant digits.

Date Format Models


You can use date format models in the following places: In the TO_CHAR function to translate a DATE value that is in a format other than the default date format In the TO_DATE function to translate a character value that is in a format other than the default date format FM ''Fill Mode'' This modifier suppresses blank padding in the return value of the TO_CHAR function. In a date format element of a TO_CHAR function, this modifier suppresses blanks in subsequent character elements (such as MONTH) and suppresses leading zeroes for subsequent number elements (such as MI) in a date format model. Since there is no blank padding, the length of the return value may vary. Without FM, the result of a character element is always right padded with blanks to a fixed length and the leading zero are always returned for a number element.

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.

GREATEST and LEAST


These functions work on a group of columns. The function compares the values of several columns and returns the greatest or the least. select greatest(22, 27) high, least(22, 27) low from dual;

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

Grouping Related Records


GROUP BY clause is used to group selected rows and return a single row of summary information based on that group. Oracle collects each group of rows based on the values of the expression(s) specified in the GROUP BY clause. If a SELECT statement contains the GROUP BY clause, the select list can contain only the following types of expressions: Constants Group functions The functions USER, UID, and SYSDATE Expressions identical to those in the GROUP BY clause

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

FOR UPDATE Clause


The FOR UPDATE clause locks the rows selected by the query. Once you have selected a row for update, other users cannot lock or update it until you end your transaction. The FOR UPDATE clause signals that you intend to insert, update, or delete the rows returned by the query, but does not require that you perform one of these operations.

FOR UPDATE OF Clause


The columns in the OF clause only specify which tables' rows are locked. The specific columns of the table that you specify are not significant. If you omit the OF clause, Oracle locks the selected rows from all the tables in the query. The following statement locks rows in the EMP table with clerks located in New York and locks rows in the DEPT table with departments in New York that have clerks: SELECT empno, sal, comm FROM emp, dept WHERE job = 'CLERK' AND emp.deptno = dept.deptno AND loc = 'NEW YORK' FOR UPDATE;

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

START WITH Clause


The START WITH clause identifies the row(s) to be used as the root(s) of a hierarchical query. This clause specifies a condition that the roots must satisfy. If you omit this clause, Oracle uses all rows in the table as root rows. A START WITH condition can contain a subquery.

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.

The LEVEL Pseudocolumn


SELECT statements that perform hierarchical queries can use the LEVEL pseudocolumn. LEVEL returns the value 1 for a root node, 2 for a child node of a root node, 3 for a grandchild, etc. The following statement returns all employees in hierarchical order. The root row is defined to be the employee whose job is 'PRESIDENT'. The child rows of a parent row are defined to be those who have the employee number of the parent row as their manager number. SELECT LPAD(' ',2*(LEVEL-1)) || ename org_chart, empno, mgr, job FROM emp START WITH job = 'PRESIDENT' CONNECT BY PRIOR empno = mgr;

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

Consider this query and the result: select * from empl;

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.

Guidelines for Using Subqueries


Enclose subqueries in parentheses. Place subqueries on the right side of the comparison operator. Do not add an ORDER BY clause to a subquery. Use single-row operators with single-row subqueries. Use multiple-row operators with multiple-row subqueries. Let us first look at single-row vs multiple row. Single-row subqueries are Queries that return only one row from the inner SELECT statement. Multiple-row subqueries are Queries that return more than one row from the inner SELECT statement. A single-row subquery is one that returns one row from the inner SELECT statement. This type of subquery uses a single-row operator. Consider the following query: SELECT ename, job FROM emp WHERE job = (SELECT job FROM emp WHERE empno = 7369);

Using Group Functions in a Subquery


You can display data from a main query by using a group function in a subquery to return a single row. The subquery is in parentheses and is placed after the comparison operator. The example below displays the employee name, job title, and salary of all employees whose salary is equal to the minimum salary. The MIN group function returns a single value (800) to the outer query. SELECT ename, job, sal FROM emp WHERE sal = (SELECT MIN(sal) FROM emp); HAVING Clause with Subqueries You can use subqueries not only in the WHERE clause, but also in the HAVING clause. The Oracle Server executes the subquery, and the results are returned into the HAVING clause of the main query.

Problems with Subqueries


A common problem with subqueries is no rows being returned by the inner query. The subquery contains a WHERE (ename='SMYTHE') clause. Presumably, the intention is to find the employee whose name is Smythe. The statement seems to be correct but selects no rows when executed. The outer query finds no employee with a job title equal to null and so returns no rows. SELECT ename, job FROM emp WHERE job = (SELECT job FROM emp WHERE ename='SMYTHE');

Errors with Subqueries


One common error with subqueries is more than one row returned for a single-row subquery. In the SQL statement below, the subquery contains a GROUP BY (deptno) clause, which implies that the subquery will return multiple rows, one for each group it finds. SELECT empno, ename FROM emp WHERE sal = (SELECT MIN(sal) FROM emp GROUP BY deptno); ` Multiple Row Operators Operator Meaning IN Equal to any member in the list ANY Compare value to each value returned by the subquery ALL Compare value to every value returned by the subquery

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.

Multiple Column Subqueries


If you want to compare two or more columns, you must write a compound WHERE clause using logical operators. Multiple-column subqueries enable you to combine duplicate WHERE conditions into a single WHERE clause. Syntax: SELECT FROM WHERE column, column, ... table (column, column, ...) IN (SELECT column, column, ... FROM table WHERE condition);

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

Incrementing Sequence Values


You can create a sequence so that its values increment in one of following ways: The sequence values increment without bound. The sequence values increment to a predefined limit and then stop. The sequence values increment to a predefined limit and then restart. Caching Sequence Numbers The number of values cached in memory for a sequence is specified by the value of the sequence's CACHE parameter. Cached sequences allow faster generation of sequence numbers. A cache for a given sequence is populated at the first request for a number from that sequence. The cache is repopulated every CACHE requests. If there is a system failure, all cached sequence values that have not been used in committed data manipulation language (DML) statements are lost. The potential number of lost values is equal to the value of the CACHE parameter.

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

Você também pode gostar