You are on page 1of 12

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

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 . The BLOB data type stores the content inside the Oracle database. If there are multiple operators of the same precedence. The connect identifier matches either an entry in a file called TNSNAMES. execute the CLEAR COLUMNS command in SQL*Plus.000 characters If you want to store data containing more than 4. The column headings are truncated to the specified length COL description FORMAT A30 To clear all the column formatting. images. or music. A CHAR column can store up to 2.000 characters. The first digit (5) is called the precision. whereas the BFILE data type stores only a reference to the file location directory and the file name.ORA SQL*Plus stores the last SQL command you typed in what is referred to as the SQL*Plus buffer. Datatypes NUMBER(5. the second digit (2) is referred to as the scale VARCHAR2 maximum size is 4. If you write a SQL query using DISTINCT or UNIQUE.000 characters.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. 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. meaning that any AND conditions are evaluated first.2) can have a maximum of three digits before the decimal point and two digits after the decimal point. You can re-execute a statement by just pressing the / key or typing the SQL*Plus RUN command. the case of the data must match exactly The AND operator always takes precedence over the OR operator. SQL considers a NULL value equal to another NULL value. When you compare a text literal to a database column.

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

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

nd. SELECT course_no. which is defined as YYYY-MM-DD HH24:MI:SS. if the two-digit year is between 50 and 99. use the ANSI TIMESTAMP keyword. you can specify a date in the ANSI format . The literal must be in the ANSI TIMESTAMP format. use the TO_CHAR function together with a format model SELECT SYS_CONTEXT ('USERENV'. The RR represents a two-digit year based on the century. day. such as the TRUNC function on the database column START_DATE_TIME. unless it is a function-based index. month. The following query returns no rows. SELECT student_id. and second When you query a DATE data type column. to include the st. 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. minute. year.[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. as long as the date Is same Instead of using Oracle’s date literals. then it’s the previous century. DD-MON-RR. This format contains no time portion and must be listed exactly in the format YYYY-MM-DD. 'NLS_DATE_FORMAT') FROM dual uses the fm mask to eliminate the extra spaces add th suffix on the day (dd) mask. To change the display format DATE. TO_CHAR(enroll_date. if the two-digit year is between 00 and 49. rd. hour. '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. section_id. TO_CHAR(start_date_time. 'Day DD-Mon-YYYY HH:MI am') FROM section . Oracle displays it in the default format determined by the database NLS_DATE_FORMAT parameter. it’s the current century. with the DATE keyword prefix. TO_CHAR(enroll_date. if you choose the ‘Day’ format 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. SELECT student_id. you cannot take advantage of an index if one exists on the column.

or any equivalent fraction or decimal number. TO_CHAR(start_date_time. . Either your column must be a DATE datatype column or you must convert it with the TO_DATE function. 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. SELECT course_no. 121. 'fmDay') = 'Sunday' A column value. you can also express minutes as a fraction of 1440 (60 minutes × 24 hours = 1440. 110. The Oracle/PLSQL NEXT_DAY function returns the first weekday that is greater than a date. 155. 'Day DD-Mon-YYYY HH:MI am') FROM section WHERE TO_CHAR(start_date_time. To determine the date of the next Sunday. 'fmDay') = 'Sunday' ----------------SELECT 'Section '||section_id||' begins on '|| TO_CHAR(start_date_time. which is the total number of minutes in a day). Finally. TO_CHAR(start_date_time. 'D') Your answer may be phrased similar to the following: “Display the day of the week when the sections 146. 'Day DD-Mon-YYYY HH:MI am') FROM section WHERE TO_CHAR(start_date_time. 'fmDay')||'. 127. 155.' AS "Start" FROM section WHERE section_id IN (146.” -----------------SYSDATE+3/24 The fraction 3/24 represents three hours. 'Day') = 'Sunday' You can use the fill mode (fm) with the format mask to suppress the extra blanks. 121.'MM/DD/YYYY DY') "First Sunday" The text string ‘12/31/1999’ is first converted to a date. 'MM/DD/YYYY'). section_id. 'SUNDAY'). and 148 start. 110. 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. Order the result by the day of the week starting with Sunday. 15 minutes is 15/1440. or 1/96. 85. section_id. TO_CHAR(NEXT_DAY(TO_DATE('12/31/1999'. format the output with a TO_CHAR format mask to display the result in the ‘MM/DD/YYYY DY’ format. the NEXT_DAY function is applied.WHERE TO_CHAR(start_date_time. 127. For example. 148) ORDER BY TO_CHAR(start_date_time. 85.

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

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

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

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

and DELETE operations with the MERGE command. such as before specific DML statements occurred. There are three different ways you can specify a foreign key constraint with respect to deletes: RESTRICT. A DML operation cannot update the table while the DDL operation is in progress (for example. 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. Oracle’s flashback query feature allows you to look at values of a query at a specific time in the past. 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. before you delete the parent row. You can perform combined INSERT. If the foreign key constraint is set to ON DELETE SET NULL. the child rows are updated to a null value. and the foreign key constraint is set to ON DELETE CASCADE. such as the creation of online indexes Oracle automatically handles this with the use of the System Change Number (SCN). To find out which foreign keys have DELETE CASCADE. you cannot update rows while a table is being altered). In this case. 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. If you issue a DELETE on a parent table with associated child records. UPDATE. The default option for a foreign key constraint with respect to DELETEs is RESTRICT. CASCADE. provided that the foreign key column of the child table allows nulls. . using the following syntax. This can be useful in case a user accidentally performs an unintended but committed DML change. It disallows the deletion of a parent if child rows exist. or the default RESTRICT constraint. or SET NULL.Alternatively. the children are automatically deleted. a unique number that tracks the order in which events occur. 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 SET NULL constraint. 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. you must delete the child rows first. This feature enables queries to return a read-consistent result.

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