Está en la página 1de 21

ORACLE SQL REFERENCE GUIDE

July 2004 Created by Larry Haug The Guthrie Center Spring Branch ISD 10660 Hammerly Boulevard Houston, TX 77043-2302

Send comments and/or suggestions for improvement to larry369@houston.rr.com

TABLE OF CONTENTS
Section 1 Section 2 Section 3 Section 4 Section 5 Naming Rules ............. Data Types .......
(CHAR, VARCHAR2, NUMBER, DATE, SYSDATE, TIMESTAMP, WITH LOCAL TIME ZONE, INTERVAL YEAR TO MONTH, INTERVAL DAY TO SECOND, BLOB, CLOB)

Page 3 Page 3 Page 4 Page 4 Page 5

Expressions .. Oracle SQL Statement Format ..


(SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, ASC, DESC)

Data Definition language (DDL) ....


(CREATE TABLE, ALTER TABLE, ADD, DROP COLUMN, DELETE FROM, MODIFY, RENAME, DROP TABLE, SET UNUSED, DROP UNUSED COLUMNS, TRUNCATE TABLE, COMMENT ON)

Section 6 Section 7 Section 8 Section 9 Section 10 Section 11 Section 12 Section 13 Section 14 Section 15 Section 16 Section 17 Section 18 Section 19 Section 20 Section 21 Section 22 Section 23 Section 24 Section 25 Section 26

Aliases ...
(SELECT AS)

Page 6 Page 6 Page 7 Page 8 Page 8 Page 9 Page 10 Page 11 Page 11 Page 11 Page 13 Page 13 Page 15 Page 15 Page 15 Page 16 Page 16 Page 18 Page 18 Page 19 Page 20

Views .....
(CREATE VIEW, DROP VIEW, SELECT ROWNUM AS)

Sequences ....
CREATE SEQUENCE, ALTER SEQUENCE, DROP SEQUENCE)

Indexes ..
CREATE INDEX, DROP INDEX)

Synonyms .....
(CREATE SYNONYM, DROP SYNONYM)

Constraints .......
(ADD CONSTRAINT, DROP CONSTRAINT, MODIFY CONSTRAINT, DISABLE CONSTRAINT, ENABLE CONSTRAINT)

Data Manipulation Language (DML) .


(INSERT INTO, UPDATE, MERGE INTO)

Data Retrieval ......


(DESCRIBE, SELECT, DISTINCT)

Case Manipulation Functions ....


(UPPER, LOWER, INITCAP)

Character Manipulation Functions ....


(LIKE, CONCAT, SUBSTR, LENGTH, INSTR, LPAD, RPAD, TRIM, REPLACE, TO_NUMBER, TO_DATE)

Number Manipulation Functions


(ROUND, TRUNC, MOD, TO_CHAR, POWER)

Date Manipulation Functions .....


(MONTHS_BETWEEN, NEXT_DAY, LAST_DAY, ADD_MONTHS, TO_CHAR)

Null Value Functions ...


(NVL, NVL2, NULLIF, COALESCE)

Conditional Functions .....


(CASE, DECODE)

Joins ...... Oracle Joins ..


(Equijoin, Cartesian Product Join, Nonequijoin, Outer Join, Self Join)

ANSI Joins ....


(NATURAL JOIN, CROSS JOIN, JOIN USING, JOIN ON, OUTER JOIN)

Group Functions ......


(AVG, SUM, STDDEV, VARIANCE, COUNT, MAX, MIN, GROUP BY, HAVING)

Subqueries
(IN, ANY, ALL)

Data Dictionary . Controlling User Access .....


(CREATE ROLE, GRANT, WITH GRANT OPTION, PUBLIC,REVOKE)

Page 2of 21

1. NAMING RULES The following naming rules apply to table names and column names: - Must begin with a letter - Must be 1 to 30 characters long - Must contain ONLY A - Z, a - z, 0 - 9, _ (underscore), $, and # - Must not duplicate the name of another object owned by the same user - Must not be an Oracle Server reserved word 2. DATA TYPES The CHAR data type specifies a fixed-length character string, including numbers, dashes and special characters. The string length is normally supplied in bytes but can be supplied in character columns. Strings are enclosed in single quotes. CHAR(n) CHAR(n CHAR) The VARCHAR2 data type specifies a variable-length character string, including numbers, special characters and dashes. Maximum string length is normally supplied in bytes but can be supplied in character columns. VARCHAR 2(n) VARCHAR2(n CHAR) The NUMBER data type stores zero as well as positive and negative fixed numbers. No dashes, text, or other nonnumeric data are allowed. Currency is stored as a number data type. Specify an integer using the following form: NUMBER(p) Specify a fixed-point number using the following form: NUMBER(p,s) where: p is the precision, or the total number of digits. Oracle guarantees the portability of numbers with precision of up to 38 digits. s is the scale, or the number of digits to the right of the decimal point. The scale can range from -84 to 127. If the scale is negative, then the actual data is rounded to the specified number of places to the left of the decimal point. For example, a specification of (10,-2) means to round to hundreds. The DATE data type stores date and time information. Oracle stores dates as numbers and by default DATE information is displayed as DD-MON-YY (for example, 19-JUN-04). The ANSI date literal contains no time portion, and must be specified in exactly this format ('YYYY-MM-DD'). The computer date can be accessed with the SYSDATE function. DATE '1998-12-25' Time can be added with the TIMESTAMP function. TIMESTAMP '1997-01-31 09:26:50.124' TIMESTAMP '1997-01-31 09:26:50.124' TIMESTAMP '1997-01-31 09:26:50.124 WITH LOCAL TIME ZONE TIMESTAMP '1997-01-31 09:26:50.124 [With Time Zone] TIMESTAMP '1999-04-15 8:00:00 -8:00' TIMESTAMP '1999-04-15 8:00:00 US/Pacific' TIMESTAMP '1999-04-15 8:00:00 US/Pacific PDT' The INTERVAL YEAR TO MONTH data type stores a period of time using the YEAR and MONTH datetime fields. This data type is useful for representing the precise difference between two datetime values. 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.

Page 3of 21

The INTERVAL DAY TO SECOND data type stores a period of time in terms of days, hours, minutes, and seconds. This data type is useful for representing the difference between two datetime values when only the year and month values are significant. INTERVAL DAY [(<day precision>)] TO SECOND [(<fractional seconds precision>)] where day precision is the number of digits in the DAY datetime field. Accepted values are 0 to 9. The default is 2. Fractional seconds precision is the number of digits in the fractional part of the SECOND datetime field. Accepted values are 0 to 9. The default is 6. The BLOB data type stores unstructured binary large objects. BLOB objects can be thought of as bitstreams with no character set semantics. BLOB objects can store up to (4 gigabytes-1) * (database block size) of binary data. The CLOB data type stores single-byte and multi-byte character data. 3. EXPRESSIONS The order of evaluating expressions is as depicted in the table below. When evaluating parenthetical expressions, the innermost expression is evaluated first, then proceeding towards the outermost expression. 1 2 3 4 5 6 7 8 Arithemitic *, /, +, Concatenation || Comparison =, <, <=, >, >=, <> IS (NOT) NULL, LIKE, (NOT) IN (NOT) BETWEEN NOT AND OR

