Refer to Appendix i for data types SQL Notes from Oracle sql by example--To show the default tablespace

names SELECT tablespace_name FROM dba_tablespaces ORDER BY tablespace_name; -To create a user named Student and password learn CREATE USER student IDENTIFIED by learn DEFAULT TABLESPACE users TEMPORARY TABLESPACE temp; -to give the STUDENT account the ability to use the database. Execute the following statement while connected as the SYSTEM user: GRANT CONNECT, RESOURCE TO student; GRANT SELECT_CATALOG_ROLE TO student; GRANT CREATE VIEW TO student; 1-----------------------------------------------------------------------Nulls cannot be evaluated or compared because they are unknown Sometimes the unique key is a system generated sequence number; this type of key is called a synthetic, or surrogate, key. If the primary key contains multiple columns, it is referred to as a composite primary key, or concatenated primary key. Eliminating redundancy is one of the key concepts in relational databases, and this process, referred to as normalization. To grant SELECT and INSERT access to the AUTHOR table, you issue a GRANT command. It allows the user Scott to retrieve and insert data in the AUTHOR table. GRANT SELECT, INSERT ON author TO scott The referential integrity rule allows a parent without child(ren) but does not allow a child without a parent because this would be considered an orphan row NORMAL FORMSFor a table to be in first normal form, all repeating groups must be removed and placed in a new table. Second normal form states that all nonkey columns must depend on the entire primary key. It applies only to tables that have composite primary keys

