* Data is retrieved from Oracle using SELECT statements.
*The syntax for a SELECT statement consists of SELECT.FROM.;.
*Expressions appearing after the keyword SELECT are part of the column clause, and are usually the names of columns from the table storing the data you wish to retrieve..
*Expressions appearing after the FROM keyword are part of the table clause, and are usually the names of tables you want to retrieve data from.
*When you’re entering a SELECT statement from the prompt using SQL*Plus, a semicolon (;) at the end of the statement or a slash (/) at the beginning of the first empty line appearing after the statement in your operating buffer must be used to terminate the statement.
*Arithmetic operations can be used to perform math operations on data selected from a table or on numbers using the DUAL table.
*The DUAL table is a table with one column and one row used to fulfill the syntactic requirements of SQL SELECT statements.
*Values in columns for particular rows may be empty (NULL).
*If a column contains a NULL value, you can use the NVL() function to return meaningful information instead of an empty field.
*Aliases can be used in place of the actual column name or to replace the appearance of the function name in the header.
*Output from two columns can be concatenated together using a double pipe (||). Alternately, the CONCAT() function can be used for this purpose.
*SQL commands can be entered directly into SQL*Plus on the command line.
*You can edit mistakes in SQL*Plus with the CHANGE command. If a mistake is made, the CHANGE(c/old/new) command is used.
*Alternatively, the EDIT (ed) command can be used to make changes in your favorite text editor.
*You can specify you favorite text editor by issuing the DEFINE_EDITOR command at the prompt.
*Use the acronym PEMDAS to remember the correct order for operator precedence.
*There are a host of commands available in SQL*Plus that are not part of Structured Query Language to be aware of. A few to pay close attention to include:
o GET for retrieving SQL scripts into SQL*Plus
o RUN for executing retrieved SQL scripts
o @ for getting and running a script in one operation
o DESCRIBE for listing the columns in a particular table, along with their datatypes
o SPOOL for telling SQL*Plus to write the contents of your session to a file
*The ORDER BY clause in a SELECT statement is a useful clause for incorporating a sort order into the output of a file.
*The sort orders that can be used are ascending and descending, abbreviated as ASC and DESC, respectively. The order is determined by the column identified in the ORDER BY clause. The default is ASC.
*The WHERE clause is used in SQL queries to limit the data returned by a query.
*The WHERE clauses contain comparison operations that determine whether a row will be returned by a query.
*The logical comparison operations include =, >, >=, <, <=, <>, !=, and ^=.
*In addition to the logical operations, a comparison operation, called LIKE, can be used to pattern matching. The % and _ characters are used to designate wildcards.
*The rage operation is called BETWEEN.
*The fuzzy logic operation is called SOUNDEX.
*The WHERE clause can contain one or more comparison operations linked together by using AND or OR and preceded by NOT.
*SQL functions are broken down into character functions, number functions, and date functions. Be sure you know how to use these functions for the OCP exam:
Text Functions
o lpad(x,y[,z]) and rpad(x,y[,z]) Return data in string or column x padded on the left or right side, respectively, to width y. The optional value z indicates the character(s) that lpad() or rpad() use to pad the column data. If no character z is specified, a space is used.
o lower(x), upper(x), and initcap(x) Return data in string or column x in lowercase or uppercase characters, respectively, or change the initial letter in the data from column x to a capital letter.
o length(x) Returns the number of characters in string or column x.
o substr(x,y[,z]) Returns a substring of string or column x, starting at the character in position number y to the end, which is optionally defined by the character appearing in the position z of the string.
o instr(x,y) Determines whether a substring y given can be found in string x.
o trim() A single-row function that behaves like a combination of ltrim() and rtrim(). Trim() accepts a string describing the data you would like to trim from a column value using the following syntax: trim([[keyword] ‘x’ from] column). Here keyword is replaced by leading, trailing, or both, or it’s omitted. Also, x is replaced with the character to be trimmed, or it’s omitted. If x is omitted, Oracle assumes it must trim whitespace. Finally, column is the name of the column in the table to be trimmed.
Arithmetic Functions
o abs(x) Obtains the absolute value for a number. For example, the absolute value of –1 is 1, whereas the absolute value of 6 is 6.
o round(x,y) Rounds x to the decimal precision of y. if y is negative, it rounds to the precision of y places to the left of the decimal point. This can also be used on DATE columns.
o ceil(x) Similar to executing round on an integer, except ceil always rounds up.
o floor(x) Similar to ceil, except floor always rounds down.
o mod(x,y) The modulus of x, defined in long division as the integer remainder when x is divided by y until no further whole number can be produced.
o sign(x) Displays an integer value corresponding to the sign of x: 1 if x is positive, -1 if x is negative.
o sqrt(x) The square root of x.
o trunc(x,y) Truncates x to the decimal precision of y. If y is negative, it truncates to y number of places to the left of the decimal point.
o vsize(x) The storage size in bytes for x.
List Functions
o greatest(x,y,…) Returns the highest value from the list of text, strings, numbers or dates.
o least(x,y,…) Returns the lowest value from the list of text strings, numbers, or dates.
o decode(column name, val1, sub1, val2, sub2,…) Works on the same principle as the if-then-else statement does in many common programming languages.
Date Functions
o add_months(x,y) Returns a date corresponding to date x plus y months.
o last_day(x) Returns the date of the last day of the month that contains date x.
o months_between(x,y) Returns a number of months between dates x and y. If date x is earlier than y, the result is negative; otherwise, the result is positive. If dates x and y contain the same day of different months, the result is an integer; otherwise, the result is a decimal.
o new_time(x,y,z) Returns the current date and time for date x in time zone y as it would be in time zone z.
o next_day(x) Identifies the name of the next day from given date, x.
*Several conversion functions are available for transforming data from text to numeric datatypes and back, numbers to dates and back, text to ROWID and back, and so on.
Conversion Functions
o to_char(x) Converts the value x to a character or converts a date to a character string using formatting conventions.
o to_number(x) Converts nonnumeric value x to a number.
o to_date(x[,y]) Converts the nondate value x to a date using the format specified by y.
o to_multi_byte(x) Converts the single-byte character string x to multibyte characters according to national language standards.
o to_single_byte(x) Converts the multibyte character string x to single-byte characters according to national language standards.
o chartorowid(x) Converts the string of characters x into an Oracle ROWID.
o rowidtochar(x) Converts the ROWID value into the string of characters x of VARCHAR2 datatype.
*SELECT statements that obtain data from more than one table and merge the data together are called joins.
*In order to join data from two tables, a common column must exist.
*A common column between two tables can create a foreign key, or link, from one table to another. This condition is especially true if the data in one of the tables is part of the primary key – the column that defines uniqueness for rows on a table.
*A foreign key can create a parent/child relationship between two tables.
*One type of join is the inner join, or equijoin. An equijoin operation is based on an equality operation linking the data in common columns of two tables.
*When joining tables using Oracle syntax, a join comparison on the common columns in the tables must be included in the WHERE clause of the query (i.e., WHERE a.empno=b.empno).
*When joining tables using ANSI/ISO syntax, the join tablename on join_comparison clause must be used (i.e., FROM a JOIN b ON a.empno=b.empno). the join comparison operation is thus kept separate from other filter comparisons that might otherwise appear in the WHERE clause.
*ANSI/ISO and Oracle syntax for joins is logically equivalent. There is no performance advantage for using one over the other. However, ANSI/ISO and Oracle syntax for joins cannot be used together in the same SQL query.
*Another type of join is the outer join. An outer join returns data in one table even when there is no data in the other table. The “other” table in the outer join operation is called the outer table.
*The common column that appears in the outer table of the join must have a special marker next to it in the comparison operation of the SELECT statement that creates the table.
*The Oracle-syntax outer join symbol is “(+)”, which is equivalent to the ANSI/ISO [left|right] outer join clause. Whether the outer join is a left join or right join depends on where the outer join symbol is placed (i.e., left join: all values from the table on the left of the statement are shown, even if the value in the right table is null; right join: all values from the table on the right side of the statement are shown, even if the value in the left table is null). Example: SELECT e.ename, e.deptno, d.dname FROM dept d, emp e WHERE d.deptno (+) = e.deptno is the same as SELECT e.ename, e.deptno, d.dname FROM emp e left outer join dept d on d.deptno=e.deptno.
*If the column name is the same in both tables, the common column in both tables used in Oracle-syntax join operations must be preceded either with a table alias that denotes the table in which the column appears or the entire table name.
*The data from a table can be joined to itself. This technique is useful in determining whether there are rows in the table that have slightly different values but are otherwise duplicate rows. This is called a self-join operation.
*Table aliases must be used in self-join SELECT statements. Example: SELECT e.empno, e.ename, e.job FROM emp e, emp e2 WHERE e.empno <> e2.empno AND e.name = e2.name;
*A Cartesian product is formed when you omit a join comparison from your Oracle-syntax join statement, or when you use the cross join keywords in ANSI/ISO syntax. Example: SELECT col1, col2 FROM example1 cross join example2;
*A natural join can be used to simplify join operations. Natural joins are possible in ANSI/ISO syntax when all common columns between joined tables have the same name. Use the natural keyword to specify to Oracle to execute a natural join. You do not need to specify a join comparison in order to execute a natural join. Example: SELECT ename, deptno, dname FROM emp natural join dept;
*Data output from table SELECT statements can be grouped together according to criteria set by the query.
*The group by clause assists you in grouping data together. Example: SELECT job, count(job) FROM emp GROUP BY job;
*Several grouping functions are available that allow you to perform operations on data in a column as though the data were logically one variable.
*The grouping functions are max(), min(), sum(), avg(), stddev(), variance(), and count().
o avg(x) Averages all x column values returned by the SELECT statement.
o count(x) Counts the number of non-NULL values returned by the SELECT statement for column x.
o max(x) Determines the maximum value in column x for all rows returned by the SELECT statement.
o min(x) Determines the minimum value in column x for all rows returned by the SELECT statement.
o stddev(x) Calculates the standard deviation for all values in column x in all rows returned by the SELECT statement.
o sum(x) Calculates the sum of all values in column x in all rows returned by the SELECT statement.
o variance(x) Calculates the variance for all values in column x in all rows returned by the SELECT statement.
*These grouping functions can be applied to the column values for a table as a whole or for subsets of column data for rows returned in group by statements.
*Data in a group by statement can be excluded or included based on a special set of where criteria defined specifically for the group in a having clause.
*The data used to determine the having clause can be specified at runtime by the query.
*NULL values are ignored by group functions. To force group functions not to ignore NULL values, use the nvl() function.
*The data used to determine the having clause can either be specified at runtime by the query or by a special embedded query, called a subquery which obtains unknown search criteria based on known search methods.
*Subqueries can be used in other parts of the SELECT statement to determine unknown search criteria, as well. Subqueries are generally included in this fashion in the WHERE clause.
*Subqueries can use columns in comparison operations that are local to the table specified in the subquery, or they can use columns that are specified in tables named in any parent query to the subquery. This use is based on the principles of variable scope. All variables or columns named in comparison operations in the outermost SELECT statement operation are local to that operation and global to all the nested subqueries.
*Various types of subqueries you might encounter when using Oracle include the following:
o Single-row subqueries The main query expects the subquery to return only one value. Example: SELECT empno FROM emp WHERE deptno = (SELECT deptno FROM emp WHERE ename = ‘John Smith’);
o Multiple-row subqueries The main query can handle situations where the subquery returns more than one value. Example: SELECT ename, job, sal FROM emp WHERE deptno in (SELECT deptno FROM dept WHERE dname in (‘Accounting’,’Sales’);
o Inline views A subquery in a FROM clause used for defining an intermediate result to query from. Example: SELECT ename, job, sal, rownum FROM (SELECT ename, job, sal FROM emp ORDER BY sal) where rownumb <=3; Notice that rownum is a virtual column identifying the row number in the table to deterime the top number of rows to return as output.
o Multiple-column subqueries A subquery that contains more than one column of return data in addition to however many rows are given in the output. Example: SELECT deptno, ename, job, sal FROM emp WHERE (deptno,sal) in (SELECT deptno, max(sal) FROM emp GROUP BY deptno);
*Be sure you understand how to set up and use a correlated subquery in Oracle to retrieve data. Oracle performs a correlated subquery when the subquery references a column from a table referred to in the parent statement. Example: SELECT e.ename, e.job e.sal FROM emp e WHERE exists (SELECT d. deptno FROM dept d WHERE d.loc = ‘New York’ AND d. deptno = e.deptno);
*Recall that most subqueries (even those returning multiple rows) generally only return one column of output per row. However, you can construct subqueries that return multiple colums.
*Subqueries that contain group by expressions will ignore rows if the group by column contains NULL values for those rows. Be sure you understand how to rewrite such queries, if necessary, to obtain those NULL values. Example: SELECT e.deptno, e.ename, e.job, e.sal FROM emp e WHERE e.sal = (SELECT max(e2.sal) from emp e2 where nvl(e.deptno,99) = nvl(e2.deptno,99));
*A subquery found in a FROM clause of the parent SQL query is called an inline view. Be sure you recall the syntax involved in using inline views, especially if you want to refer directly to columns in an inline view. Recall the use of inline views for top-N queries as well.
*Review the SQL*Plus environment characteristics that can be configured using the set command.
o ARRAYSIZE [ARRAY] {15|n} this command sets the number of rows that SQL*Plus fetches from the database at one time. Valid values are 1 to 5,000. A large value increases the efficiency of queries and subqueries that fetch many rows, but it requires more memory.
o AUTOTRACE [AUTO] {OFF|ON|TRACEONLY|EXPLAIN|STATISTICS} This command displays a report on the execution of successful SQL statements. The report can include execution statistics and the query execution path. OFF does not display a trace report. ON displays a trace report. TRACEONLY displays a trace report, but does not print query data, if any. Before using autotrace, you must run the plustrce.sql script fond in the sqlplus/admin directory under your Oracle software home directory. The EXPLAIN and STATISTICS options can be used for performance tuning as well by displaying SQL statement execution plans and statistics from the cost-based optimizer, respectively.
o COLSEP [COLSEP] {|text} This command sets the text to be printed between selected columns. If the colsep variable contains blanks or punctuation characters, you must enclose it with single quotes. The default value for text is a single space. In multilane rows, the column separator does not print between columns that begin on different lines.
o FEEDBACK [FEED] {6|n|OFF|ON} This displays the number of records returned by a query when a query selects at least n records. ON or OFF turns this display on or off. Turning feedback ON sets n to 1. Setting feedback to 0 is equivalent to turning it OFF.
o HEADING [HEA] {OFF|ON} This command controls the printing of column headings in reports. ON prints column headings in reports; OFF suppresses column headings. The set heading OFF command will not affect the column width displayed; it only suppresses the printing of the column header itself.
o LINESIZE [LIN] {80|n} This sets the total nmber of characters that SQL*Plus displays on one line before beginning a new line. You can define linesize as a value from 1 to a system-dependent maximum.
o LONG [LONG] {80|n} This sets the maximum width (in bytes) for displaying LONG, CLOB, and NCLOB values as well as for copying LONG values. The maximum valule of n is 2 GB.
o PAGESIZE [PAGES] {24|n} This sets the number of lines in each page. You can set pagesize to 0 to suppress all headings, page breaks, titles, the initial blank line, and other formatting information.
o PAUSE [PAU] {OFF|ON|text} This command enables you to control scrolling of your terminal when running reports. ON causes SQL*Plus to pause at the beginning of each page of report output. You must press ENTER after each pause. The text you enter specifies the text to be displayed each time SQL*Plus pauses. If you enter multiple words, you must enclose the text in single quotes. You can embed terminal-dependent escape sequences in the pause command. These sequences enable you to create inverse video messages or other effects on terminals that support such characteristics.
o SUFFIX [SUF] {SQL|text} This sets the default file extension that SQL*Plus uses in commands that refer to command files. The value for suffix does not control extensions for spool files.
o TERMOUT [TERM] {OFF|ON} This controls the display of output generated by commands executed from the command file. OFF suppresses the display so that you can spool output from a command file without seeing the output on the screen. ON displays the output. Setting termout OFF does not affect output from commands you enter interactively.
*In addition, be sure you understand completely how to use the following SQL*Plus commands for enhancing output readability:
o format COLUMN {col} FORMAT {fmt} HEADING {string}. Example: COLUMN empno FORMAT 999999 or COLUMN ename FORMAT a12
o underline UNDERLINE {-|c|ON|OFF} This command sets the character used to underline column headings in SQL*Plus reports to c. Note, c cannot be an alphanumeric character or a whitespace character. ON or OFF turns underlining on or off. ON changes the value of c back to the default (-). Example: set underline *
o wrap WRAP {OFF|ON} The wrap variable controls whether SQL*Plus truncates the display of a selected row if it is too long for the current line width. OFF truncates the selected row; ON emables the selected row to wrap to the next line. Example: set recsep wrapped
o break Sometimes when the information returned by your SQL query is ordered on a column, you may have multiple rows of data, each with the same value in the ordered column. The output can be changed so that only the first in a series of rows, where the ordered column values is the same, will show the column value. Example: break on deptno
o compute The computer command performs one of several grouping functions on the column you are breaking on, including sum, minimum, maximum, avg (average), std (standard deviation), variance, count, and number (number of rows in the column). Example: compute sum of sal on deptno
o ttitle and btitle If you want a top or bottom title to appear on each page of a report, you can place one through the use of the ttitle and btitle commands, respectively. The syntax is [btitle|ttitle] position ‘title_text’, where position can be LEFT, CENTER, RIGHT, or COLn to indicate a fixed number of characters from the left to start the title line.
*Variables can be set in a SELECT statement at runtime with the use of runtime variables. A runtime variable is designated with the ampersand character (&) preceding the variable name. Example: SELECT empno, deptno, sal FROM emp WHRE ename =’&name’;
*The special character that designates a runtime variable an be changed using the set define command.
*The define command can identify a runtime variable value to be picked up by the SELECT statement automatically. Example: define var_empno = 7844
*Once defined, the variable remains defined for the rest of the session or until it is undefined by the user or process with the undefined command. Example: undefined var_empno
*You can modify the message that prompts the user to input a variable value. This activity is performed with the accept command. Example: accept var_empno prompt ‘Enter EMPNO now =>’
*Every time you execute a SQL statement in SQL*Plus, that statement gets saved to a buffer used by SQL*Plus for repeat execution. This SQL statement can be saved using the save command. Example: save employee.sql
*The basic types of data relationships in Oracle include primary keys and functional dependency within a table as well as foreign key constraints from one table to another.
*A relational database is composed of objects that store data, objects that manage access to data, and objects that improve performance when accessing data.
*A table can be created using a create table statement. Example: CREATE TABLE emp (empno number primary key, name varchar2(50), ssn number(9));
*Tables can be added using data from another table. Example: CREATE TABLE emp AS SELECT * FROM scott.emp WHERE deptno = 10;
*A temporary table is created using the create global temporary table command. Data in a temporary table is private to the session, meaning that each session can see and modify only its own data in the temporary table.
*Oracle database object names must begin with a letter and can usually be between 1 and 30 characters long, except for databases (which have a maximum of eight characters) and database links (with a maximum of 128 characters). Names are not case-sensitive.
*A user cannot own or refer to two objects with the same name, so if both you and SCOTT own a table called EMPLOYEE, you must prefix references to EMPLOYEE with the schema owner.
*Don’t name a table DUAL, because Oracle already has table called DUAL that is accessible by everyone.
*Don’t use table names beginning with SYS.
*You can only use the following three special characters in table and column names: #, $, and _.
*Don’t use special characters from European or Asian character sets in a database name, global database name, or database link name.
*An object name cannot be an Oracle reserved word, such as SELECT or FROM; a datatype, such as NUMBER; or a built-in function, such as DECODE(). Oracle may not complain when you create the object, but it may give you an unpleasant surprise when you refer to the object in your SQL statement.
*A table can be dropped using the drop table statement. Example: DROP TABLE emp;
*A table can be renamed using the alter table rename statement. Example: RENAME emp to employee or ALTER TABLE emp RENAME TO employee;
*A table can be truncated using the truncate table statement. Truncating a table removes all row data from a table quickly, while leaving the definition of the table intact, including the definition of constraints and any associated database objects such as indexes, constraints, and triggers on the table. When you truncate the table, Oracle resets the high-water mark to zero. Once this operation has been completed, the data cannot be recovered unless you have a backed-up copy of the data.
*Comments can be added to a table or column using the comment command. Example: COMMENT ON TABLE emp IS ‘This is a test table’ or COMMENT ON column emp.empno IS ‘unique employee number’;
*A table can be created with five different types of integrity constraints: PRIMARY KEY, FOREIGN KEY, UNIQUE, not NULL, and CHECK.
*Referential integrity often creates a parent/child relationship between two tables – the parent being the referenced table and the child being the referring table. Often a naming convention that requires child objects to adopt and extend the name of the parent table is useful in identifying these relationships.
*The datatypes available for creating columns in tables are CHAR, VARCHAR2, NUMBER, DATE, RAW, LONG, LONG RAW, ROWID, BLOB, CLOB, NCLOB, and BFILE.
o CHAR(n) Contains fixed text strings of n bytes, where n can be up to 2,000 bytes in Oracle.
o VARCHAR2(n) Contains variable-length text strings of length n bytes, where n can be of up to 4,000 bytes.
o NUMBER(n[,m]) Contains numeric data of up to n digits in length, where n can be up to 38 digits in Oracle. A NUMBER can also have an optimal m number of digits to the right of the decimal point. This collection of digits is called a mantissa. The mantissa can have up to 38 digits as well. If no value is specified for n, Oracle defaults to 38.
o DATE Contains date information. DATE columns are seven bytes in length.
o RAW Contains binary data of up to 2, 000 bytes in Oracle. This is a variable length datatype like VARCHAR2 in Oracle.
o LONG Contains text data of up to 2GB.
o LONG RAW Contains binary data of up to 2GB.
o ROWID Contains the address for rows in your table. These could be physical ROWIDs or logical ROWIDs.
o BLOB Stores large unstructured binary object data of up to 4GB.
o CLOB Stores large database character set data of up to 4GB.
o NCLOB Stores large single-byte or multibyte character-based Unicode character set data of up to 4 GB.
o BFILE Stores pointers to large unstructured operating system files outside the Oracle database.
*A table column can be added or modified with the alter table statement. Example: ALTER TABLE emp add (ename varchar2(25)) or ALTER TABLE emp modify (ename varchar2(30))
*Columns can be added with little difficulty if they are nullable, using the alter table add (column_name datatype) statement. If a not NULL constraint is desired, add the column, populate the column with data, and then add the not NULL constraint separately.
*Column datatype size can be increased with no difficulty using the alter table modify (column_name datatype) statement. Column size can be decreased, or the datatype can be changed, only if the column contains NULL for all rows.
*Constraints can be added to a column only if the column already contains values that will not violate the added constraint.
*PRIMARY KEY constraints can be added with the table constraint definition by using the alter table add (constraint constraint_name primary key (column_name)) statement or with a column constraint definition using the alter table modify (column_name constraint constraint_name primary key) statement. Example: CREATE TABLE emp (empno number primary key, name varchar2(50)) or CREATE TABLE emp (empno number, name varchar2(50) CONSTRAINT pk_emp_01 primary key (empno)) or ALTER TABLE add CONSTRAINT pk_emp_01 primary key (empno) or ALTER TABLE modify (empno CONSTRAINT pk_emp_01 primary key)
*UNIQUE constraints can be added with the table constraint definition by using the alter table add (constraint constraint_name unique (column_name)) statement or with a column constraint definition by using the alter table modify (column_name constraint constraint name unique) statement. Example: CREATE TABLE emp (empno number unique, name varchar2(50)) or CREATE TABLE emp (empno number, name varchar2(50) CONSTRAINT uk_emp_01 unique (empno)) or ALTER TABLE add CONSTRAINT uk_emp_01 unique (empno) or ALTER TABLE modify (empno CONSTRAINT uk_emp_01 unique);
*FOREIGN KEY constraints can be added with a table constraint definition by using the alter table add (constraint constraint_name foreign key (column_name) references OWNER.TABLE (column_name) [on delete cascade]) statement or with a column constraint definition by using the alter table modify (column_name constraint constraint_name references OWNER.TABLE (column_name) [on delete cascade]) statement. Example: CREATE TABLE emp (empno number, name varchar2(50) references scott.employee (ename) on delete set null) or ALTER TABLE add CONSTRAINT fk_emp_01 foreign key (name) references scott.employee (ename) or ALTER TABLE modify (empno CONSTRAINT fk_emp_01 foreign key (name) references scott.employee (ename);
*CHECK constraints can be added with a table constraint definition by using the alter table add (constraint constraint_name check (check_condition)) statement or with a column constraint definition by using the alter table modify (column_name constraint constraint_name check (check_condition)) statement. Example: CREATE TABLE emp (empno number primary key, name varchar2(50), salary (8,2) check (salary <= 100000) or ALTER TABLE add CONSTRAINT ck_emp_01 check (salary <= 100000) or ALTER TABLE modify (salary CONSTRAINT ck_emp_01 check (salary <= 100000);
*The check condition cannot contain subqueries, references to certain keywords (such as user, sysdate, and rowed) or any pseudocolumns.
*Not NULL constraints can be added with a column constraint definition by using the alter table modify (column_name NOT NULL) statement. Example: CREATE TABLE emp (empno number primary key, name varchar2(50) NOT NULL) or ALTER TABLE modify (name NOT NULL);
*A named PRIMARY KEY, UNIQUE, CHECK, or FOREIGN KEY constraint can be dropped with the alter table drop constraint constraint_name statement. A NOT NULL constraint is dropped using the alter table modify (column_name NULL) statement. Example: ALTER TABLE DROP CONSTRAINT pk_emp_01 or ALTER TABLE MODIFY (name NULL);
*If a constraint that created an index automatically (such as a primary key or UNIQUE constraint) is dropped, the corresponding index is also dropped.
*A constraint can be disabled using the alter table disable constraint statement. Example: ALTER TABLE employee DISABLE primary key or ALTER TABLE employee DISABLE CONSTRAINT uk_employee_01;
*You may experience a problem if you attempt to disable a primary key when existing foreign keys depend on that primary key.
*A constraint can be re-enabled using the alter table enable statement. Example: ALTER TABLE department ENABLE primary key or ALTER TABLE employee ENABLE uk_employee_01;
*If you disable a constraint and then load data into the table column that violates the integrity constraint while the constraint is disabled, your attemp to enable the constraint later with the alter table enable constraint statement will fail.
*You will need to use a special table called EXCEPTIONS (created by running the utlexcpt.sql script from rdbms/admin under the Oracle software home directory) to identify and correct offending records.
*When there are constraints on other tables that reference the tables to be dropped, you can use the cascade constraints clause in your drop table statement. The constraints in other tables that refer to the table being dropped are also dropped with cascade constraints. Example: DROP TABLE department CASCADE CONSTRAINTS;
*If the table is dropped, all constraints, triggers, and indexes created for the table are also dropped.
*Removing all data from a table is best accomplished with the truncate command rather than the delete from table_name statement because truncate resets the table’s high-water mark and deallocates all the table’s storage quickly, thus improving performance on SELECT count() statements issued after the truncation.
*An object name can be changed with the rename statement or with the use of synonyms.
*Indexes are created automatically in conjunction with primary key and UNIQUE constraints. The indexes are named after the constraint name given to the constraint in the definition of the table.
*Tables are created without any data in them, except for tables created with the create table as select statement. These tables are crated and prepopulated with data from another table.
*New rows are put into a table with the insert statement. The user issuing the insert statement can insert one row at a time with one statement or can perform a mas insert operation with insert into table_name (select…..). Example: INSERT INTO emp (empno, name) values (12345,’John Smith’) or INSERT INTO emp (SELECT * FROM scott.emp);
*Existing rows in a database table can be modified using the update statement. The update statement contains a where clause similer in function to the where clause of select statements. Example: UPDATE emp set name = null or UPDATE emp set name = ‘Jane Smith’ where empno = 12345;
*Existing rows in a table can be deleted using the delete statement. The delete statement also contains a where clause similar in function to the where clause in update and select statements. Example: DELETE FROM emp or DELETE FROM emp WHERE name = ‘Jane Smith’;
*Transaction processing controls the change of data in an Oracle database.
*Transaction controls include commands that identify the beginning, breakpoint, and end of a transaction as well as the locking mechanism that prevent more than one user at a time from making changes in the database.
o set transaction Initiates the beginning of a transaction and sets key features. This command is optional. A transaction will be started automatically when you start SQL*Plus, commit the previous transaction, or roll back to the previous transaction. the set transaction isolation level serializable command specifies serializable transaction isolation mode as defined in SQL92.
o commit Ends the current transaction by saving database changes and starts a new transaction.
o rollback Ends the current transaction by discarding database changes and starts a new transaction.
o savepoint Defines breakpoints for the transaction to enable partial rollbacks.
*A table-level lock enables only the user holding the lock to change any piece of row data in the table, during which time no other users can make changes anywhere on the table.
*A row-level lock gives the user the excusive ability to change data in one or more rows of the table.
*An update statement requires a special rwo-level lock called a row-exclusive lock, which means that for the period of time the update statement is executing, no other user in the database ccan view or change the data in the row. The same goes for delete or insert operations. Another update statement – the select for update statement – acquires a more lenient lock called the share row lock. This lock means that for the period of time the update statement is changing the data in the rows of the table, no other user may change that row, but users may look at the data in the row as it changes.
*A vew is a virtual table defined by a select statement.
*Views can distill data from tables that may be inappropriate for some users, and they can hide the complexity of data joined from several tables. You can also mask the complexity that arises when you perform many single-row or group operations on the data returned by the view’s query.
*The two types of views are simple and complex.
*Simple views are those that only have only one underlying table. Example: CREATE OR REPLACE VIEW emp_view AS (SELECT * FROM emp WHERE job = ‘ANALYST’);
*Complex views are those with two or more underlying tables that have been joined together. Example: CREATE OR REPLACE VIEW emp_dept_view AS (SELECT empno, ename, job, dname, loc FROM emp e, dept d WHERE e.deptno = d.deptno and job in (‘ANALYST’,’CLERK’,’MANAGER’));
*Data may be inserted into simple views, except in the following cases:
o If the with check option clause is used, the user may not insert, delete, or update data on the table underlying the simple view if the view itself is not able to select that data for the user.
o The user may not insert, delete, or update data on the table underlying the simple view if the SELECT statement creating the view contains group by, order by, or a single-row operation.
o No data may be inserted in simple views that contain references to any virtual columns, such as ROWID, CURRVAL, NEXTVAL, and ROWNUM.
o Not data may be inserted into simple views that are created with the read only option.
*Data may be inserted into complex views when all the following conditions are true:
o The statement affects only one of the tables in the join.
o For update statements, all columns changed are extracted from a key-preserved table. In addition, if the view is created with the with check option clause, join columns and columns taken from the tables that are referenced more than once in the view are not part of the update.
o Fore delete statements, the join has only one key preserved table. This table may be present more than once in the join, unless the view has been created with the check option clause.
o For insert statements, all columns where values are inserted must come from a key-preserved table, and the view must not have been created with the with check option.
*The with check option clause, upon creating a view, enables this simple view to limit the data that can be inserted or otherwise changed on the underlying table by requiring that the data change can be selectable by the view.
*A join view is simply another name for a complex view.
*A key-preserved table is a table in a complex view whose primary key column is present in the view and whose values are all unique and not NULL in the view.
*Views containing outer joins generally won’t contain key preserved tables unless the outer join generates no NULL values.
*Modifying the data selected by a view requires re-creating the view with the create or replace view statement or dropping the view first and issuing the create view statement.
*An existing view can be recompiled by executing the alter view statement if for some reason it becomes invalid due to object dependency. Example: ALTER VIEW emp_dept_view COMPILE;
*A view is dropped with a drop view statement. Example: DROP VIEW profits_view;
*Oracle doesn’t remove views from the database if a base table is destroyed. Oracle simply marks the view as invalid.
*A sequence generates integers based on rules that are defined by sequence creation.
*Options that can be defined for sequences include the first number generated, how the sequence increments, the maximum value, the minimum value, whether the sequence can recycle numbers, and whether numbers will be cached for improved performance. Example: CREATE SEQUENCE countdown_20 START WITH 20 INCREMENT BY –1 MAXVALUE 20 MINVALUE 0 CYCLE ORDER CACHE2;
o start with n Enables the creator of the sequence to specify the first value generated by the sequence. If no start with value is specified, Oracle defaults to a start value of 1.
o increment by n Defines the number by which to increment the sequence every time the NEXTVAL virtual column is referenced. The default for this clause is 1 if it is not explicitly specified.
o minvalue n Defines the minimum value that can be produced by the sequence. If no minimum value is specified, Oracle will assume the default, nominvalue.
o maxvalue n Defines the maximum value that can be produced by the sequence. If no maximum value is desired or specified, Oracle will assume the default, nomaxvalue.
o cycle Enables the sequence to recycle values produced when maxvalue or minvalue is reached. If cycling is not desired or not explicitly specified, Oracle will assume the default, nocycle. You cannot specify cycle in conjunction with nomaxvalue or nominvalue. if you want your sequence to cycle, you must specify maxvalue for incrementing sequences or minvalue for decrementing or countdown sequences.
o cache n Enables the sequence to cache a specified number of values to improve performance. If caching is not desired or not explicitly specified, Oracle will assume the default, which is to cache 20 values.
o order Enables the sequence to assign values in the order in which requests are received by the sequence. If order is not desired or not explicitly specified, Oracle will assume the default, noorder.
*Sequences are used by selecting from the CURRVAL and NEXTVAL virtual columns.
*The CURRVAL column contains the current value of the sequence.
*Selecting from NEXTVAL increments the sequence and changes the value of CURRVAL to whatever is produced by NEXTVAL.
*The rules that a sequence uses to generate values can be modified using the alter sequence statement. The effect is immediate. Example: ALTER SEQUENCE countdown_20 INCREMENT BY –4;
*A sequence can be deleted with the drop sequence statement. Example: DROP SEQUENCE countdown_20;
*References to sequences cannot be used in subqueries of SELECT statements (including those with having), views, and SELECT statements using set operations (such as union and minus), or any SELECT statement that requires a sort to be performed.
*Some indexes in a database are created automatically, such as those supporting the primary key and the unique constraints on a table.
*Other indexes are created manually to support database performance improvements.
o unique indexes CREATE UNIQUE INDEX emp_empno_01 ON emp (empno);
o nonunique indexes CREATE INDEX emp_sal_01 ON emp (sal);
o composite indexes CREATE UNIQUE INDEX employee_empno_ename_indx_01 ON emp (empno, ename);
o reverse key indexes CREATE INDEX emp_ename_reverse_indx ON emp (ename) REVERSE;
o bitmap indexes CREATE BITMAP INDEX emp_deptno_indx_01 ON emp (deptno);
o function-based indexes CREATE INDEX idx_emp_01 ON emp (sal*1.08);
*Indexes created manually are often on non-unique columns.
*B-tree indexes work best on columns that have high cardinality – that is, columns that contain a large number of distinct values and few duplicates.
*B-tree indexes improve performance by storing data in a binary search tree and then searching for values in a tree using a divide-and-conquer methodology, as outlined in this chapter.
*Bitmap indexes improve performance on columns with low cardinality – that is, columns that contain few distinct values and many duplicates.
*Columns stored in an index can be changed only by dropping and recreating the index.
*Indexes can be deleted by issuing the drop index statement. Example: DROP INDEX employee_last_first_indx_01;
*A function-based index is a new type of index in Oracle that is designed to improve query performance by making it possible to define an index that works when your WHERE clause contains operation on columns.
*To create a function-based index in your own schema on your own table you must have the CREATE INDEX and QUERY REWRITE system privileges.
*To create a function-based index in another schema or on another schema’s table, you musht have the CREATE ANY INDEX and GLOBAL QUERY REWRITE privileges. The table owner must also have the EXECUTE object privilege on the functions used in the function-based index.
*To enable the use of function-based indexes, you must issue two alter session statements: ALTER SESSION SET query_rewrite_enabled = true and ALTER SESSION SET query_rewrite_integrity = trusted;
*Synonyms are alternative names that can be crated as database objects in Oracle to refer to a table or view.
*Two types of synonyms exist in Oracle: private synonyms and public synonyms.
*You can use a private synonym within your own schema to refer to a table or view by an alternative name.
*Public synonyms are publicly available to all users of Oracle; however you need special privileges to create public synonyms.
*Creating a synonym is accomplished with the create synonym or create public synonym command. Example: CREATE SYNONYM all_my_emps FOR emp or CREATE PUBLIC SYNONYM emp FOR scott.emp;
*Synonyms do not give you access to data in a table that you do not already have access to. Only privileges can do that. Synonyms simply enable you to refer to a table without prefixing the schema name to the table reference.
*The Oracle database security model consists of two parts: limiting user access with password authentication and controlling object use with privileges.
*Available privileges in Oracle include system privileges, for maintaining database objects, and object privileges, for accessing and manipulating data in database objects.
*Users can be created using the create user identified by statement. Example: CREATE USER turner IDENTIFIED BY ike;
*Users that are created can be authenticated by a host. The username identifying the user in Oracle must match that used on the host system, prefixed by OPS$. Example: CREATE USER OPS$harvey IDENTIFIED BY externally;
*Once a user is created, it does not have any privileges. The DBA can then grant privileges to the user.
*Usernames can be up to 30 characters in length and can contain alphanumeric characters as well as the $, #, and _ characters.
*Changing a password can be performed by a user with the alter user identified by statement. Example: ALTER USER SCOTT IDENTIFIED BY 123456;
*Granting system and object privileges is accomplished with the grant command. Example: GRANT create session TO turner or GRANT select, update, insert ON emp TO turner (NOTE, this object privilege syntax does not work when granting privileges to a single column – correct syntax is GRANT privilege (column_name) ON table TO user;).
System Privileges
o Database Access These privileges control who accesses the database, when he or she can access it, and what he or she can do regarding management of his or her restricted session. Privileges include create session, alter session, and restricted session.
o Users These privileges are used to manage users in the Oracle database. Typically, these privileges are reserved for DBAs or security administrators. Privileges include create user, become user, alter user, and drop user.
o Tables These privileges govern which users can create and maintain tables. The privileges include create table, create any table, alter any table, backup any table, drop any table, lock any table, comment any table, select any table, insert any table, update any table, and delete any table. The create table or create any table privilege also enables you to deop the table. The create table privileges also bestows the ability to create indexes on the table and to run the analyze command on the table. To be able to truncate a table, you must have the drop any table privilege granted to you.
o Indexes The privileges include create any index, alter any index, and drop any index. You should note that no create index system privilege exists. the create table privilege also enables you to alter and drop indexes that you won and that are associated with the table.
o Synonyms These privileges include create synonym, create any synonym, drop any synonym, create public synonym, and drop public synonym. The create synonym privilege also enables you to alter and drop synonyms that you own.
o Views Privileges include create view, create any view, and drop any view. The create view privilege also enables you to alter and drop views that you own.
o Sequences Privileges include create sequence, create any sequence, alter any sequence, drop any sequence, and select any sequence. The create sequence privilege also enables you to drop sequences that you own.
o Roles Roles are objects that can be used for simplified privilege management. You create a role, grant privileges to it, and then grant the role to users. Privileges include create role, drop any role, grant any role, and alter any role.
o Transactions These privileges are for resolving in-doubt distributed transactions being processed on the Oracle database. Privileges include force transaction and force any transaction.
o PL/SQL These privileges enable you to create, run, and manage those different types of blocks. Privileges include create procedure, create any procedure, alter any procedure, drop any procedure, and execute any procedure. The create procedure privilege also enables you to alter and drop PL/SQL blocks that you own.
o Triggers A trigger is a PL/SQL block in Oracle that executes when a specified DML activity occurs on the table to which the trigger is associated. Privileges include create trigger, create any trigger, alter any trigger, and drop any trigger. The create trigger privilege also enables you to alter and drop triggers that you own.
Object Privileges
o select Permits the grantee of this object privilege to access the date in a table, sequence, view, or snapshot.
o insert Permits the grantee of this object privilege to insert data into a table or, in some cases, a view. You can also restrict this privilege to specified columns of a table.
o update Permits the granted to update data in a table or view. You can also restrict this privilege to specified columns of a table.
o delete Permits the granted to delete data in a table or view. You can also restrict this privilege to specified columns of a table.
o alter Permits the grantee of this object privilege to alter the definition of a table or sequence only; the alter privileges on all other database objects are considered system privileges.
o index Permits the grantee of this object privilege to create an index on a table already defined.
o references Permits the grantee of this object privilege to create or alter a table in order to crate a foreign key constraint against data in the reference table.
o execute Permits the grantee of this object privilege to run a stored procedure or function.
*In order to grant an object privilege, the grantor must either have been granted the privilege with the with grant option privilege or must own the object. Example: GRANT insert ON emp TO turner WITH GRANT OPTION;
*A system privilege or a role can be granted with the ADMIN OPTION. A grantee with this option can grant or revoke the system privilege or role to or from any user or other role in the database. However, a user cannot revoke a role from themselves.
*Taking away system and object privileges is accomplished with the revoke command. Example: REVOKE create session FROM turner or REVOKE select, update, insert ON emp FROM turner (NOTE, this object privilege syntax does not work when granting privileges to a single column – correct syntax is REVOKE privilege (column_name) ON table FROM user;).
*When the CASCADE CONSTRAINTS option is specified, any foreign key constraints currently defined that use the revoked REFERENCES privilege are dropped.
*No cascading effects of revoking system privileges from users occur. If you want to take away a system privilege from a user, you have to explicitly revoke that privilege directly from the user as well as drop whatever objects that user has created while having the privilege.
*When an object privilege is revoked from a grantor of that privilege, all grantees receiving the privilege from the grantor also lose the privilege. The changes made by those users will remain.
*If a privileges has been granted on two individual columns, the privilege cannot be revoked on only one column – the privilege must be revoked entirely and then regranted on the individual column.
*If the user has been given the references privilege and has used it to create a foreign key constraint to another table, you must use the cascade constraints clause to revoke the references privilege (otherwise it will fail), as follows: REVOKE REFERENCES ON emp FROM spanky CASCADE CONSTRAINTS;
*The insert, update, and references privileges can be granted on columns within the database object. However, if a user has the insert privilege on several columns in the table but not all columns, the privilege administrator must ensure that no columns in the table that do not have the insert privilege granted are not NULL columns.
*If a user has the ability to execute a stored procedure owned by another user, and the procedure accesses some tables, the object privileges required to access those tables must be granted to the owner of the procedure, not the user whom execute privileges were granted. What’s more, the privileges must be granted directly to the user, not through a role.
*Depending upon what is granted or revoked, a grant or revoke takes effect at different times. All grants/revokes of privileges (system and schema object) to users, roles, or PUBLIC are immediately observed. All grants/revokes of roles to users, other roles, or public are observed only when a current user session issues a SET ROLE statement to reenable the role after the grant/revoke, or when a new user session is created after the grant/revoke.
*A role acts in two capacities in the database. First, the role can act as a focal point for grouping the privileges to execute certain tasks. Second, the role can act as a “virtual user” of a database, to which all the objects privileges required to execute a certain job function can be granted.
* A role can be created using the create role statement. You must have the create role system privilege to create a role. Example: CREATE ROLE rpt_writer.
* A role can be modified using the alter role statement. It can also be altered to require a password by using the alter role identified by statement. Example: ALTER ROLE data_changer IDENTIFIED BY hightly#secure;
* You grant and revoke object privileges to a role in the same manner you would a user. Example: GRANT select ON emp TO rpt_writer;
* Once a role is created and privileges are granted to it, the role can then be granted to users. Example: GRANT rpt_writer TO turner;
* If a role already granted to a user is later granted another privilege, that additional privilege is available to the user immediately. The same statement can be made for privileges revoked from roles already granted to users.
* You can use the following keywords in the alter user default role command to define default roles for users: all, all except rolename, and none. Note that users usually cannot issue alter user default role themselves to change their default roles – only a privileged user such as the DBA can do it for them. Example: ALTER USER scott DEFAULT ROLE none;
* You can enable a role by using the set role command. Example: set role data_changer identified by highly#secure;
* Some special roles are available to the users of a database.
* CONNECT Enables the user extensive development ability within his or her own user schema, including the ability to perform create table, create cluster, create session, create view, create sequence, and more. The privileges associated with this roll are platform specific; therefore, the role can contain a different number of privileges, but typically the role never enables the creation of stored procedures.
* RESOURCE Enables the user moderate development ability within his or her own schema, such as the ability to execute create table, create cluster, create trigger, and create procedure. The privileges associated with this role are platform specific; therefore, the role can contain a different number of privileges.
* DBA Enables the user to administer and use all system privileges.
USER_TAB_COMMENTS Stores comment information on tables.
USER_COL_COMMENTS Stores comment information for columns.
USER_CONSTRAINTS CONTRAINT_TYPE column will list the first character of the first word that best describes each type of constraint.
ALL_CONSTRAINTS CONTRAINT_TYPE column will list the first character of the first word that best describes each type of constraint.
USER_OBJECTS Can be used to verify the validity status of all user database objects.
ALL_OBJECTS Can be used to verify the validity status of all database objects.
USER_UPDATABLE_COLUMNS COLUMN_NAME and UPDATABLE will tell you whether the columns in a complex view can be modified.
USER_INDEXES Contains the name of the index and it uniqueness.
USER_IND_COLUMNS Contains the index name, the table name, and the column name.
USER_SYS_PRIVS Shows all privileges associated with this user.
SESSION_PRIVS Shows all privileges available in this session.
USER_ROLE_PRIVS Identifies the roles granted to you.
ROLE_ROLE_PRIVS Identifies the roles granted to other roles in the database.
ROLE_TAB_PRIVS Identifies object privileges granted to roles.
ROLE_SYS_PRIVS Identifies system privileges granted to roles.
SESSION_ROLES Identifies roles available to the current session.