AND both conditions must be true OR one condition must be true NOT returns rows that dont satisfy a condition 4. ORACLE SQL STATEMENT FORMAT SQL statements for data retrieval are of the format (Students Fail When Gorillas Hide Oranges): SELECT <column name> FROM <table name> WHERE <condition> GROUP BY <condition> HAVING <condition> ORDER BY <condition> where SELECT clause - selects from the reduced data set the columns requested FROM clause - locates the table that contains the data WHERE clause - restricts the rows to be returned GROUP BY clause - enables aggregate data to be applied to groups of column values. HAVING clause - restricts the rows to be returned for aggregate data ORDER BY clause - orders the results set. Default is ASCending. Use DESC for descending. Numeric values are displayed lowest to highest. Date values are displayed with the earliest date first. Character values are displayed in alphabetical order. Null values are displayed last in ascending order sorts and first in descending order sorts. SQL statements are not usually case sensitive and can be entered on one or many lines. Keywords (SELECT, FROM, etc.) are typically entered in uppercase and cannot be abbreviated or split across lines. Table and column names are typically entered in lowercase.

Page 4of 21

5. DATA DEFINITION LANGUAGE (DDL) The CREATE command can be used to create a table, view, sequence, index, or synonym. To create a table, use the CREATE TABLE command. A column in a table can be given a DEFAULT value. This option prevents null values from entering the columns if a row is inserted without a specified value for the column. Using default values also allows the user to control where and when the default value should be applied. The default value can be a literal value, an expression, or a SQL function, such as SYSDATE and USER, but the value cannot be the name of another column or a pseudocolumn, such as NEXTVAL or CURRVAL. The default expression must match the data type of the column. A second method for creating a table is to apply the AS subquery clause, which both creates the table and inserts rows returned from the subquery. CREATE TABLE <table name> (<column 1 name> <column 1 data type [DEFAULT <value or expression>]> [CONSTRAINT] [DISABLE] <constraint>, <column n name> <column n data type>) or CREATE TABLE <table name> AS SELECT <column 1>, <column 2>, <column n> FROM <table> To add a new column to a table or drop a column, you would use the ALTER TABLE command. ALTER TABLE <table> ADD (<new column name> <data type>) DROP COLUMN <column name> To delete a row from a table, use the DELETE FROM command. You cannot delete a row that contains a primary key that is used as a foreign key in another table. All rows will be deleted if the WHERE clause is omitted. DELETE FROM <table name> WHERE <condition for row select> To modify a column, you would use the MODIFY command. You can increase the width or precision of a numeric or character column. You can decrease the width of a column only if the column contains only null values or if the table has no rows. You can change the data type only if the column contains null values. You can convert a CHAR column to the VARCHAR2 data type or convert a VARCHAR2 column to the CHAR data type only if the column contains null values or if you do not change the size. A change to the default value of a column affects only subsequent insertions to the table. ALTER TABLE <table> MODIFY (<column 1> <data type> [DEFAULT <value or expression>], <column n> <data type>) To rename a table, you would use the RENAME command. RENAME <table name> TO <new name> To delete a table, you would use the DROP TABLE command. DROP TABLE <table> The SET UNUSED option marks one or more columns as unused so they can be dropped when the demand on system resources is lower. The columns are physically still in the database, they simply can no longer be accessed. Once columns are SET UNUSED, a SELECT * query will not retrieve data from the columns. Also, if a DESCRIBE statement is issued on the table, the columns marked SET UNUSED will not be displayed. In fact, you could add a new column to the database with the same name as the unused column. The UNUSED columns are there, but invisible! ALTER TABLE <table> SET UNUSED (<column>) DROP UNUSED COLUMNS removes all columns currently marked as unused. You use this statement when you want to reclaim the extra disk space from unused columns in a table. ALTER TABLE <table> DROP UNUSED COLUMNS Use the TRUNCATE TABLE command to remove all rows from a table and to release the storage space used by that table. TRUNCATE TABLE <table>
Page 5of 21

You can add a comment of up to 2,000 bytes about a column, table or view by using the COMMENT ON statement. The comment is stored in the data dictionary and can be viewed in one of the data dictionary views (ALL_COL_COMMENTS, USER_COL_COMMENTS, ALL_TAB_COMMENTS, USER_TAB_COMMENTS) in the COMMENTS column: COMMENT ON TABLE <table> | COLUMN <table.column> IS 'place your comment here 6. ALIASES Working with lengthy column and table names can be cumbersome. Fortunately, there is a way to shorten the syntax using aliases. Table aliases precede the column name. However, if a table alias is used in the FROM clause, then that table alias MUST be substituted for the table name throughout the SELECT statement. To distinguish columns that have identical names but reside in different tables use column aliases. Column aliases containing more than one word must be enclosed in double quotes. When there are no shared column names between two tables, there is no need to add the table name to it. SELECT <column in table 1> AS <alias>, <column in table 2> AS <column alias> or SELECT <table alias>.<column> FROM <table> <table alias> 7. VIEWS A VIEW, like a table, is a database object. However, views are not real" tables. They are logical representations of existing tables or of another view. Views contain no data of their own. They function as a window through which data from tables can be viewed or changed. The tables on which a view is based are called base tables. The view is a query stored as a SELECT statement in the data dictionary. Views restrict access to the data because the view can display selective columns from the table. Views can be used to reduce the complexity of executing queries based on more complicated SELECT statements. For example, the creator of the view can construct join statements that retrieve data from multiple tables. The user of the view neither sees the underlying code nor how to create it. The user, through the view, interacts with the database using simple queries. Views can be used to retrieve data from several tables providing data independence for users. Users can view the same data in different ways. Views provide groups of users access to data according to their particular permissions or criteria. There are two classifications for views: simple and complex. Simple views allow DML operations INSERT, UPDATE and DELETE through the view. Guidelines for creating a view include: The subquery that defines the view can contain complex SELECT syntax. The subquery that defines the view cannot contain an ORDER BY clause. The ORDER BY clause is specified when you retrieve data from the view. You can use the OR REPLACE option to change the definition of the view without having to drop it or re-grant object privileges previously granted on it. Aliases can be used for the column names in the subquery. You cannot remove a row from an underlying base table, modify data or add data through a view if the view contains group functions, a GROUP BY clause, the DISTINCT keyword or the pseudocolumn ROWNUM keyword (a number value given to each row in the result set). You cannot modify data through a view if the view contains columns defined by expressions. You cannot add data through a view if the view contains columns defined by expressions or NOT NULL columns in the base tables that are not selected by the view. NOT NULL means that the base columns must have a value. The user of a view will not see all the columns in the table and wouldn't know which columns in the base tables must have a value. Adding a new row must include data for all the NOT NULL columns for that row. To create a SIMPLE VIEW embed a subquery within the CREATE VIEW statement. CREATE [OR REPLACE] [FORCE] [NO FORCE] VIEW <view name> AS <subquery> [[WITH CHECK OPTION] [CONSTRAINT <constraint name>]] [WITH READ ONLY] where OR REPLACE re-creates the view if it already exists. FORCE creates the view regardless of whether or not the base tables exist. NO FORCE creates the view only if the base table exists (default). subquery is a complete SELECT statement (you can use aliases for the columns in the SELECT list). The subquery can contain complex SELECT syntax. WITH CHECK OPTION specifies that only rows accessible to the view can be inserted or updated. WITH READ ONLY ensures that no DML operations can be performed on this view.
Page 6of 21