2) can have a maximum of three digits before the decimal point and two digits after the decimal point. The BLOB data type stores the content inside the Oracle database. execute the CLEAR COLUMNS command in SQL*Plus. images. If you write a SQL query using DISTINCT or UNIQUE. SQL considers a NULL value equal to another NULL value. or music.The third normal form goes a step further than the second normal form: It states that every nonkey column must be a fact about the primary key Data warehouse applications are database applications that benefit users who need to analyze large data sets from various angles and use this data for reporting and decision making purposes. the case of the data must match exactly The AND operator always takes precedence over the OR operator.000 characters. When you compare a text literal to a database column. Datatypes NUMBER(5. you need to consider the CLOB data type The data types BLOB and BFILE are binary data types that deal with access to multimedia content such as movies. You can re-execute a statement by just pressing the / key or typing the SQL*Plus RUN command. A CHAR column can store up to 2.000 characters If you want to store data containing more than 4.000 characters.ORA SQL*Plus stores the last SQL command you typed in what is referred to as the SQL*Plus buffer. If there are multiple operators of the same precedence. The connect identifier matches either an entry in a file called TNSNAMES. whereas the BFILE data type stores only a reference to the file location directory and the file name. meaning that any AND conditions are evaluated first. The first digit (5) is called the precision. the second digit (2) is referred to as the scale VARCHAR2 maximum size is 4. The column headings are truncated to the specified length COL description FORMAT A30 To clear all the column formatting. the left operator is executed before the right TRUE FALSE UNKNOWN AND Truth Table TRUE FALSE TRUE FALSE FALSE FALSE UNKNOWN FALSE UNKNOWN UNKNOWN FALSE UNKNOWN OR Truth Table .

n [. char2]) RPAD(char1. Unlike the LOWER. the string is padded with spaces by default. The optional keyword AS can precede the alias name. or you can be explicit by adding the abbreviation ASC after the column. The ORDER BY clause often contains columns listed in the SELECT clause. If descending order is desired. char2]) The first input parameter accepts either a text literal or a column of data type VARCHAR2. char2]) TRIM([LEADING|TRAILING|BOTH] char1 FROM char2) SUBSTR(char1. An alias may contain one or more words or be spelled in exact case when enclosed in double quotation marks. or INITCAP functions. the lowercase letters are listed after the uppercase letters. starting_position [. when ORDER BY is used. n [. LTRIM(char1 [. The row column value of NULL is the last row in the sort order You can change the ordering of the nulls with the NULLS FIRST or NULLS LAST option in the ORDER BY clause different forms of a column alias are used to take the place of the column name in the result set. char2]) RTRIM(char1 [.TRUE FALSE UNKNOWN TRUE TRUE TRUE TRUE FALSE TRUE FALSE UNKNOWN UNKNOWN TRUE UNKNOWN UNKNOWN Order by clause By default. When ordering the result set. substring_length]) . the result set is sorted in ascending order. the column(s) the keyword pertains to must also be listed in the ORDER BY clause. LPAD and RPAD functions take more than one parameter as their input LPAD(char1. UPPER. Instead of listing the name of the column to be ordered. The third optional argument indicates the character(s) the string should be padded with. but it is also possible to use ORDER BY on columns that are not selected. If this parameter is not specified. you use the abbreviation DESC after the column in the ORDER BY clause. or CLOB. The second argument specifies the total length to which the string should be padded. One exception is columns qualified using the DISTINCT keyword: If the SELECT list contains DISTINCT. CHAR. you can list the sequence number of the column in the SELECT list.

CASE {expr WHEN expr THEN return_expr [WHEN expr THEN return_expr]. No greater than. 'hand'. and the computation of REMAINDER is (23-(8*ROUND(23/8))) COALESCE(input_expression. The function returns a substitution value in case the input value is NAN (“not a number”). null_substitution_expr) The LNNVL function can be used only in the WHERE clause of a SELECT statement.. CASE {WHEN condition THEN return_expr [WHEN condition THEN return_expr]. otherwise. equal_expression2) The NANVL function is used only for the BINARY_FLOAT and BINARY_DOUBLE floating-point data types. if the values are equal. [.else_default]) for the purpose of the DECODE function.-. char2 [.. or IS NULL comparisons are allowed. The function compares two expressions. 'foot') The SOUNDEX function allows you to compare differently spelled words that phonetically sound alike CONTAINS. equals_search. then_result [. substitution_expression_1. the function returns the first expression--NULLIF(expression1. CATSEARCH.INSTR(char1. not_null_substitution_expr. combining the DECODE function with the SIGN function overcomes this shortcoming. the function returns a null. however.. and MATCHES MOD function is (23-(8*FLOOR(23/8))). substitution_value) DECODE (if_expr.} . which replaces an entire string.. occurrence]]) Unlike REPLACE. } [ELSE else_expr] END The simple CASE expression tests for equality only. less than. substitution_expression_n]) NVL2(input_expr. the TRANSLATE function provides a one-for-one character substitution REPLACE('My hand is asleep'.NANVL(input_value. It returns either true or false-LNNVL(condition) The NULLIF function is unique in that it generates null values.starting_position [. null values are treated as equals The DECODE function does not allow greater than or less than comparisons.

with the DATE keyword prefix. as long as the date Is same Instead of using Oracle’s date literals. SELECT course_no. SELECT student_id. if you choose the ‘Day’ format mask. rd. 'Day DD-Mon-YYYY HH:MI am') FROM section . Oracle displays it in the default format determined by the database NLS_DATE_FORMAT parameter. section_id. hour. TO_CHAR(start_date_time. use the ANSI TIMESTAMP keyword. such as the TRUNC function on the database column START_DATE_TIME. if the two-digit year is between 50 and 99. TO_CHAR(enroll_date. it’s the current century. if the two-digit year is between 00 and 49. The literal must be in the ANSI TIMESTAMP format. unless it is a function-based index. day. then it’s the previous century. which is defined as YYYY-MM-DD HH24:MI:SS. and second When you query a DATE data type column. TO_CHAR(enroll_date. nd. you can specify a date in the ANSI format . month.[ELSE else_expr] END Date and Conversion Functions Oracle’s DATE data type consists of a date and time that are stored in an internal format that keeps track of the century. to include the st. The following query returns no rows. 'DD-MON-YYYY HH24:MI:SS') FROM enrollment WHERE enroll_date >= TIMESTAMP '2007-02-07 00:00:00' AND enroll_date < TIMESTAMP '2007-02-08 00:00:00' When you modify a database column with a function in the WHERE clause. SELECT student_id. use the TO_CHAR function together with a format model SELECT SYS_CONTEXT ('USERENV'. minute. you must specify the correct case and add the extra blanks to fill it up to a total length of nine characters. and th in lowercase after each number TRUNC (DATE datatype) the effect of including the records no matter what the time. To change the display format DATE. you cannot take advantage of an index if one exists on the column. This format contains no time portion and must be listed exactly in the format YYYY-MM-DD. year. 'NLS_DATE_FORMAT') FROM dual uses the fm mask to eliminate the extra spaces add th suffix on the day (dd) mask. 'DD-MON-YYYY HH24:MI:SS') FROM enrollment WHERE enroll_date >= DATE '2007-02-07' AND enroll_date < DATE '2007-02-08' If you want to include the time portion. The RR represents a two-digit year based on the century. DD-MON-RR.

Finally. 110. SELECT course_no. TO_CHAR(start_date_time. format the output with a TO_CHAR format mask to display the result in the ‘MM/DD/YYYY DY’ format. 'SUNDAY'). TO_CHAR(start_date_time. Order the result by the day of the week starting with Sunday. 15 minutes is 15/1440. The Oracle/PLSQL ADD_MONTHS function returns a date plus n months The LAST_DAY function takes a single parameter and accepts only parameters of the DATE data type.WHERE TO_CHAR(start_date_time. . section_id. 'fmDay') = 'Sunday' A column value. 155. 'Day DD-Mon-YYYY HH:MI am') FROM section WHERE TO_CHAR(start_date_time.' AS "Start" FROM section WHERE section_id IN (146. 'fmDay')||'. 127. Either your column must be a DATE datatype column or you must convert it with the TO_DATE function. the NEXT_DAY function is applied. which is the total number of minutes in a day).” -----------------SYSDATE+3/24 The fraction 3/24 represents three hours. 'MM/DD/YYYY'). 85. 85. 155. 'Day DD-Mon-YYYY HH:MI am') FROM section WHERE TO_CHAR(start_date_time. 127. 'fmDay') = 'Sunday' ----------------SELECT 'Section '||section_id||' begins on '|| TO_CHAR(start_date_time. TO_CHAR(NEXT_DAY(TO_DATE('12/31/1999'. 'Day') = 'Sunday' You can use the fill mode (fm) with the format mask to suppress the extra blanks. such as ‘14-APR-2007 09:30:00’ is inclusive of the text literals ‘01-JUL-2007 00:00:00’ and ‘31-JUL-2007 23:59:59’ because the first digit of the column value 1 falls within the range of the characters 0 and 3 SELECT course_no. To determine the date of the next Sunday. you can also express minutes as a fraction of 1440 (60 minutes × 24 hours = 1440. section_id. The Oracle/PLSQL NEXT_DAY function returns the first weekday that is greater than a date. 'D') Your answer may be phrased similar to the following: “Display the day of the week when the sections 146. or 1/96. 121. and 148 start. 148) ORDER BY TO_CHAR(start_date_time. 110. 121. For example. or any equivalent fraction or decimal number.'MM/DD/YYYY DY') "First Sunday" The text string ‘12/31/1999’ is first converted to a date.

TIMESTAMP WITH TIME ZONE data type includes the time zone displacement value select to_char(systimestamp. in the DATE data type. not the time displayed by default in the column. .VARCHAR2(return type) ALTER SESSION SET TIME_ZONE = 'America/New_York' ALTER SESSION SET TIME_ZONE = dbtimezone ALTER SESSION SET TIME_ZONE = local when using EXTRACT on this data type. FF4 displays the fractional seconds with a four-digit precision.DATE(return type) CURRENT_TIMESTAMP Returns the individual’s session date and time in the data type TIMESTAMP WITH TIME ZONE value. if the client session is in a different time zone. --TIMESTAMP(return type) SESSIONTIMEZONE Returns the time zone offset value of the session time zone or the time zone region name. depending on the setupof the database. and fractional seconds and time zone of the server. all date and time values are returned in UTC.SS.--TIMESTAMP WITH TIME ZONE (return type) LOCALTIMESTAMP Returns in the TIMESTAMP format the current date and time in the local session time. This is similar to the SYSDATE function but includes the fractional seconds and time zone. The fractional seconds are expressed with the FF format mask. For example. The TO_TIMESTAMP function sets the time portion of the DATE column to midnight.--VARCHAR2(return type) DBTIMEZONE Returns the time zone offset value of the database server time zone or time zone region name. (The local session time can be different than the server’s date and time.'DD-MM-RRRR HH. TIMESTAMP WITH TIME ZONE(return type) SYSTIMESTAMP Returns the date.) -. when you apply a TO_TIMESTAMP function to a DATE data type column. depending on the setup of the database.-.The TIMESTAMP data type allows you to store optional fractional seconds with a precision of up to nine digits. you add a number from 1 to 9 after the FF mask. time. the default is six digits.FF AM TZH:TZM') from dual SYSDATE Returns the database server operating system’s current date and time. To change the default precision of the fractional seconds.MI. – DATE(return type) CURRENT_DATE Returns the date and time of the local session time zone.

in SQL Developer’s Script Output tab. hours. SELECT DISTINCT location FROM section SELECT location FROM section GROUP BY location For a select statement using a group by function the columns used in the ORDER BY clause must appear in the SELECT list. and seconds. However. INTERVAL DAY [(day_precision)] TO SECOND [(fractional_seconds_precision)] Values are expressed in days. all columns are left aligned. the fractional seconds precision has a six-digit default value. whereas COUNT with a column excludes rows that contain nulls. The default year precision is two digits. Aggregate Functions: The difference is that COUNT(*) counts rows that contain null values. In general. The TO_DATE function and TO_CHAR functions are overall very versatile as they allow you a large variety of different format model choices. The default precision for the DAY is 2. just as the WHERE clause is used to eliminate rows . which is a distinct list of the values in the LOCATION column. So you may choose the functions that fit your specific requirements. minutes. both in SQL*Plus and the SQL Developer Results window. The following two queries return the same result. The syntax for the CAST function is as follows. CAST(expression AS data type) One disadvantage of the CAST function is casting into VARCHAR2 and CHAR data types because they need to be constrained to a determined length. character values are always left aligned. Applying functions to database columns in the SELECT clause does not affect performance. values of the NUMBER data type are always right aligned.INTERVAL YEAR [(year_precision)] TO MONTH Values are expressed in years and months. which is unlike the normal use of ORDER BY The purpose of the HAVING clause is to eliminate groups.

if any exist. this query is best suited for situations in which the inner query does not returns a very large result set and where no indexes exist on the compared columns. Inline views.The HAVING clause can use multiple operators to further eliminate any groups. You can do this by adding additional restricting criteria in the WHERE clause of the statement. . and the join is indicated with the keywords NATURAL JOIN. The inner query is executed once. you use the ON condition A natural join joins tables based on the columns with the same name and data type. Here there is no need to prefix the column name with the table alias. NOT EXISTS offers better performance because indexes are usually used. Subqueries NOT IN operator subqueries that can potentially return null values will return no rows ORDER BY clause is not permitted in a subquery(allowed in inline view) the difference between NOT EXISTS and NOT IN lies in the way NULL values are treated. parentheses around the column in using clause is compulsory In case the column names on the tables are different. the NOT IN operator does not. identifies the common column between the tables. If your query involves a NOT EXISTS condition. Equijoins the JOIN keyword replaces the comma between the tables and identifies the tables to be joined. allow you to treat a query as a virtual table or view. Any use of the ON clause or the USING clause is not allowed with the NATURAL JOIN keywords. Therefore. The advantage of correlated subqueries is that they can use indexes on the correlated columns. The NOT EXISTS operator tests for NULL values. you can specify either the USING condition or the ON condition. also referred as the USING clause. There is not even a mention of which column(s) to join. your optimization strategy should focus on eliminating as many rows as possible from the outer query. Generally speaking. Either the columns used in the HAVING clause must be found in the GROUP BY clause or they must be aggregate functions. you cannot modify it to a NOT IN condition if the subquery can return null values. The USING condition. A noncorrelated subquery executes the inner query first and then feeds this result to the outer query. and the common columns cannot list a table alias. A correlated subquery evaluates the inner query for every row of the outer query. In many circumstances. The keyword INNER is optional and typically omitted. To express a join condition. also referred to as queries in the FROM clause.

q’!!’ q single quote delimiter then the string then single quote . Oracle does not support a full outer join with the (+) outer join operator.. To include single quotes use this notation q‘!O’Neil!’ . such as an image file. The following is the syntax for the conditional INSERT ALL.]] (query) The insert_clause syntax is defined as follows.Whenever a subquery with the ALL operator fails to return a row.)] Oracle places a lock on a row whenever the row is manipulated through a DML statement.. eliminate duplicate values. a query containing the UNION operator is more time-consuming to execute than a query with the UNION ALL operator All set operators. To accomplish a full outer join.]... which returns false. This is different from the ANY operator. Complex Joins The keywords LEFT OUTER are added to the JOIN keyword.. so DISTINCT is not needed. INSERT ALL WHEN condition THEN insert_clause [insert_clause.. except UNION ALL. Users can continue to query the row and see the old values until the row is committed. To store multimedia content in the Oracle database. Insert. Update. Set Operators IN UNION operator the results are automatically sorted by the order in which the columns appear in the SELECT list.] [WHEN condition THEN insert_clause [insert_clause.expression|DEFAULT].. column]..)] [VALUES (expression|DEFAULT[.. indicating that the rows in the table to the left side of the JOIN keyword are to be listed.. the query is automatically true. you need to use either the ANSI full outer join syntax or the UNION operator.] [ELSE insert_clause [insert_clause.. and Delete The BFILE data type allows you to store the pointer to an external binary file.. use the BLOB data type.. INTO tablename [(column [. This prevents other users from manipulating the row until it is either committed or rolled back.

such as before specific DML statements occurred. using the following syntax. If the foreign key constraint is set to ON DELETE SET NULL. you can query the data dictionary views USER_CONSTRAINTS or ALL_CONSTRAINTS The TRUNCATE statement works more quickly than the DELETE statement to remove all rows from a table because the database does not have to store the undo information in case a ROLLBACK command is issued. . before you delete the parent row. UPDATE. a unique number that tracks the order in which events occur. If you issue a DELETE on a parent table with associated child records. you must delete the child rows first. In this case. CASCADE. you cannot update rows while a table is being altered). It disallows the deletion of a parent if child rows exist. and DELETE operations with the MERGE command. MERGE INTO tablename USING {query|tablename} ON (condition) [WHEN MATCHED THEN UPDATE set_clause [DELETE condition]] [WHEN NOT MATCHED THEN INSERT values_clause] The MERGE syntax contains an optional DELETE condition to the WHEN MATCHED THEN UPDATE clause The only rows deleted are the ones that satisfy both the DELETE and the ON conditions Depending on how DELETEs on the foreign key are defined. Locks are not just acquired on individual rows but also on the entire table when a DDL operation such as an ALTER TABLE or a CREATE INDEX command is issued. the children are automatically deleted. and the foreign key constraint is set to ON DELETE CASCADE. To find out which foreign keys have DELETE CASCADE. This feature enables queries to return a read-consistent result. or SET NULL. The default option for a foreign key constraint with respect to DELETEs is RESTRICT. There are three different ways you can specify a foreign key constraint with respect to deletes: RESTRICT. the SET NULL constraint. or the default RESTRICT constraint. you can break the string into pieces and place the ampersand at the end of one string and then concatenate it with the remainder of the string. the child rows are updated to a null value. such as the creation of online indexes Oracle automatically handles this with the use of the System Change Number (SCN). Oracle’s flashback query feature allows you to look at values of a query at a specific time in the past. You can perform combined INSERT. A DML operation cannot update the table while the DDL operation is in progress (for example. This can be useful in case a user accidentally performs an unintended but committed DML change. and the same holds true for the reverse: A DDL command on a table cannot be executed if users are holding locks on the table (with some exceptions.Alternatively. provided that the foreign key column of the child table allows nulls.

such as legacy systems. you can use an optional index clause to explicitly create an index with predefined storage parameters. constraints. you can use an optional index clause to explicitly create an index with predefined storage parameters. The default is to check the constraint when the data manipulation occurs. Partitioning a table essentially means splitting a table into smaller pieces. 362 of 553 . Before making any changes. SELECT statements are issued against external tables. Because unique and primary key constraints automatically create a unique index. or any other objects associated with the base table except the NOT NULL constraints. nor can you build an index on an external table. and Drop Tables Check constraints enforce logical expressions on columns. Because unique and primary key constraints automatically create a unique index. This allows you to define the index on a different tablespace (which is often on a different physical device) for better performance. a null value is also acceptable. column default values. When the primary key of a table comprises most or all of the columns in a table. except for the NOT NULL constraints If the foreign key column is defined as allowing nulls. much as with any other table. The individual partitions often are stored in different tablespaces. Tables created with the create table as syntax construct do not inherit the primary key. constraints are not automatically preserved in the new table. Alter. Oracle allows read access to data stored outside the database. This allows you to define the index on a different tablespace (which is often on a different physical device) for better performance. you might want to consider storing the data in an index-organized table With the help of external tables. the constraint is not checked immediately but only when the transaction is committed. If a constraint is set as DEFERRABLE. indexes. You cannot insert into or update and delete from an external table. Very large tables become more manageable for database administration tasks when they are stored on different partitions A temporary table is session-specific when created with the ON COMMIT PRESERVE ROWS keywords and transaction specific when created with the ON COMMIT DELETE ROWS keywords. which receive a system-generated name that starts with SYS_. The DEFERRABLE clauses enforce the timing when the constraint is checked. which must evaluate to true for every row in the table.Create. you can find out which objects are dependent on the table by querying the USER_DEPENDENCIES or ALL_DEPENDENCIES data dictionary views When a table is created from another table. foreign keys.

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master Your Semester with a Special Offer from Scribd & The New York Times

Cancel anytime.