Oracle Training
Instructor
Siemens Greece D.I.P.
2.2006
Page 1
Training Index
Writing a BASIC SQL statement Retrieving Data Using the SQL SELECT Statement Restricting and Sorting Data Using Single Row Functions to Customize Reports Reporting Aggregated Data Using the Group Functions Displaying Data From Multiple Tables Subqueries Using the SET Operators Manipulating Data Create and Manage Tables Creating and Manage other Schema Objects Controlling User Access Hierarchical Data Retrieval Data Dictionary Views
Siemens Greece D.I.P.
2.2006
Page 2
Querying data
Select
Controlling transactions
Commit Rollback Savepoint
Page 3
DEPT
SALGRADE
Siemens Greece D.I.P.
2.2006
Page 4
Page 5
SELECT [DISTINCT] {*, column [alias],...} FROM table; SQL statements are not case sensitive. SQL statements can be on one or more lines. Keywords cannot be abbreviated or split across lines. Clauses are usually placed on separate lines. Tabs and indents are used to enhance readability.
Page 6
Operator * / +
Multiplication and division take priority over addition and subtraction. Operators of the same priority are evaluated from left to right. Parentheses are used to force prioritized evaluation and to clarify statements.
Page 7
A null is a value that is unavailable, unassigned, unknown, or inapplicable. A null is not the same as zero or a blank space. Arithmetic expressions containing a null value evaluate to null.
Page 8
Renames a column heading Is useful with calculations Immediately follows column name; optional AS keyword between column name and alias Requires double quotation marks if it contains spaces or special characters or is case sensitive
Page 9
Concatenates columns or character strings to other columns Is represented by two vertical bars (||) Creates a resultant column that is a character expression
Page 10
A literal is a character, a number, or a date included in the SELECT list. Date and character literal values must be enclosed within single quotation marks. Each character string is output once for each row returned.
Page 11
Eliminate duplicate rows by using the DISTINCT keyword in the SELECT clause.
Page 12
Restrict the rows returned by using the WHERE clause. The WHERE clause follows the FROM clause.
Page 13
Character strings and date values are enclosed in single quotation marks. Character values are case sensitive and date values are format sensitive. The default date format depends on system configuration.
Page 14
<=
<> Between . And . In (item1,item2,,itemn) Is Null
Page 15
Use the LIKE operator to perform wildcard searches of valid search string values. Search conditions can contain either literal characters or numbers.
% denotes zero or many characters. _ denotes one character.
Page 16
Page 17
Meaning Returns TRUE if both component conditions are TRUE (2) Returns TRUE if either component condition is TRUE (3) Returns TRUE if the following condition is FALSE (1)
Page 18
SELECT [DISTINCT] {*| column [alias], ...} FROM table [WHERE condition(s)]; [ORDER BY {column | alias | order in select [ASC|DESC], ...} ] Sort rows with the ORDER BY clause
ASC: ascending order, default DESC: descending order
Page 19
Single-Row Functions
Manipulate data items Accept arguments and return one value Act on each row returned Return one result per row May modify the datatype Can be nested
Page 20
Character
General
Single-row functions
Number
Conversion
Date
Page 21
Page 22
Number functions
ROUND (round value to specific decimal) TRUNC (truncate value to specific decimal) MOD (remainder of division) ABS (absolute value)
Page 23
Oracle stores dates in an internal numeric format: century, year, month, day, hours, minutes, seconds. The default date format depends on system configuration. SYSDATE is a function returning date and time. DUAL is a dummy table used to view SYSDATE. Add or subtract a number to or from a date for a resultant date value. Subtract two dates to find the number of days between those dates. Add hours to a date by dividing the number of hours by 24.
Page 24
Date functions
MONTHS_BETWEEN (number of months between two dates) ADD_MONTHS (add calendar months to date) NEXT_DATE (next day of the date specified) LAST_DATE (last day of the month) ROUND (round date ) TRUNC (truncate date)
Page 25
Implicitly Conversion
From VARCHAR/CHAR to NUMBER From VARCHAR/CHAR to DATE
Explicitly Conversion
VARCHAR/CHAR to NUMBER using function TO_NUMBER NUMBER to VARCHAR/CHAR using function TO_CHAR VARCHAR/CHAR to DATE using function TO_DATE DATE to VARCHAR/CHAR using function TO_CHAR
Formta Model YYYY YEAR Full year in number Year spellout Meaning
MM
MONTH DY DAY
Page 26
Page 27
Page 28
Group functions operate on sets of rows to give one result per group. Group functions ignore null values in the column. Group functions can be nested.
Page 29
AVG (average value) COUNT (counts rows) MAX (maximum value) MIN (minimum value) STDDEV (standard deviation) SUM (sum of values) VARIANCE (variance)
Page 30
Divide rows in a table into smaller groups by using the GROUP BY clause. All columns in the SELECT list that are not in group functions must be in the GROUP BY clause. The GROUP BY column does not have to be in the SELECT list.
Page 31
Page 32
Use ROLLUP or CUBE with GROUP BY to produce superaggregate rows by cross-referencing columns. ROLLUP grouping produces a result set containing the regular grouped rows and the subtotal values. CUBE grouping produces a result set containing the rows from ROLLUP and cross-tabulation rows.
Page 33
ROLLUP is an extension to the GROUP BY clause. You can use the ROLLUP operation to produce cumulative aggregates such as subtotals.
Page 34
CUBE is an extension to the GROUP BY clause. You can use the CUBE operator to produce cross-tabulation values.
Page 35
SELECT table1.column, table2.column FROM table1 [CROSS JOIN table2] | [NATURAL JOIN table2] | [JOIN table2 USING (column)] | [JOIN table2 ON (table1.column= table2.column)] | [LEFT|RIGHT|FULL OUTER JOIN table2 ON (table1.column= table2.column)];
Page 36
To avoid a Cartesian product, always include a valid join condition in a WHERE clause.
Page 37
Cartesian
CROSS JOIN
Page 38
Subqueries
SELECT select_list FROM table WHERE expr operator (SELECT select_list FROM table); The subquery (inner query) executes once before the main query. The result of the subquery is used by the main query (outer query). 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.
Page 39
Single-row subquery
Return only one row Use single-row comparison operators (=,>,>=,<,<=,<>)
Multiple-row subquery Return more than one row Use multiple-row comparison operators (IN,ANY,ALL)
<ANY means less than the maximum. >ANY means more than the minimum. =ANY is equivalent to IN >ALL means more than the maximum <ALL means less than the minimum.
Multiple-column subquery
Pairwise Nonpairwise
The subquery references a column from the table in the parent query.
Page 41
Page 42
B Intersect
B
Union/Union All
B Minus
Page 43
UNION is the combination of two tables. Use the UNION operator to return all rows from multiple queries and eliminate any duplicate rows.
The number of columns and the data types of those columns must be identical between the two SELECT statements. The names of the columns need not be identical. UNION operates over all of the columns being selected. NULL columns are ignored during duplicate checking. Queries that use UNION in the WHERE clause must have the same number and type of columns in their SELECT list. The output is sorted in ascending order by default.
Page 44
Use the UNION ALL operator to return all rows from multiple queries.
Unlike UNION, duplicate rows are not eliminated and the output is not sorted by default. The DISTINCT keyword cannot be used.
Page 45
Use the MINUS operator to return rows returned by the first query but not the second query (the first select statement MINUS the second select statement).
The number of columns and the data types of those columns must be identical between the two SELECT statements. The names of the columns need not be identical. All of the columns in the WHERE clause must be in the SELECT clause for the MINUS operator query to work. Queries that use MINUS in the WHERE clause must have the same number and type of columns in their SELECT list.
Page 46
Use the INTERSECT operator to return all common rows in both queries.
The number of columns and the data types of those columns must be identical between the two SELECT statements. The names of the columns need not be identical. Reversing the order of the Intersected tables does not alter the result. INTERSECT, like UNION, ignores NULL columns. Queries that use INTERSECT in the WHERE clause must have the same number and type of columns in their SELECT list.
Page 47
A transaction consists of a collection of DML statements that form a logical unit of work.
Page 48
Add new rows to a table by using the INSERT statement. Only one row is inserted at a time with this syntax. Insert a new row containing values for each column. List values in the default order of the columns in the table. Optionally list the columns in the INSERT clause. Enclose character and date values within single quotation marks. Inserting rows with null values
Implicit method: Omit the column from the column list. Explicit method: Specify the NULL keyword.
Page 49
INSERT INTO
table [(column [, column...])] select [(column [, column...])] from table [WHERE condition];
Write your INSERT statement with a subquery. Do not use the VALUES clause. Match the number of columns in the INSERT clause to those in the subquery.
Page 50
Modify existing rows with the UPDATE statement. Update more than one row at a time, if required.
Specific row or rows are modified when you specify the WHERE clause. All rows in the table are modified if you omit the WHERE clause.
Page 51
DELETE [FROM] table [WHERE condition]; You can remove existing rows from a table by using the DELETE statement. Specific rows are deleted when you specify the WHERE clause. All rows in the table are deleted if you omit the WHERE clause.
Page 52
Begin when the first executable SQL statement is executed End with one of the following events:
COMMIT or ROLLBACK is issued
Ensure data consistency Preview data changes before making changes permanent Group logically related operations
DDL or DCL statement executes (automatic commit) User exits System crashes
Page 53
Ensure data consistency Preview data changes before making changes permanent Group logically related operations
Transaction
INSERT INSERT
COMMIT
UPDATE
INSERT
Savepoint B
DELETE
Savepoint A
ROLLBACK
Page 54
Page 55
The previous state of the data can be recovered. The current user can review the results of the DML operations by using the SELECT statement. Other users cannot view the results of the DML statements by the current user. The affected rows are locked; other users cannot change the data within the affected rows.
Page 56
Data changes are made permanent in the database. The previous state of the data is permanently lost. All users can view the results. Locks on the affected rows are released; those rows are available for other users to manipulate. All savepoints are erased.
Page 57
Page 58
Create a marker in a current transaction by using the SAVEPOINT statement. Roll back to that marker by using the ROLLBACK TO SAVEPOINT statement.
Page 59
If a single DML statement fails during execution, only that statement is rolled back. The Oracle Server implements an implicit savepoint. All other changes are retained. The user should terminate transactions explicitly by executing a COMMIT or ROLLBACK statement.
Page 60
Read consistency guarantees a consistent view of the data at all times. Changes made by one user do not conflict with changes made by another user. Read consistency ensures that on the same data
Readers do not wait for writers Writers do not wait for readers
Page 61
Data blocks
Rollback segments
User A
SELECT * FROM emp;
User B
Page 62
Prevent destructive interaction between concurrent transactions Require no user action Automatically use the lowest level of restrictiveness
Are held for the duration of the transaction Have two basic modes
Exclusive Share
Page 63
CREATE [GLOBAL TEMPORARY] TABLE [schema.]table (column datatype [DEFAULT expr][, ...]);
You specify
Table name
Must begin with a letter Can be 130 characters long Must contain only AZ, az, 09, _, $, and # Must not duplicate the name of another object owned by the same user Must not be an Oracle Server reserved word
Page 64
Tables belonging to other users are not in the users schema. You should use the owners name as a prefix to the table.
Page 65
Specify a default value for a column during an insert. Legal values are literal value, expression, or SQL function. Illegal values are another columns name or pseudocolumn. The default datatype must match the column datatype.
Page 66
User Tables
Collection of tables created and maintained by the user Contain user information
Data Dictionary
Collection of tables created and maintained by the Oracle server Contain database information
Page 67
CREATE TABLE table [(column, column...)] AS subquery; Create a table and insert rows by combining the CREATE TABLE statement and AS subquery option. Match the number of specified columns to the number of subquery columns. Define columns with column names and default values.
Page 68
ALTER TABLE table ADD (column datatype [DEFAULT expr] [, column datatype]...); ALTER TABLE table MODIFY (column datatype [DEFAULT expr] [, column datatype]...); ALTER TABLE table DROP COLUMN (column [, column]...); Use the ALTER TABLE statement to
Add a new column Modify an existing column Define a default value for the new column
Page 69
table (column);
ALTER TABLE table SET UNUSED COLUMN column; ALTER TABLE table DROP UNUSED COLUMNS; You use the SET UNUSED option to mark one or more columns as unused. You use the DROP UNUSED COLUMNS option to remove the columns that are marked as UNUSED.
Page 70
DROP TABLE table; All data and structure in the table is deleted. Any pending transactions are committed. All indexes are dropped. You cannot roll back this statement.
Page 71
RENAME object_name TO new_object name; To change the name of a table, view, sequence, or synonym, you execute the RENAME statement. You must be the owner of the object.
Page 72
You cannot roll back row removal when using TRUNCATE. Alternatively, you can remove rows by using the DELETE statement.
Page 73
Page 74
Constraints enforce rules at the table level. Constraints prevent the deletion of a table if there are dependencies. The following constraint types are valid in Oracle
NOT NULL UNIQUE PRIMARY KEY FOREIGN KEY CHECK
Name a constraint or the Oracle Server will generate a name by using the SYS_Cn format. Create a constraint:
At the same time as the table is created After the table has been created
Page 75
CREATE TABLE [schema.]table (column datatype [DEFAULT expr] [column_constraint], ... [table_constraint][,...]);
Page 76
NOT NULL
Ensures that null values are not permitted for the column
Page 77
UNIQUE
Defined at either the table level or the column level Ensure uniqueness of a column
Page 78
PRIMARY KEY
Defined at either the table level or the column level Defines the primary key of the table
Page 79
FOREIGN KEY
CONSTRAINT costraint FOREIGN KEY (column [,column..]) REFERENCES table (column [,column..]) FOREIGN KEY Defines the column in the child table at the table constraint level REFERENCES Identifies the table and column in the parent table ON DELETE CASCADE Allows deletion in the parent table and deletion of the dependent rows in the child table Defined at either the table level or the column level
Page 80
CHECK
Defines a condition that each row must satisfy Expressions that are not allowed
References to CURRVAL, NEXTVAL, LEVEL, and ROWNUM pseudocolumns Calls to SYSDATE, UID, USER, and USERENV functions Queries
Page 81
ALTER TABLE table ADD/DROP [CONSTRAINT constraint] type (column); Add or drop, but not modify, a constraint Enable or disable constraints Add a NOT NULL constraint by using the MODIFY clause
Page 82
ALTER TABLE table ENABLE/DISABLE CONSTRAINT constraint ; Activate an integrity constraint currently disabled in the table definition by using the ENABLE clause. A UNIQUE or PRIMARY KEY index is automatically created if you enable a UNIQUE key or PRIMARY KEY constraint.
Page 83
Views are
Logically represents subsets of data from one or more tables
Types of views
Feature Number of tables Contain functions Contain groups of data DML through view Simple Views One No No Yes Complex Views One or More Yes Yes Not always
Siemens Greece D.I.P.
2.2006
Page 84
CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view [(alias[, alias]...)] AS subquery [WITH CHECK OPTION [CONSTRAINT constraint]] [WITH READ ONLY];
You embed a subquery within the CREATE VIEW statement. The subquery can contain complex SELECT syntax. The subquery cannot contain an ORDER BY clause.
Page 85
You can perform DML operations on simple views. You cannot remove a row if the view contains the following Group functions A GROUP BY clause The DISTINCT keyword The pseudocolumn ROWNUM keyword You cannot modify data in a view if it contains Any of the conditions mentioned mentioned above Columns defined by expressions You cannot add data if The view contains any of the conditions mentioned above There are NOT NULL columns in the base tables that are not selected by the view
Page 86
You can ensure that DML on the view stays within the domain of the view by using the WITH CHECK OPTION clause. Any attempt to change the columns in check option for any row in the view will fail because it violates the WITH CHECK OPTION constraint.
Page 87
You can ensure that no DML operations occur by adding the WITH READ ONLY option to your view definition. Any attempt to perform a DML on any row in the view will result in Oracle Server error.
Page 88
DROP VIEW view; Remove a view without losing data because a view is based on underlying tables in the database
Page 89
An inline view is a subquery with an alias (correlation name) that you can use within a SQL statement. An inline view is similar to using a named subquery in the FROM clause of the main query. An inline view is not a schema object.
Page 90
SELECT [column_list], ROWNUM FROM (SELECT [column_list] FROM table ORDER BY Top-N_column) WHERE ROWNUM <= N Top-N queries ask for the n largest or smallest values of a column.
What are the ten best selling products? What are the ten worst selling products ?
Both largest values and smallest values sets are considered Top-N queries.
Page 91
CREATE SEQUENCE sequence [INCREMENT BY n] [START WITH n] [{MAXVALUE n | NOMAXVALUE}] [{MINVALUE n | NOMINVALUE}] [{CYCLE | NOCYCLE}] [{CACHE n | NOCACHE}];
Automatically generates unique numbers Is a sharable object Is typically used to create a primary key value Replaces application code Speeds up the efficiency of accessing sequence values when cached in memory
Siemens Greece D.I.P.
2.2006
Page 92
NEXTVAL returns the next available sequence value. It returns a unique value every time it is referenced, even for different users. CURRVAL obtains the current sequence value. NEXTVAL must be issued for that sequence before CURRVAL contains a value.
Page 93
Caching sequence values in memory allows faster access to those values. Gaps in sequence values can occur when: A rollback occurs The system crashes A sequence is used in another table
Page 94
ALTER SEQUENCE sequence [INCREMENT BY n] [{MAXVALUE n | NOMAXVALUE}] [{MINVALUE n | NOMINVALUE}] [{CYCLE | NOCYCLE}] [{CACHE n | NOCACHE}]; Change the increment value, maximum value, minimum value, cycle option, or cache option.
You must be the owner or have the ALTER privilege for the sequence. Only future sequence numbers are affected. The sequence must be dropped and re-created to restart the sequence at a different number. Some validation is performed.
Page 95
DROP SEQUENCE sequence; Remove a sequence from the data dictionary by using the DROP SEQUENCE statement. Once removed, the sequence can no longer be referenced.
Page 96
Is a schema object
Created Automatically: A unique index is created automatically when you define a PRIMARY KEY or UNIQUE constraint in a table definition. Created Manually: Users can create nonunique indexes on columns to speed up access time to the rows.
Is used by the Oracle Server to speed up the retrieval of rows by using a pointer Can reduce disk I/O by using rapid path access method to locate the data quickly Is independent of the table it indexes Is used and maintained automatically by the Oracle Server
Page 97
CREATE INDEX index ON table (column[, column]...); Create an index on one or more columns when
The column is used frequently in the WHERE clause or in a join condition. The column contains a wide range of values. The column contains a large number of null values. Two or more columns are frequently used together in a WHERE clause or a join condition. The table is large and most queries are expected to retrieve less than 24% of the rows.
Page 98
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.
Page 99
DROP INDEX index; Remove an index from the data dictionary. To drop an index, you must be the owner of the index or have the DROP ANY INDEX privilege.
Page 100
Simplify access to objects by creating a synonym (another name for an object). Refer to a table owned by another user. Shorten lengthy object names.
Page 101
Database administrator
Page 102
Database security:
System security Data security
System privileges: Gain access to the database Object privileges: Manipulate the content of the database objects Schema: Collection of objects, such as tables, views, and sequences
Page 103
More than 100 privileges are available. The DBA has high-level system privileges: Create new users Remove users Remove tables Back up tables
Page 104
Page 105
Users
Manager
Page 106
CREATE ROLE role GRANT privilege [, privilege...] TO role [, role...]; CREATE SESSION CREATE TABLE CREATE SEQUENCE CREATE VIEW CREATE PROCEDURE ;
Page 107
Table
View
Sequence
Procedure
INDEX
INSERT REFERENCES
SELECT
UPDATE
Page 108
GRANT object_priv [(columns)] ON object TO {user|role|PUBLIC} [WITH GRANT OPTION]; Object privileges vary from object to object. An owner has all the privileges on the object. An owner can give specific privileges on that owners object.
Page 109
Give a user authority to pass along the privileges. Allow all users on the system to query data from table.
Page 110
You use the REVOKE statement to revoke privileges granted to other users. Privileges granted to others through the WITH GRANT OPTION will also be revoked. CASCADE is required to remove any referential integrity constraints made to the CONSTRAINTS object by means of the REFERENCES privilege.
Page 111
Hierarchical queries
SELECT [LEVEL], column, expr... FROM table [WHERE condition(s)] [START WITH condition(s)] [CONNECT BY PRIOR condition(s)]; Hierarchical queries are a facility that enable you to retrieve data based on a natural hierarchical relationship between rows in a table. CONNECT BY PRIOR column1 = column2 (parent key=child key walk top down child key=parent key walk buttom up)
Page 112
ALL_XXXXXX Object accesible by the user USER_XXXXXX Object owned by the user
Page 113
Description
View tables owned by the user View object owned by the user Comments on table columns
USER_TAB_COMMENTS
USER_CONSTRAINTS USER_CONS_COLUMNS
Comments on tables
View constraints View columns associated with constraints
Page 114
Description View Indexes owned by the user View columns associated with index View tables, views, synonyms, and sequences owned by the user
USER_VIEWS
USER_SEQUENCES USER_SYNONYMS
Page 115
ROLE_TAB_PRIVS
USER_ROLE_PRIVS USER_TAB_PRIVS_MADE
USER_TAB_PRIVS_RECD
USER_COL_PRIVS_MADE USER_COL_PRIVS_RECD
Page 116