COMPLEX VIEWS are views that can contain joins and group functions. CREATE VIEW <view name> (<column 1>, <column 2>, <column n>) AS SELECT <table 1>.<column 1>, <table 1>.<column 2>, <table 2>.<column 1>, <table 2>.<column 2> FROM <table 1>, <table 2> WHERE <table 1>.<column 3> = <table 2>.<column 3> or CREATE VIEW <view name> (<column 1>, <column 2>, <column n>) AS SELECT <table 1>.<column 1>, <table 1>.<column 2>, <table 2>.<column 1>, <table 2>.<column 2> FROM <table 1>, <table 2> WHERE <table 1>.<column 3> = <table 2>.<column 3> GROUP BY <table 1>.<column 3>, <table 1>.<column 1>, <table 2>.<column 1> To delete a view use the DROP VIEW statement. DROP VIEW <view name> INLINE VIEWS are also referred to as queries in the FROM clause. SELECT x.<column 1>, x.<column 2>, y.<column 1>, y.<column 2> FROM <table 1> x, (SELECT <column 1 or expression>, <column 2 or expression>, <column n or expression> FROM <table 2> GROUP BY column 1) y WHERE x.<column 3> = y.<column 1> TOP-N-ANALYSIS is a SQL operation used to rank results. SELECT ROWNUM AS <column alias>, <column 1>, <column 2> FROM (SELECT <column 1>, <column 2> FROM <table> ORDER BY <column 1>) WHERE ROWNUM < | <= n 8. SEQUENCES SQL has a process for automatically generating unique numbers that eliminates the worry about the details of duplicate or skipped numbers. The numbering process is handled through one of SQL's database objects called a SEQUENCE. Typically, sequences are used to create a PRIMARY KEY value. Sequence numbers are stored and generated independently of tables. Therefore, the same sequence can be used for multiple tables. Sequences are established by using the CREATE SEQUENCE statement. CREATE SEQUENCE <sequence name> [INCREMENT BY n] NOTE: Descending sequences can be created by specifying n. [START WITH n] NOTE: n can be either a positive or negative integer but cannot be 0. [{MAXVALUE n | NOMAXVALUE}] [{MINVALUE n | NOMINVALUE}] [{CYCLE | NOCYCLE}] [{CACHE n | NOCACHE}] [{ORDER | NOORDER}] where Using the CACHE n option specifies how many values of the sequence the database preallocates and keeps in memory for faster access. The NOCACHE option prevents values in the sequence from being cached, which in the event of system failure prevents numbers pre-allocated and held in memory from being lost. The NOCYCLE option prevents the numbering from starting over at the START WITH value if the MAXVALUE is exceeded. Don't use the CYCLE option if the sequence is used to generate primary key values unless there is a reliable mechanism that purges old rows faster then new ones are added. Specify ORDER to guarantee that sequence numbers are generated in order of request. This clause is useful if you are using the sequence numbers as timestamps. Guaranteeing order is usually not important for sequences used to generate primary keys. After a sequence has been created you can use it to insert data into a table. The NEXTVAL pseudocolumn is used to extract successive sequence numbers from a specified sequence. You must qualify NEXTVAL with the sequence name. When you reference <sequence name>.NEXTVAL, a new sequence number is generated and the current sequence number is placed in CURRVAL. The CURRVAL pseudocolumn is used to refer to a sequence number that the current user has just generated. INSERT INTO <table name>(<column 1>, <column 2>, <column n>) VALUES (<sequence name>.NEXTVAL, <value 2>, <value 3>)

Page 7of 21

A sequence can be changed using the ALTER SEQUENCE statement. ALTER SEQUENCE <sequence name> Modified sequence statements To view a sequence; SELECT increment_by, min_value, max_value, min_value, last_number FROM user_sequences WHERE sequence_name = '<SEQUENCE NAME>' To remove a sequence from the data dictionary, use the DROP SEQUENCE statement. DROP SEQUENCE <sequence name> 9. INDEXES Oracle uses an INDEX to speed up the retrieval of rows. An Oracle server index is a schema object that can speed up the retrieval of rows by using a pointer. Indexes can be created explicitly or automatically. If you do not have an index on the column youre selecting, then a full table scan occurs. An index provides direct and fast access to rows in a table. Its purpose is to reduce the necessity of disk I/O (input/output) by using an indexed path to locate data quickly. Null values are not included in the index. The index is used and maintained automatically by the Oracle server. Once an index is created, no direct activity is required by the user. Indexes are logically and physically independent of the table they index. This means that they can be created or dropped at any time and have no effect on the base tables or other indexes. Note: When you drop a table, corresponding indexes are also dropped. Two types of indexes can be created: a UNIQUE INDEX is an index that the Oracle server automatically creates when you define a column in a table to have a PRIMARY KEY or a UNIQUE key constraint. The name of the index is the name given to the constraint; a NON-UNIQUE INDEX is an index that a user can create to speed up access to the rows. For example, to optimize joins, you can create an index on the FOREIGN KEY column, which speeds up the search to match rows to the PRIMARY KEY column. Although you can manually create a unique index, it is recommended that you create a unique constraint in the table using the CREATE INDEX statement, which implicitly creates a unique index. CREATE INDEX <index name> ON <table> ( <column 1>, <column 2>, column n>) A FUNCTION-BASED INDEX stores the indexed values and uses the index based on a SELECT statement to retrieve the data. A function-based index is an index based on expressions. The index expression is built from table columns, constants, SQL functions, and user-defined functions. Function-based indexes are useful when you don't know in what case the data was stored in the database. Function-based indexes defined with the UPPER(<column>) or LOWER(<column>) keywords allow case-insensitive searches. CREATE INDEX <index name> ON <table> (<FUNCTION>(<column>)) To view an index: SELECT index_name, table_name, uniqueness FROM user_indexes WHERE table_name = '<TABLE>' To display the indexes and uniqueness that exist in the data dictionary for a table: SELECT ic.index_name, ic.column_name, ic.column_position col_pos,ix.uniqueness FROM user_indexes ix, user_ind_columns ic WHERE ic.index_name = ix.index_name AND ic.table_name = '<TABLE>' You cannot modify indexes. To change an index, you must drop it and then re-create it. Remove an index definition from the data dictionary by issuing the DROP INDEX statement. DROP INDEX <index name> 10. SYNONYMS In SQL, as in language, a SYNONYM is a word or expression that is an accepted substitute for another word. Synonyms are used to simplify access to objects by creating another name for the object. Synonyms can make referring to a table owned by another user easier and shorten lengthy object names. For example, to refer to another users table you can create a synonym for that table using a short name. Creating a synonym with the
Page 8of 21

CREATE SYNONYM statement eliminates the need to qualify the object name with the schema and provides you with an alternative name for a table, view, sequence, procedure, or other objects. This method can be especially useful with lengthy object names, such as views. CREATE [OR REPLACE] [PUBLIC] SYNONYM [<schema>.]<synonym name> FOR [<schema>.] <object> Use the OR REPLACE clause to change the definition of an existing synonym without first dropping it. Specify PUBLIC to create a public synonym. Public synonyms are accessible to all users. If you omit schema (or user), then Oracle Database creates the synonym in your own schema. You cannot specify a schema for the synonym if you have specified PUBLIC. To remove a synonym use the DROP SYNONYM command. DROP [PUBLIC] SYNONYM [<schema>.]<synonym name> 11. CONSTRAINTS A CONSTRAINT is a database rule. Their definitions are stored in the data dictionary. Constraints prevent the deletion of a table if there are dependencies from other tables. Constraints enforce rules on the data whenever a row is inserted, updated or deleted from a table. When the constraint is created, it may or may not be given a name, in which case, the system gives the constraint a name such as SYS_C00585417. Note: if the word CONSTRAINT is used in the CREATE TABLE definition, you must give the constraint a name. It is best to name constraints yourself because the system-generated names are not intuitive. Types of constraints: PRIMARY KEY (pk) - to define the column or set of columns as a Primary Key that uniquely identifies each row in a table. No primary key value can appear in more than one row in the table and NULLS are not allowed. FOREIGN KEY (fk) - to define the column as a Foreign Key. The table containing the foreign key is called the child table and the table containing the referenced key is called the parent table. A foreign key must have a corresponding primary key which must be created first. Using the ON DELETE CASCADE option when defining a foreign key, enables the dependent rows in the child table to be deleted when a row in the parent table is deleted. Using the ON DELETE SET NULL option when defining a foreign key, enables the dependent rows in the child table to be set to NULL when a row in the parent table is deleted. UNIQUE (uk) - to define the column as a Unique Key. A UNIQUE constraint requires that every value in a column be unique: that is, no two rows of a table can have duplicate values. COMPOSITE UNIQUE KEY (uk) - to define a combination of columns as a Unique Key. If the combination of two columns must not be the same for any entry, the constraint is said to be a composite unique key. Can only be defined at the table level. CHECK (ck) - to require a value in the database to comply with a specified condition. A single column can have multiple CHECK constraints that reference the column in its definition. There is no limit to the number of CHECK constraints which you can define on a column. NOT NULL (nn) - to signify that the column may NOT have a Null value. Can only be defined at the column level. A COLUMN LEVEL constraint references a single column. To accomplish this, the constraint must be defined in the CREATE TABLE statement when the column is defined. CREATE TABLE <table name> (<column 1 name> <column 1 data type> CONSTRAINT <primary key name> PRIMARY KEY, <column 2 name> <column 2 data type> CONSTRAINT <foreign key name> REFERENCES <referenced table> (<referenced primary or unique key column>) [ON DELETE CASCADE/SET NULL], <column 3 name> <column 3 data type> CONSTRAINT <unique key name> UNIQUE, <column 4 name> <column 4 data type> CONSTRAINT <check key name> CHECK (<conditional expression>), <column 5 name> <column 5 data type> CONSTRAINT <not null key name> NOT NULL)

Page 9of 21

TABLE LEVEL constraints are listed separately from the column definitions in the CREATE TABLE statement. Table level constraint definitions are stated after all the table columns have been defined. CONSTRAINT <constraint name> <TYPE OF CONSTRAINT> (<column name or condition>) CONSTRAINT <constraint name> PRIMARY KEY (<column 1>, <column 2>, <column n>) CONSTRAINT <constraint name> FOREIGN KEY (<column>) REFERENCES <referenced table> (<referenced primary or unique key column>) [ON DELETE CASCADE/SET NULL] CONSTRAINT <name> UNIQUE (<column>), CONSTRAINT <name> UNIQUE (<column 1>, <column 2>, <column n>) CONSTRAINT <name> CHECK (<conditional expression>) The ALTER TABLE statement is used to make changes to constraints in existing tables. These changes can include adding or dropping constraints, enabling or disabling constraints or adding a NOT NULL constraint to a column. You can add, drop, enable, or disable a constraint, but you cannot modify its structure. You can add a NOT NULL constraint to an existing column by using the MODIFY clause of the ALTER TABLE statement. MODIFY is used because NOT NULL is a column level change. You can define a NOT NULL column only if the table is empty or if the column has a value for every row. ALTER TABLE <table> ADD CONSTRAINT <constraint name> <TYPE OF CONSTRAINT> (<column>) ADD CONSTRAINT <constraint name> <TYPE OF CONSTRAINT> (<column>) REFERENCES <table>(<primary key column>) [ON DELETE CASCADE/NULL] MODIFY (<column> CONSTRAINT <constraint name> NOT NULL) DROP <TYPE OF CONSTRAINT> (<column>) CONSTRAINT <constraint name> [CASCADE] DROP PRIMARY KEY CASCADE DISABLE CONSTRAINT <constraint name> [CASCADE] ENABLE CONSTRAINT <constraint name> To view all constraints on a table, query the USER_CONSTRAINTS table. SELECT <constraint name>, <TYPE OF CONSTRAINT> FROM USER_CONSTRAINTS WHERE TABLE_NAME = <table> 12. DATA MANIPULATION LANGUAGE (DML) The INSERT command lets you add a row of data to the table. You may EXPLICITY list each column or IMPLICITY not list the column names. If a column can hold null values, it can be omitted from the INSERT clause. An implicit insert will automatically insert a null value in that column. To explicitly add null values to a column, use the NULL keyword in the VALUES list for those columns that can hold null values. To specify empty strings and/or missing dates use empty single quotation marks (' ') for missing data. Special values such as SYSDATE and USER can be entered in the VALUES list of an INSERT statement. SYSDATE will put the current date and time in a column. USER will return the current username which in HTML DB will be PUBLIC_USER. In addition, functions can also be used in the VALUES clause. If the keyword DEFAULT is used as a <value> and a default value was set for the column, Oracle sets the column to the default value. However, if no default value was set when the column was created, Oracle inserts a null value. Subqueries can also be used to populate the table from another table. INSERT INTO <table name>(<column 1>, <column 2>, <column n>) VALUES (<value 1>, <value 2>, <value 3>) or INSERT INTO <table name> VALUES (<value 1>, <value 2>, <value 3>) or INSERT INTO <table 1 name> SELECT <column 1 | expression>, <column 2 | expression>,<column 3 | expression> FROM <table 2 name> or INSERT INTO <table 1 name> SELECT * FROM <table 2 name>

Page 10of 21

The UPDATE statement is used to modify existing data in a table. If the keyword DEFAULT is used as the <value> and a default value was set for the column, Oracle sets the column to the default value. However, if no default value was set when the column was created, Oracle inserts a null value. UPDATE <table> SET <column> = <value or subquery> WHERE <condition for row select> Using the MERGE statement accomplishes two tasks at the same time. MERGE will INSERT and UPDATE simultaneously. If a value is missing, a new one is inserted, if a value exists, but needs to be changed, MERGE will update it. For each row in the target table for which the search condition is true, Oracle Database updates the row with corresponding data from the source table. If the condition is not true for any rows, then the database inserts into the target table based on the corresponding source table row. MERGE INTO <target table> USING <source table or subquery> ON <condition> WHEN MATCHED THEN UPDATE SET <target column 1> = <source column | expression>, <target column 2> = <source column | expression>, <target column n> = <source column | expression> WHEN NOT MATCHED THEN INSERT (<target column 1 | expression>, <target column 2 | expression>, <target column n | expression>) VALUES (<value 1>, <value 2>, <value n>) 13. DATA RETRIEVAL The DESCRIBE command displays the structure of a table. DESCRIBE <table name> The SELECT * command returns all the rows in a table. SELECT * FROM <table name> To return a subset of the data, modify the SELECT statement. SELECT <column 1 name>, <column n name> Use DISTINCT to eliminate duplicate rows. SELECT DISTINCT .. 14. CASE MANIPULATION FUNCTIONS Use the UPPER function to convert alpha characters to upper case. UPPER (<column | expression>) Use the LOWER function to convert alpha characters to lower case. LOWER (<column | expression>) Use the INITCAP function to convert alpha character values to uppercase for the first letter of each word. INITCAP (<column | expression>) 15. CHARACTER MANIPULATION FUNCTIONS In the LIKE function the % symbol is used to represent any sequence of zero or more characters. The underscore _" symbol is used to represent a single character. The backward slash \ is used to indicate that the underscore or % is part of the name not a wildcard value. If you are searching for a character at the beginning of the string, place the % symbol after the character. If you are searching for a character at the end of the string, place the % symbol before the character. If you are searching for a group of characters, place the characters in between a set of % symbols. The CONCAT function joins two string values together. A shortcut symbol || may also be used. CONCAT (<column 1 | expression 1>, <column 2 | expression 2>) <column 1 | expression 1> || <column 2 | expression 2> The SUBSTR function extracts a string of a determined length SUBSTR (<column | expression>, <1st character number>, <number of characters>)
Page 11of 21

The LENGTH function shows the length of a string as a number value LENGTH (<column | expression>) The INSTR function finds the numeric position of a named character INSTR (<column | expression>, <character>) The LPAD function pads the left-hand side of a character resulting in a right justified value LPAD (<column | expression>, <number of positions>, <pad character>) The RPAD function pads the right-hand side of a character string resulting in a left justified value RPAD (<column | expression>, <number of positions>, <pad character>) The TRIM function removes all specified characters either from the beginning and/or the ending of a string. If none of these are chosen (i.e. leading, trailing, both), the trim function will remove [the character(s) to be removed] from both the front and end of [string to trim] TRIM (LEADING|TRAILING|BOTH '<character to be trimmed>' FROM <column | expression>) The REPLACE function replaces a sequence of characters in a string with another set of characters. REPLACE (<string column or expression>, <string to replace>, <replacement string>) where string column or expression is the string that will have characters replaced in it, string to replace is the string that will be searched for and taken out of string column or expression and replacement string is the new string to be inserted in string column or expression. To convert a string value to a number so that arithmetic operations can be performed use the TO_NUMBER function. Oracle Server displays a string of hash signs(#) in place of a whole number whose digits exceed the number of digits provided in the format model and rounds numbers to the decimal place provided in the format model. TO_NUMBER (<column | expression>, <format model>) where format model is: 9 for a numeric position (number of 9s determine width) 0 to display leading zeroes $ for a floating dollar sign L for a floating local currency symbol . to specify a decimal point in the position indicated , to specify a comma in the position indicated MI for a minus signs to the right for negative values PR to parenthesize negative numbers EEEE for scientific notation V to multiply by 10 n times (n=number of 9s after V) B to display zero values as blank, not 0 To convert a non-date value character string to a date value use the TO_DATE function. TO_DATE (<column | expression>, <format model>) This conversion takes a non-date value character string such as 'November 3, 2001' and converts it to a date value. The format model tells the server what the character string "looks like". The fx format means "format exact" so the fxdate of the format model must exactly match the format of the date being converted. When making a character to date conversion, the fx modifier specifies exact matching for the character argument and the date format model. Punctuation and quoted text in the character argument must match the corresponding parts of the format model exactly (except for case). The character argument can not have extra blanks. Without fx, the Oracle Server 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. If the date format is specified with the YY or YYYY format, the return value will be in the same century as the current century. So, if the year is 1995 and you use the YY or YYYY format, all is well and the dates will be in the 1900's. However, if the current year is 2004 and you use the YY or YYYY format for a date like 1989, you will get 2089! If the date format is specified with the RR or RRRR format, the return value has two possibilities: If the current year is between 00 - 49 - dates from 0 - 49 The date will be in the current century - dates from 50 - 99 The date will be in the last century
Page 12of 21

If the current year is between 51 - 99 - dates from 0 - 49 The date will be in next century - dates from 50 - 99 The date will be in current century 16. NUMBER MANIPULATION FUNCTIONS The ROUND function is used to round numbers to a specified number of decimal places. ROUND can also be used to round numbers to the left of the decimal point and with dates. If the number of decimal places is not specified or is zero, the number will round to NO decimal places. If the number of decimal places is a positive number, the number is rounded to that number of decimal places. If the number of decimal places is a negative number, numbers to the left of the decimal are rounded. ROUND (<column | expression>, <number of decimal places>) The TRUNC function is used to terminate the column, expression, date or value to a specified number of decimal places. When using TRUNC, if the number of decimal places is not specified, then the specified number defaults to zero. TRUNC (<column | expression>, <number of decimal places>) The MOD function is used to return the remainder when one number is divided by another. MOD (<column | expression>, <column | expression>) To convert columns of number data to a desired format use the TO_CHAR function. TO_CHAR (<column | expression>, '<format model>') where format model is: 9 for a numeric position (number of 9s determine width) 0 to display leading zeroes $ for a floating dollar sign L for a floating local currency symbol . to specify a decimal point in the position indicated , to specify a comma in the position indicated MI for a minus signs to the right for negative values PR to parenthesize negative numbers EEEE for scientific notation V to multiply by 10 n times (n=number of 9s after V) B to display zero values as blank, not 0 The POWER function is used to perform exponential calculations. Positive exponent numbers (n) are used to raise to a desired power, xn. Fractional exponent numbers (1/n) are used to extract roots, i.e.x1/n. Rounding is suggested when extracting roots. POWER (<column | expression>, exponent) 17. DATE MANIPULATION FUNCTIONS To subtract two dates: (<column | 1st date> - <column | 2nd date>) To subtract a fixed number from a date: (<column | date> - <number in days>) To add a fixed number to a date: (<column | date> + <number in days>) To determine the difference between two dates use the MONTHS_BETWEEN function. It is useful to use the ROUND function to restrict output. The function returns a negative number if the more recent date is stated last. ROUND (MONTHS_BETWEEN (<column | 1st date> - <column | 2nd date>), <number of decimal places>) To determine a specific day use the NEXT_DAY function. NEXT_DAY (<column | date>, 'DAY OF WEEK') To determine the last day of the month for a specific date use the LAST_DAY function. LAST_DAY (<column | date>)
Page 13of 21

To add months to a specific date use the ADD_MONTHS function. ADD_MONTHS (<column | date>, <number of months to add>) To convert a date to a character string use the TO_CHAR function. Any valid date format element can be included (See table). TO_CHAR (<column | date>, '<format model>') Use an fm element to remove padded blanks or remove leading zeroes from the output Use sp to spell out a number Use th to add st, nd, rd, or th to a number Use double quotation marks to add character strings to format models Use HH:MM:SS for time (HH24 for 24 hour notation; am for AM/PM notation)

AD, A.D. AM, A.M. BC, B.C. D DAY DD DDD DY FM FX HH HH12 HH24 IW IYYY J MI MM MON MONTH PM, P.M. Q RM RR RRRR SS SSSSS WW W X Y,YYY YEAR SYEAR YYYY, YYY, YY, Y SYYYY.

Day of week (1-7). Name of day, padded with blanks to length of 9 characters. Day of month (1-31). Day of year (1-366). Abbreviated name of day. Returns a value with no leading or trailing blanks. Requires exact matching between the character data and the format model. Hour of day (1-12). Hour of day (1-12). Hour of day (0-23). Week of year (1-52 or 1-53) based on the ISO standard. 4-digit year based on the ISO standard. Julian day; the number of days since January 1, 4712 BC. Number specified with J must be integers. Minute (0-59). Month (01-12; January = 01). Abbreviated name of month. Name of month, padded with blanks to length of 9 characters. Quarter of year (1, 2, 3, 4; January - March = 1). Roman numeral month (I-XII; January = I). Lets you store 20th century dates in the 21st century using only two digits. Round year. Accepts either 4-digit or 2-digit input. If 2-digit, provides the same return as RR. If you do not want this functionality, then enter the 4-digit year. 0 to 59.9(n), where 9(n) is the precision of interval fractional seconds Seconds past midnight (0-86399). Week of year (1-53) where week 1 starts on the first day of the year and continues to the seventh day of the year. Week of month (1-5) where week 1 starts on the first day of the month and ends on the seventh. Local radix character. Year with comma in this position. -4712 to 9999 (excluding year 0) Year, spelled out; S prefixes BC dates with a minus sign (-). Year or last 3, 2, 1 digits of year 4-digit year; S prefixes BC dates with a minus sign

Page 14of 21

18. NULL VALUE FUNCTIONS The NVL function converts a null value to either a date, a character or a number. The data types of the null value column and the new value must be the same. NVL (<value that may contain a null>, <value to replace the null>) The NVL2 function evaluates an expression with three values. If the first value is NOT null, then the NVL2 function returns the second expression. If the first value IS null, then the third expression is returned. The values in expression 1 can have any data type. Expression 2 and expression 3 can have any data type except LONG. The data type of the return value is always the same as the data type of expression 2, unless expression 2 is character data, in which it case the return type is VARCHAR2. NVL2 (<expression 1 value that may contain a null>, <expression 2 value to return if expression 1 is NOT null>, <expression 3 value to replace if expression 1 IS null>) The NULLIF function compares two functions. If they are equal, the function returns null. If they are not equal, the function returns the first expression. NULLIF (<expression 1>, <expression 2>) The COALESCE function is an extension of the NVL function except COALESCE can take multiple values. The world coalesce literally means to come "together" and that is what happens. If the first expression IS null, the function continues down the line until a NOT null expression is found. Of course, if the first expression has a value, the function returns the first expression and the function stops. COALESCE (<expression 1>, <expression 2>, <expression n>) 19. CONDITIONAL FUNCTIONS The CASE expression basically does the work of an IF-THEN-ELSE statement. The syntax for CASE is: CASE expression WHEN <comparison_expression 1> THEN <return_expression 1> WHEN <comparison_expression 2> THEN <return_expression 2> WHEN <comparison_expression n>THEN <return_expression n> ELSE <else_expresssion> END The DECODE function evaluates an expression in a similar way to the IF-THEN-ELSE logic (Oracle propriety). DECODE compares an expression to each of the search values. The syntax for DECODE is: DECODE (<column l | expression>, search 1, result 1 [, search 2, result 2, search n, result n] [, default]) Note: If the default value is omitted, a null value is returned where a search value does not match any of the values. 20. JOINS Joins allow you to select data from more than one table. There are two classes of JOINS: Oracle Syntax and ANSI SQL:1999 Standard (See table). ORACLE Equijoin Outerjoin Selfjoin Nonequijoin Cartesian Product ANSI SQL:1999 Natural or Inner Join Left/Right/Full Outer Join Join ON Join USING Cross Join

In any join three conditions must be met for the join to take place: WHAT? The SELECT clause specifies the column names to retrieve. WHERE? The FROM clause specifies the two tables that the database must access. HOW? The WHERE clause specifies how the tables are to be joined

Page 15of 21

21. ORACLE JOINS EQUIJOIN Sometimes called a simple or inner join, an equijoin is a table join that combines rows that have equivalent values for the specified columns. SELECT <table 1>.<column>, <table 2>.<column> FROM <table 1>, <table 2> WHERE <table 1>.<column> = <table 2>.<column> CARTESIAN PRODUCT JOIN If two tables in a join query have no join condition specified in the WHERE clause or the join condition is invalid, the Oracle Server returns the Cartesian product of the two tables. This is a combination of 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! This may not be what you were trying to retrieve. SELECT <column 1>, <column 2> FROM <table 1>, <table 2> NONEQUIJOIN A nonequijoin is a join condition containing something other than the equality operator. It is used when you want to retrieve data from a table that has no corresponding column in another table. Use a nonequijoin when the joining of two columns in different tables does not have matching values. Instead, the match occurs within a range of values. SELECT <table 1>.<column 1>, <table 1>.<column 2>, <table 2>.<column 1> FROM <table 1>, <table 2> WHERE <table 1>.<column 1> < <table 2>.<column 2> or SELECT <table 1>.<column 1>, <table 2>.<column 1> FROM <table 1>, <table 2> WHERE <table 1>.<column 1> BETWEEN <table 2>.<column 2> AND <table 2>.<column 3> OUTER JOIN An outer join is used to see rows that have a corresponding value in another table PLUS those rows in one of the tables that have no matching value in the other table. To indicate which table may have missing data use a (+) sign after the table's column name in the query. Think of the (+) being used to fill in missing data in a column. Put the plus next to that column. Visualize plus signs filling in all the gaps. Do not place the (+) sign in both columns. SELECT <table 1>.<column 1>, <table 2>.<column 1> FROM <table 1>, <table 2> WHERE <table 1>.<column 1>(+) = <table 2>.<column 1> Left Outer WHERE <table 1>.<column 1> = <table 2>.<column 1>(+) Right Outer SELF JOIN In data modeling, it was sometimes necessary to show an entity with a relationship to itself. A special kind of join called a self join is required to access this data. To join a table to itself, the table is given two names or aliases. This will make the database think that there are two tables. Choose alias names that relate to the data's association with that table. SELECT <a.column 1>, <a.column 2>, <b.column 1> FROM <table 1> a, <table 1> b WHERE <a.column 2> = <b.column 1> 22. ANSI JOINS NATURAL JOIN A NATURAL JOIN is based on all columns in the two tables that have the same name and selects rows from the two tables that have equal values in all matched columns. SELECT <column 1>, <column 2> FROM <table 1> NATURAL JOIN <table 2>

Page 16of 21

CROSS JOIN This is this ANSI version of a Cartesian Product Join. SELECT <column 1>, <column 2> FROM <table 1> CROSS JOIN <table 2> JOIN USING In a NATURAL JOIN, if the tables have columns with the same names but different data types, the join causes an error. To avoid this situation, the join clause can be modified with a USING clause. The USING clause specifies the columns that should be used for the join. The columns referenced in the USING clause should not have a qualifier (table name or alias) anywhere in the SQL statement. SELECT <table 1>.<column 1>, <table 2>.<column 1> FROM <table 1> JOIN <table 2> USING (<column x>) JOIN ON The ON clause can be used to specify columns to join. The advantage of the ON clause is the ability to specify the join conditions separate from the WHERE clause. The WHERE clause can then be used for search or filter conditions. The ON clause can also be used to specify arbitrary conditions such as joining columns that have different names. SELECT <table 1>.<column 1>, <table 1>.<column 2>, <table 2>.<column 1>, <table 2>.<column 2> FROM <table 1> JOIN <table 2> ON (<table 1>.<column 1> = <table 2>.<column 1>) OUTER JOINS In ANSI SQL, joins of two or more tables that return only matched rows are referred to as INNER joins. When a join returns the matched rows as well as unmatched rows it is called an OUTER join. OUTER join syntax uses the terms LEFT, FULL, and RIGHT. These names are associated with the order of the table names in a query. The results set of a FULL OUTER JOIN includes all rows in both tables even if there is no match in the other table. The following examples compare ANSI and Oracle Outer Joins. Show all Employees even if they are not assigned to a Department: SELECT e.last_name, e.department_id, d.department_name FROM employees e LEFT OUTER JOIN departments d ON (e.department_id = d.department_id) is equivalent to SELECT e.last_name, e.department_id, d.department_name FROM employees e, departments d WHERE e.department_id = d.department_id(+) Show all Department Names even if there is no one assigned to that Department: SELECT e.last_name, e.department_id, d.department_name FROM employees e RIGHT OUTER JOIN departments d ON (e.department_id = d.department_id) is equivalent to SELECT e.last_name, e.department_id, d.department_name FROM employees e, departments d WHERE e.department_id(+) = d.department_id Show all Employees even if they are not assigned to a Department and Show all Department Names even if there is no one assigned to that Department: SELECT e.last_name, e.department_id, d.department_name FROM employees e FULL OUTER JOIN departments d ON (e.department_id = d.department_id)

Page 17of 21

23. GROUP FUNCTIONS Group functions operate on sets of rows to give one result per group. The AVG, SUM, STDDEV and VARIANCE functions can be used against columns that can store numeric data types. The COUNT, MAX and MIN functions can be used for any data type. Group functions ignore null values. You may include the NVL function to force group functions to include null values. The COUNT function returns the number of rows with non-null values. Group functions may be written in the SELECT, HAVING and ORDER clauses. Because aggregate functions (like SUM) return the aggregate of all column values every time they are called, it would be impossible to find the sum for each individual group of column values. Use the DISTINCT keyword to suppress the counting of any duplicate value within a column. The GROUP BY clause enables aggregate data to be applied to groups of column values. If you include a group function in a SELECT clause and any other individual columns, each individual column must also appear in the GROUP BY clause. You cannot use a column alias in the GROUP BY clause. The WHERE clause excludes rows before they are divided into groups. A GROUP BY clause can be used in a SELECT statement without having a group function in the SELECT statement. Group functions can be nested to a depth of two. In order to restrict rows returned with aggregate functions, you must use a HAVING clause. Aggregate functions cannot appear in the WHERE clause. The HAVING clause was added to SQL to be able to restrict the returned rows when using an aggregate function. Use the HAVING clause to restrict groups. SELECT <GROUP FUNCTION>(<column 1 | expression>), <column 2 | expression> FROM <table> GROUP BY <column 2 | expression> HAVING <GROUP FUNCTION>(<condition>) 24. SUBQUERIES A subquery is the combination of two queries, placing one query inside the other query to return one result. The inner query is called the subquery and is evaluated first and returns one value that is used by the outer query or main query. The subquery executes to find the information you dont know. The outer query uses that information to find out what you need to know. Being able to combine two queries into one can be very useful when you need to select rows from a table with a condition that depends on the data in the table itself. The outer and inner queries can get data from different tables. A subquery is a SELECT statement that is embedded in a clause of another statement. Group functions can be used in subqueries as they return a single row. Subqueries can be placed in a number of SQL clauses, including the WHERE clause, the HAVING clause and the FROM clause. The only limit on the number of subqueries is the buffer size the query uses. There are two types of subqueries: Single-row subqueries that use single-row operators (<, >, =, >=, <=, <>) and return only one row from the inner query Multiple-row subqueries that use multiple-row operators (IN, ANY, ALL) and return more than one row from the inner query. The NOT operator can be used with any of these three operators. IN The IN operator is used when the outer query WHERE clause is designed to restrict rows based on a list of values returned from the inner query. The IN operator is equivalent to = ANY. ANY The ANY operator is used when the outer query WHERE clause is designed to restrict rows based on any value returned from the inner query. This means that the outer query must do a comparison to each value returned. The outer query selects any row that is equal to any of the inner query values returned. ALL The ALL operator is used when the outer query WHERE clause is designed to restrict rows based on all values returned from the inner query. The outer query selects only those rows that are greater than ALL of the inner query values. The ALL operator compares a value to every value returned by the inner query. When a multiple-row subquery uses the NOT IN( <> ALL) operator, if one of the values returned by the inner query is a null value, the entire query returns no rows. When in reality, there were other rows that should be returned. The reason for the "no rows returned is that all conditions that compare a null value, result in null remember null is NOT a number or value - it's just not anything. To avoid this mistake, when there is a chance
Page 18of 21

that null values may be returned by the inner query, use the IN (= ANY) operator. This is a safer choice because if there isn't a value in the results set, then there are truly no values that satisfy the WHERE clause. SELECT <column | expression> FROM <table> WHERE <condition> <operator> (SELECT <column | expression> FROM <table>) 25. DATA DICTIONARY The Oracle data dictionary is one of the most important components of the Oracle DBMS. The tables and views provided by the data dictionary contain information about: users and their privileges tables, columns and their data types, integrity constraints, indexes statistics about tables and indexes used by the optimizer privileges granted on database objects storage structures of the database The data dictionary consists of two levels: the internal level contains all base tables that are used by the various DBMS software components. These are normally not accessible to end users. The external level provides numerous views on these base tables to access information about objects and structures at different levels of detail. An installation of an Oracle database always includes the creation of three standard Oracle users: SYS is the owner of all data dictionary tables and views. This user has the most privileges for managing objects and structures of an Oracle database such as creating new users. SYSTEM is the owner of tables used by different tools such SQL*Forms, SQL*Reports etc. This user has fewer privileges than SYS. PUBLIC is a dummy user in an Oracle database. All privileges assigned to this user are automatically assigned to all users known in the database. You can query the data dictionary to view various database objects owned by you. To access the data dictionary use the SQL command shown: SELECT * FROM DICTIONARY The data dictionary tables frequently used are USER_TABLES, USER_OBJECTS, USER_UPDATABLE_COLUMNS and USER_CATALOG or USER_CAT To see the names and characteristics of tables owned by you the user. SELECT * FROM user_tables To view distinct object types owned by the user. SELECT DISTINCT <object_type> FROM user_objects To view all objects owned by the user. SELECT * FROM user_catalog To view the columns which will allow UPDATE, INSERT or DELETE. SELECT * FROM USER_UPDATABLE_COLUMNS WHERE table_name = '<TABLE> NOTE: All table names in the data dictionary are stored in uppercase.

Page 19of 21

26. CONTROLLING USER ACCESS In a multiple-user environment, you want to maintain security of the database access and use. With Oracle server database security, you can control database access, give access to specific objects in the database, confirm given and received privileges within the Oracle data dictionary and create synonyms for database objects. PRIVILEGES Privileges are the right to execute particular SQL statements. The database administrator (DBA) is a high-level user with the ability to grant users access to the database and its objects. The users require system privileges to gain access to the database and object privileges to manipulate the content of the objects in the database. Users can also be given the privilege to grant additional privileges to other users or to roles, which are named groups of related privileges. DBA's generally allocate system privileges; any user who owns an object can grant object privileges. SCHEMA A schema is a collection of objects, such as tables, views, and sequences. The schema is owned by a database user and has the same name as that user. In this course, your schema name is a combination of your city, state/country, your school name, course name and student number - USWA_SKHS_SQL01_S22. Database security can be classified into two categories: system security and data security. SYSTEM SECURITY This level of security covers access and use of the database at the system level. There are more than 100 distinct system privileges. The system level privileges such the ability to create or remove users, remove tables or backup tables, the disk space allocated to users, and the system operations that users can perform, is the job of the DBA. DBA SYSTEM PRIVILEGES SUMMARY TABLE To be Supplied OBJECT PRIVILEGES TABLE To be supplied ROLES A role is a named group of related privileges that can be granted to the user. This method makes it easier to revoke and maintain privileges. A user can have access to several roles, and several users can be assigned the same role. Roles are typically created for a database application using the CREATE ROLE statement. To create and assign a role the DBA must first create the role. After the role is created, the DBA can use the GRANT statement to assign users to the role as well as assign privileges to the role. CREATE ROLE <role name> GRANTING OBJECT PRIVILEGES To grant object privileges use the GRANT command. You can grant UPDATE, REFERENCES, and INSERT privileges on individual columns on a table. A SELECT privilege can be restricted by creating a view with a subset of columns and granting the SELECT privilege only on the view. You can't grant SELECT on individual columns. A privilege granted on a synonym is converted to a privilege on the base table referenced by the synonym. In other words, a synonym is simply a new easier to use name, using this name to grant a privilege is the same as granting the privilege on the table itself. To grant privileges on an object, the object must be in your own schema, or you must have been granted the object privileges WITH GRANT OPTION. A privilege that is granted using the WITH GRANT OPTION clause can be passed on to other users and roles by the grantee. This means that a long chain of grantees is possible, but no circular grants are permitted. Object privileges granted using the WITH GRANT OPTION clause are revoked when the grantors privilege is revoked. An object owner can grant any object privilege on the object to any other user or role of the database. The owner of an object automatically acquires all object privileges on that object. An owner of a table can grant access to all users by using the PUBLIC keyword. GRANT <object privilege> [(<column 1>, <column 2>, <column n>)] ON <object> FROM {<user 1>[, <user 2>, <user n>] | <role> | [PUBLIC]} [WITH GRANT OPTION]

Page 20of 21

REVOKING OBJECT PRIVILEGES You can remove privileges granted to other users by using the REVOKE statement. When you use the REVOKE statement, the privileges that you specify are revoked from the users you name and from any other users to whom those privileges were granted through the WITH GRANT OPTION clause. CASCADE CONSTRAINTS is required to remove any referential integrity constraints made to the object by means of the REFERENCES privilege. REVOKE {<privilege 1> [, <privilege 2>, <privilege n> [ALL]} ON <object> FROM {<user 1>[, <user 2>, <user n>] | <role> | [PUBLIC]} [CASCADE CONSTRAINTS] DATABASE LINKS A database link is a pointer that defines a one-way communication path from an Oracle database server to another database server. The link pointer is actually defined as an entry in a data dictionary table. To access the link, you must be connected to the local database that contains the data dictionary entry. A database link connection is one-way in the sense that a client connected to local database A can use a link stored in database A to access information in remote database B, but users connected to database B cannot use the same link to access data in database A. If local users on database B want to access data on database A, they must define a link that is stored in the data dictionary of database B. A database link connection gives local users access to data on a remote database. For this connection to occur, each database in the distributed system must have a unique global database name. The global database name uniquely identifies a database server in a distributed system. The great advantage of database links is that they allow users to access another users objects in a remote database so that they are bounded by the privilege set of the objects owner. In other words, a local user can access a remote database without having to be a user on the remote database. Typically, the DBA is responsible for creating the database link. The dictionary view USER_DB_LINKS contains information on links to which a user has access. The USING clause identifies the service name of a remote database. Once the database link is created, you can write SQL statements against the data in the remote site. If a synonym is set up, you can write SQL statements using the synonym. You cannot grant privileges on remote objects. CREATE PUBLIC SYNONYM <synonym name> FOR <remote user> i.e., emp@hq.acme.com Then write a SQL statement that uses the synonym: SELECT * FROM <synonym name>

Page 21of 21

También podría gustarte