Skip Headers
Oracle® Database Express Edition 2 Day Developer Guide
10g Release 2 (10.2)

Part Number B25108-01
Go to Documentation Home
Home
Go to Book List
Book List
Go to Table of Contents
Contents
Go to Index
Index
Go to Master Index
Master Index
Go to Feedback page
Feedback

Go to previous page
Previous
Go to next page
Next
View PDF

3 Using SQL

This section discusses how to use Structured Query Language (SQL) with Oracle Database Express Edition, including how to retrieve and manipulate data, use SQL functions, and create database objects.

This section contains the following topics:


See Also:


Overview of SQL

SQL is nonprocedural language for accessing a database. You run SQL statements commands to perform various tasks, such as retrieving data from tables in Oracle Database XE. The SQL language automatically handles how to navigate the database and perform the desired task. All database operations are performed using SQL statements.

With SQL statements you can perform the following:

Oracle SQL statements are divided into several categories:

A statement consists partially of SQL reserved words, which have special meaning in SQL and cannot be used for any other purpose. For example, SELECT and UPDATE are reserved words and cannot be used as table names. For a list of SQL reserved, see Appendix B, "Reserved Words".

A SQL statement is an instruction. The statement must be the equivalent of a complete SQL sentence, for example:

SELECT last_name, department_id FROM employees;


See Also:

Oracle Database SQL Reference for more information about the types of SQL statements

Running SQL Statements

You can enter and run SQL statements with the SQL Commands page, Script Editor page, or SQL Command Line (SQL*Plus).

Using the SQL Commands and Script Editor pages are described in this section. The SQL Commands page is a simpler interface and easier to use.

Both SQL Commands and Script Editor pages enable you to save your SQL statements as a script file in a database repository for future use. You can run multiple SQL statements in the Script Editor page. Script Editor also enables you to download the script to the local file system, which can be run as a SQL script with SQL Command Line. For information about running SQL statements or SQL scripts with SQL Command Line, see Appendix A, "Using SQL Command Line".

This section contains the following topics:

Running SQL Statements on the SQL Commands Page

To enter and run SQL statements in the SQL Commands page:

  1. Log in to the Database Home Page. See "Logging in to the Database Home Page". To run the examples in this guide, log in as user HR with your password for the HR account.

  2. On the Database Home Page, click the SQL icon to display the SQL page.

  3. Click the SQL Commands icon to display the SQL Commands page.

  4. On the SQL Commands page, enter the SQL statements in Example 3-1. Note that SQL statements are terminated with a semi colon (;) in the examples. The semi colon is required when running the SQL statements in a SQL script or at the SQL Command Line prompt, but it is optional on the SQL Commands page.

  5. Select (highlight) the SQL statement that you want to run, then click Run to run the statement and display the results.

    Description of xe_sql_commands.gif follows
    Description of the illustration xe_sql_commands.gif

  6. If you want to save the SQL statements for future use, click the Save button.

  7. In the Name field, enter a name for the saved SQL statements. You can also enter an optional description. Click the Save button to save the SQL statement.

  8. To access saved SQL statements, click the Saved SQL tab and select the name of the saved SQL statement that you want to access.


See Also:

Oracle Database Express Edition Application Express User's Guide for detailed information about using SQL Commands

Running SQL Statements in the Script Editor Page

You can enter SQL statements on the Script Editor page and create a SQL script that can be saved in the database. The script can be downloaded to the local file system, and can be run from SQL Command Line (SQL*Plus). For information about running SQL scripts from SQL Command Line, see "Running Scripts From SQL Command Line".

To access and run SQL statements on the SQL Script Editor page:

  1. Log in to the Database Home Page. See "Logging in to the Database Home Page". To run the examples in this guide, log in as user HR with your password for the HR account.

  2. On the home page, click the SQL icon to display the SQL page.

  3. Click the SQL Scripts icon to display the Script Editor page.

  4. Click the Create button to create a SQL script.

  5. In the Script Name field, enter a name (my_sql_script) for the script.

  6. In the Script Editor entry area, enter the SQL statements and comments in Example 3-2.

    Description of xe_sql_script_editor.gif follows
    Description of the illustration xe_sql_script_editor.gif

  7. Click the Run button on the Script Editor page to begin the processing of the statements in the script.

    The Run Script page displays information about the script, including any errors or SQL Command Line (SQL*Plus) commands that will be ignored when the script is run.

  8. Click the Run button on the Run Script page to confirm your request, and start running the script.

  9. Click the View Results icon for the script (my_sql_script) on the Manage Scripts page to display the results of the script.

  10. Select the Detail view and enable all the Show options on the Results page to display details about the script results.

    Description of xe_script_editor_results.gif follows
    Description of the illustration xe_script_editor_results.gif

  11. Click the Edit Script button to continue working on the SQL script.

  12. When you are finished updating the script, click the Save button to save the script file in the database repository for future use.

  13. To save the SQL script on the local file system, click the Download button, and choose the location for the script file. Note that the .sql extension is appended to the SQL script name.


See Also:

Oracle Database Express Edition Application Express User's Guide for detailed information about using SQL Scripts

Retrieving Data With Queries

You can retrieve data from rows stored in one or more database tables or views with a query using the SQL SELECT statement. The SELECT statement retrieves all of or part of the column data from rows depending on the conditions that you specify in the WHERE clauses. The group of columns that are selected from a table is referred to as the SELECT list.

This section contains the following topics:


See Also:

Oracle Database SQL Reference for detailed information about the SQL SELECT statement

Displaying Data Using the SELECT Statement

With the SQL SELECT statement, you can query and display data in tables or views in a database.

Example 3-1 shows how to use SELECT to retrieve data from the employees and departments tables. In this example, the data for all columns in a row (record) of the tables are retrieved using the wildcard (*) notation. Note the use of comments to document the SQL statements. The comments (or remarks) in this example begin with two hyphens (--), but you can also use rem or REM.

Example 3-1 Using the SQL SELECT Statement to Query All Data From a Table

-- the following uses the wildcard * to retrieve all the columns of data in
-- all rows of the employees table
SELECT * FROM employees;

-- the following uses the wildcard * to retrieve all the columns of data in
-- all rows of the departments table
SELECT * FROM departments;

Example 3-2 shows how to use SELECT to retrieve data for specific columns of the employees and departments tables. In this example, you explicitly enter the column names in the SELECT statement. For information about the columns in the employees and departments table, see "Managing Database Objects With Object Browser".

Example 3-2 Using the SQL SELECT Statement to Query Data From Specific Columns

-- the following retrieves data in the employee_id, last_name, first_name columns
SELECT employee_id, last_name, first_name FROM employees;

-- the following retrieves data in the department_id and department_name columns
SELECT department_id, department_name FROM departments;

Example 3-3 shows how to use SELECT to retrieve data from the emp_details_view view.

Example 3-3 Using the SQL SELECT Statement to Query Data in a View

-- the following retrieves all columns of data in all rows of the emp_details_view
SELECT * FROM emp_details_view;

-- the following retrieves data from specified columns in the view
SELECT employee_id, last_name, job_title, department_name, country_name, 
       region_name FROM emp_details_view;

Using a Column Alias to Change Headings When Selecting Data

When displaying the result of a query, SQL normally uses the name of the selected column as the column heading. You can change a column heading by using a column alias to make the heading more descriptive and easier to understand.

You can specify the alias after the column name in the SELECT list using a space as a separator. If the alias contains spaces or special characters, such as number sign # or dollar sign $, or if it is case-sensitive, enclose the alias in quotation marks " ".

Example 3-4 shows the use of a column alias to provide a descriptive heading for each of the columns selected in a query.

Example 3-4 Using a Column Alias for a Descriptive Heading in a SQL Query

-- the following retrieves the data in employee_id, last_name, first_name columns
-- and provides column aliases for more descriptive headings of the columns
SELECT employee_id "Employee ID number", last_name "Employee last name", 
  first_name "Employee first name" FROM employees;

Restricting Data Using the WHERE Clause

The WHERE clause uses comparison operators to identify specific rows in a table. When used with the SELECT statement, you can selectively retrieve rows from a table, rather than retrieving all rows of a table.

Comparison operators include those listed in Table 3-1.

Table 3-1 Comparison Operators

Operator Definition

=, !=, <>

Test for equal to, not equal to, not equal to

>, >=, <, <=

Test for greater than, greater than or equal to, less than, less than or equal to

BETWEEN ... AND ...

Checks for a range between and including two values

LIKE

Searches for a match in a string, using the wildcard symbols % (zero or multiple characters) or _ (one character)

IN ( ), NOT IN ( )

Tests for a match, or not match, in a specified list of values

IS NULL, IS NOT NULL

Checks whether a value is null, is not null


Example 3-5 shows how to use SELECT with a WHERE clause and several comparison operators to retrieve specific rows of data from the employees table.

Example 3-5 Selecting Data With the SQL WHERE Clause to Restrict Data

-- the following retrieves data where the manager_id equals 122
SELECT * FROM employees WHERE manager_id = 122;

-- this retrieves data where the manager_id equals 122 and job_id is ST_CLERK
SELECT * FROM employees WHERE manager_id = 122 AND job_id = 'ST_CLERK';

-- this retrieves employees with managers with IDs between 122 and 125 inclusive
SELECT * FROM employees WHERE manager_id BETWEEN 122 AND 125;

-- this uses LIKE with the wildcard % to retrieve employee data 
-- where the last name contains mar somewhere in the name string
SELECT employee_id, last_name FROM employees WHERE last_name LIKE '%mar%';

-- this uses LIKE with the wildcard % to retrieve employee data 
-- from the employees table where the last name starts with Mar
SELECT employee_id, last_name FROM employees WHERE last_name LIKE 'Mar%';

-- this retrieves employee data where the commission percentage is not null
SELECT employee_id, last_name FROM employees WHERE commission_pct IS NOT NULL;

-- the following retrieves data where the employee_id equals 125, 130, or 135
SELECT employee_id, last_name, first_name FROM employees
       WHERE employee_id IN (125, 130, 135);


See Also:

Oracle Database SQL Reference for detailed information about using the WHERE clause

Using Character Literals in SQL Statements

Many SQL statements contain conditions, expressions, and functions that require you to specify character literal values. By default, you must use single quotation marks with character literals, such as 'ST_CLERK' or 'Mar%'. This technique can sometimes be inconvenient if the text itself contains single quotation marks. In such cases, you can also use the quote-delimiter mechanism, which enables you to specify q or Q followed by a single quotation mark and then another character to be used as the quotation mark delimiter.

The quote-delimiter can be any single-byte or multi-byte character except for a space, tab, or return. If the opening quote-delimiter is a left bracket [, left brace {, left angle bracket <, or left parenthesis ( character, then the closing quote delimiter must be the corresponding right bracket ], right brace }, right angle bracket >, or right parenthesis ) character. In all other cases, the opening and closing delimiter must be identical.

The following character literals use the alternative quoting mechanism:


q'(name LIKE '%DBMS_%%')'
q'#it's the "final" deadline#'
q'<'Data,' he said, 'Make it so.'>'
q'"name like '['"'

You can specify national character literals for unicode strings with the N'text' or n'text' notation, where N or n specifies the literal using the national character set. For example, N'résumé' is a national character literal. For information about unicode literals, see "Unicode String Literals".


See Also:


Using Regular Expressions When Selecting Data

Regular expressions enable you to search for patterns in string data by using standardized syntax conventions. A regular expression can specify complex patterns of character sequences.

You specify a regular expression with metacharacters and literals. Metacharacters are operators that specify search algorithms. Literals are the characters for which you are searching.

The regular expression functions and conditions include REGEXP_INSTR, REGEXP_LIKE, REGEXP_REPLACE, and REGEXP_SUBSTR. Example 3-6 shows some examples of the use of the regular expression functions and conditions.

Example 3-6 Using Regular Expressions With the SQL SELECT Statement

-- in the following example, the REGEXP_LIKE is used to select rows where
-- the value of job_id starts with ac, fi, mk, or st, 
-- then follows with _m, and ends with an or gr
-- the metacharacter | specifies OR
-- the 'i' option specifies case-insensitive matching
SELECT employee_id, job_id FROM employees 
   WHERE REGEXP_LIKE (job_id, '[ac|fi|mk|st]_m[an|gr]', 'i');

-- in the following example, REGEXP_REPLACE is used to replace 
-- phone numbers of the format "nnn.nnn.nnnn" with 
-- parentheses, spaces, and dashes to produce this format "(nnn) nnn-nnnn"
-- digits (0-9) are denoted with the metacharacter [:digit:]
-- the metacharacter {n} specifies a fixed number of occurrences
-- the \ is used an escape character so that the subsequent metacharacter 
-- in the expression is treated as a literal, such as \.; otherwise, the 
-- metacharacter . denotes any character in the expression
SELECT phone_number, REGEXP_REPLACE( phone_number,
 '([[:digit:]]{3})\.([[:digit:]]{3})\.([[:digit:]]{4})', '(\1) \2-\3') 
 "Phone Number" FROM employees;

-- in the following example, REGEXP_REPLACE is used to replace
-- phone numbers of the format "nnn.nnn.nnnn.nnnnnn"
-- with the format "+nnn-nn-nnnn-nnnnnn"
SELECT phone_number, REGEXP_REPLACE( phone_number,
 '([[:digit:]]{3})\.([[:digit:]]{2})\.([[:digit:]]{4})\.([[:digit:]]{6})',
 '+\1-\2-\3-\4') "Phone Number" FROM employees;

-- in the following example, REGEXP_SUBSTR returns the first substring
-- composed of one or more occurrences of digits and dashes
-- the metacharacter + specifies multiple occurrences in [[:digit:]-]+
SELECT street_address, REGEXP_SUBSTR(street_address, '[[:digit:]-]+', 1, 1) 
  "Street numbers" FROM locations;

-- in the following example, REGEXP_INSTR starts searching at the first character
-- in the string and returns the starting position (default) of the second
-- occurrence of one or more non-blank characters
-- REGEXP_INSTR returns 0 if not found
-- the metacharacter ^ denotes NOT, as in NOT space [^ ]
SELECT street_address, REGEXP_INSTR(street_address, '[^ ]+', 1, 1) 
  "Position of 2nd block" FROM locations;


See Also:


Sorting Data Using the ORDER BY Clause

You can use SELECT with the ORDER BY clause to retrieve and display rows from a table ordered (sorted) by a specified column in the table. The specified column in the ORDER BY clause does not have to be in the SELECT list of columns that you want to display.

You can specify the sort order as ASC for ascending or DESC for descending. The default sort order is ascending, which means:

  • Numeric values are displayed with the lowest values first, such as 1 to 999.

  • Character values are displayed in alphabetical order, such as A first and Z last.

  • Date values are displayed with the earliest value first, such as 01-JUN-93 before 01-JUN-95.

Null (empty) values are displayed last for ascending sequences and first for descending sequences.

Example 3-7 shows how to use SELECT with the ORDER BY clause to retrieve and display rows from the employees table ordered (sorted) by specified columns.

Example 3-7 Selecting Data With the SQL ORDER BY Clause to Sort the Data

-- the following retrieves rows with manager_id = 122 ordered by employee_id
-- the order is the default ascending order, lowest employee_id displays first
SELECT * FROM employees WHERE manager_id = 122 ORDER BY employee_id;

-- the following retrieves rows ordered by manager_id
-- the order is specified as descending, highest manager_id displays first
SELECT employee_id, last_name, first_name, manager_id FROM employees
      ORDER BY manager_id DESC;

See Example 3-23 for the use of ORDER BY with the GROUP BY clause.


See Also:

Oracle Database SQL Reference for detailed information about using ORDER BY with SELECT

Displaying Data From Multiple Tables

You can use SELECT to display data from multiple tables. This process is referred to as joining tables. In a join, rows from multiple tables are usually linked by similar columns.

Joining tables is useful when you need to view data that is stored in multiple tables. For example, the employees table contains employee information with a column of department IDs, but not the department names. The departments table contains columns for department IDs and names. By joining the tables on the department ID, you can view an employee's information with the corresponding department name.

There are several types of joins, including self, inner, and outer. A self-join joins a table to itself. Example 3-11 is an example of a self- join. An inner join (sometimes called a simple join) is a join of two or more tables that returns only those rows that satisfy the join condition. Any unmatched rows are not displayed in the output. Example 3-8 and Example 3-9 are examples of inner joins. An outer join extends the result of a simple join. An outer join returns all rows that satisfy the join condition and also returns some or all of those rows from one table for which no rows from the other satisfy the join condition. There are three types of outer joins: LEFT OUTER, RIGHT OUTER, and FULL OUTER. Example 3-12 shows examples of a outer joins.

When you retrieve data from multiple tables, you can explicitly identify to which table a column belongs. This is important when tables contain columns with the same name. You can use the complete table name to explicitly identify a column, such as employees.employee_id, or a table alias. Note the use of the table aliases (d, e, and l) to explicitly identify the columns by table in the SQL statement in Example 3-9 and Example 3-10. The alias is defined in the FROM clause of the SQL statement. A table alias is used, rather than the table name, to simplify and reduce the size of the SQL code.

You can join two tables automatically on all the columns that have matching names and datatypes using the NATURAL JOIN syntax as shown in Example 3-8. This join select rows from the two tables that have equal values in the matched columns. If the columns with the same name have different datatypes, an error results.

Example 3-8 Selecting Data From Two Tables With the SQL NATURAL JOIN Syntax

-- the following SELECT statement retrieves data from two tables
-- that have a corresponding column(s) with equal values
-- for employees and departments, matching columns are department_id, manager_id
SELECT employee_id, last_name, first_name, department_id, 
  department_name, manager_id  FROM employees
  NATURAL JOIN departments;

Example 3-9 is an example of querying data from joined tables using the JOIN ... USING syntax. The first SELECT joins two tables, and the second SELECT joins three tables. With the JOIN ... USING syntax, you explicitly specify the join columns. The columns in the tables that are used for the join must have the same name. Note that the table alias is not used on the referenced columns.

Example 3-9 Selecting Data From Multiple Tables WIth the SQL JOIN USING Syntax

-- the following SELECT statement retrieves data from two tables
-- that have a corresponding column (department_id)
-- note that the employees table has been aliased to e and departments to d
SELECT e.employee_id, e.last_name, e.first_name, e.manager_id, department_id, 
  d.department_name, d.manager_id FROM employees e 
  JOIN departments d USING (department_id);

-- the following SELECT retrieves data from three tables
-- two tables have the corresponding column (department_id) and 
-- two tables have the corresponding column (location_id)
SELECT e.employee_id, e.last_name, e.first_name, e.manager_id, department_id,
  d.department_name, d.manager_id, location_id, l.country_id FROM employees e
  JOIN departments d USING (department_id)
  JOIN locations l USING (location_id);

Example 3-10 is an example of querying data from joined tables using JOIN ... ON syntax. The first SELECT joins two tables, and the second SELECT joins three tables. Using the ON clause enables you to specify a join condition outside a WHERE clause and a join condition with columns that have different name, but equal values.

Example 3-10 Selecting Data From Multiple Tables With the SQL JOIN ON Syntax

-- the following SELECT statement retrieves data from two tables
-- that have a corresponding column department_id
-- note that the employees table has been aliased to e and departments to d
SELECT e.employee_id, e.last_name, e.first_name, e.department_id, 
  d.department_name, d.manager_id FROM employees e 
  JOIN departments d ON e.department_id = d.department_id
  WHERE e.manager_id = 122;

-- the following SELECT retrieves data from three tables
-- two tables have the corresponding column department_id and 
-- two tables have the corresponding column location_id
SELECT e.employee_id, e.last_name, e.first_name, e.department_id,
  d.department_name, d.manager_id, d.location_id, l.country_id FROM employees e
  JOIN departments d ON e.department_id = d.department_id
  JOIN locations l ON d.location_id = l.location_id
  WHERE l.location_id = 1700;

You can join a table to itself, a process called a self-join. For example, if you want to view an employee ID and employee last name with the manager ID and manager name of that employee, you would use a self-join on the employees table as shown in Example 3-11. The employees table is joined to itself using the manager ID of the employee and employee ID of the manager. Note that the columns used for the join have different names. Column aliases, such as emp_id and emp_lastname, were used to clearly identify the column values in the output.

Example 3-11 Self Joining a Table With the SQL JOIN ON Syntax

-- the following SELECT statement retrieves data from the employees table
-- to display employee_id and last_name, along with manager_id and last_name
-- of the employee in a self-join
-- note that the employees table has been aliased to e and m
SELECT e.employee_id emp_id, e.last_name emp_lastname, m.employee_id mgr_id,
  m.last_name mgr_lastname
  FROM employees e 
  JOIN employees m ON e.manager_id = m.employee_id;

Example 3-12 shows how to use outer joins.

Example 3-12 Using SQL Outer Joins

-- the following uses a LEFT OUTER JOIN
-- all rows are retrieved from the left table (employees) even if 
-- there is no match in the right table (departments)
SELECT e.employee_id, e.last_name, e.department_id, d.department_name
  FROM employees e LEFT OUTER JOIN departments d
  ON (e.department_id = d.department_id);

-- the following uses a RIGHT OUTER JOIN
-- all rows are retrieved from the right table (departments) even if 
-- there is no match in the left table (employees)
SELECT e.employee_id, e.last_name, d.department_id, d.department_name
  FROM employees e RIGHT OUTER JOIN departments d 
  ON (e.department_id = d.department_id);

-- the following uses a FULL OUTER JOIN
-- all rows are retrieved from the employees table even if there is no match in
-- the departments table, and all rows are retrieved from the departments table
-- even if there is no match in the left table
SELECT e.employee_id, e.last_name, d.department_id, d.department_name
  FROM employees e FULL OUTER JOIN departments d
  ON (e.department_id = d.department_id);


See Also:

Oracle Database SQL Reference for information about using SELECT with multiple tables

Using Bind Variables With the SQL Commands Page

You can use bind variables with the SQL Commands page to prompt for values when running a SQL statement, rather than supplying the value when the statement is created. Bind variables are prefixed with a colon. You can choose any name for the bind variable name, such as :b, :bind_variable, or :employee_id. For example, you could enter and run the following statement in the SQL Commands page:

SELECT * FROM employees WHERE employee_id = :employee_id

When you run a statement with a bind variable in the SQL Commands page, a window opens prompting you for a value for the bind variable. After entering a value, click the Submit button. Note that you might need to configure your Web browser to allow the popup window to display.

For information about using bind variables with PL/SQL, see "Using Bind Variables With PL/SQL".

Using Pseudocolumns, Sequences, and SQL Functions

With SQL built-in functions, you can manipulate character, numeric, and date data in SQL statements to change how the data is displayed or to convert the data for insertion in a column of a table. You can also perform operations on a collection of data with aggregate functions.

Pseudocolumns are built-in values that provide specific information with a query and are similar to functions without arguments. However, functions without arguments typically return the same value for every row in the result set, whereas pseudocolumns typically return a different value for each row.

This section contains the following topics:


See Also:

Oracle Database SQL Reference for detailed information about SQL functions

Using ROWNUM, SYSDATE, and USER Pseudocolumns With SQL

A pseudocolumn is similar to a table column, but is not stored in a table. A pseudocolumn returns a value, so it is similar to a function without argument. Oracle Database XE provides several pseudocolumns, such as the ROWNUM, SYSDATE, and USER. The ROWNUM pseudocolumn returns a number indicating the order in which Oracle Database XE selects the row in a query. SYSDATE returns the current date and time set for the operating system on which the database resides. USER returns the name of the user name that is currently logged in.

Example 3-13 shows the use of the SYSDATE pseudocolumn. Note the use of the DUAL table, which is automatically created by Oracle Database XE for use as a dummy table in SQL statements. See Example 3-19 for another example of the use of SYSDATE.

Example 3-13 Using the SQL SYSDATE Pseudocolumn

-- the following statement displays the SYSDATE, which is the current system date
-- NOW is a column alias for display purposes
-- DUAL is a dummy table with one row simply used to complete the SELECT statement
SELECT SYSDATE "NOW" FROM DUAL;

Example 3-14 shows the use of the USER pseudocolumn.

Example 3-14 Using the SQL USER Pseudocolumn

-- display the name of the current user, the user name should be HR
SELECT USER FROM DUAL;

Example 3-15 shows the use of the ROWNUM pseudocolumn.

Example 3-15 Using the SQL ROWNUM Pseudocolumn

-- using ROWNUM < 10 limits the number of rows returned to less than 10
SELECT employee_id, hire_date, SYSDATE FROM employees WHERE ROWNUM < 10;

Using Arithmetic Operators

You can use arithmetic operators to create expressions for calculations on data in tables. The arithmetic operators include:

  • Plus sign + for addition

  • Minus sign - for subtraction

  • Asterisk * for multiplication

  • Slash / for division

In an arithmetic expression, multiplication and division are evaluated first, then addition and subtraction. When operators have equal precedence, the expression is evaluated left to right. It is best to include parentheses to explicitly determine the order of operators and provide clarity in the expression.

Example 3-16 shows the use of arithmetic operators in expressions with the data in the employees table. Note the use of a column alias to provide a more descriptive heading for the displayed output.

Example 3-16 Using SQL Arithmetic Operators

-- in the following query the commission is displayed as a percentate instead 
-- of the decimal that is stored in the database
SELECT employee_id, (commission_pct * 100) "Commission %" FROM employees;

-- in the following query, the proposed new annual salary is calculated
-- for employees who report to the manager with ID 145
SELECT employee_id, ((salary + 100) * 12) "Proposed new annual salary" 
  FROM employees WHERE manager_id = 145;

Using Numeric Functions

Oracle Database XE provides a set of numeric functions that you can use in your SQL statements to manipulate numeric values. With numeric functions, you can round to a specified decimal, truncate to a specified decimal, and return the remainder of a division on numeric data.

Example 3-17 shows the use of numeric functions on numeric data.

Example 3-17 Using SQL Numeric Functions

-- you can use the ROUND function to round off numeric data, in this case to
-- two decimal places
SELECT employee_id, ROUND(salary/30, 2) "Salary per day" FROM employees;

-- you can use the TRUNC function to truncate numeric data, in this case to
-- 0 decimal places; 0 is the default so TRUNC(salary/30) would be same
SELECT employee_id, TRUNC(salary/30, 0) "Salary per day" FROM employees;

-- use the MOD function to return the remainder of a division
-- MOD is often used to determine is a number is odd or even
-- the following determines whether employee_id is odd (1) or even (0)
SELECT employee_id, MOD(employee_id, 2) FROM employees;

Using Character Functions

Oracle Database XE provides a set of character functions that you can use in your SQL statements to customize the character values. With character functions, you can perform operations that change the case, remove blanks, extract substrings from, replace substrings in, and concatenate character data.

Example 3-18 shows the use of some character functions on character data.

Example 3-18 Using SQL Character Functions

-- you can use the UPPER function to display uppercase data, LOWER for lowercase
SELECT employee_id, UPPER(last_name), LOWER(first_name) FROM employees;

-- you can use the INITCAP function to display uppercase only the first letter
SELECT employee_id, INITCAP(first_name), INITCAP(last_name) FROM employees;

-- you can use RTRIM and LTRIM to remove spaces from the beginning or end of 
-- character data. Note the use of concatenation operator || to add a space
SELECT employee_id, RTRIM(first_name) || ' ' || LTRIM(last_name) FROM employees;

-- you can use TRIM to remove spaces from both the beginning and end
SELECT employee_id, TRIM(last_name) || ', ' || TRIM(first_name) FROM employees;

-- you can use RPAD to add spaces on the right to line up columns
-- in this case, spaces are added to pad the last_name output to 30 characters
SELECT employee_id, RPAD(last_name, 30, ' '), first_name FROM employees;

-- use SUBSTR to select a substring of the data, in the following only 
-- the characters from 1 to 15 are selected from the last_name
SELECT employee_id, SUBSTR(last_name, 1, 10) FROM employees;

-- use LENGTH to return the number of characters in a string or expression
SELECT LENGTH(last_name) FROM employees;

-- use REPLACE to replace characters in a string or expression
SELECT employee_id, REPLACE(job_id, 'SH', 'SHIPPING') FROM employees
   WHERE SUBSTR(job_id, 1, 2) = 'SH';

Using Date Functions

Oracle Database Express Edition provides a set of date functions to manipulate and calculate date and time data. For example, with date functions you can add months to, extract a specific field from, truncate, and round a date value. You can also calculate the number of months between two dates.

Example 3-19 shows the use of some date functions on date data.

Example 3-19 Using SQL Date Functions

-- in the following statement you can use MONTHS_BETWEEN to compute months
-- employed for employees and then truncate the results to the whole month
-- note the use of the label (alias) "Months Employed" for the computed column
SELECT employee_id, TRUNC(MONTHS_BETWEEN(SYSDATE, HIRE_DATE)) "Months Employed" 
  FROM employees;

-- the following extracts displays the year hired for each employee ID
SELECT employee_id, EXTRACT(YEAR FROM hire_date) "Year Hired" FROM employees;

-- the following extracts and concatenates the year, month, and day from SYSDATE
SELECT EXTRACT(YEAR FROM SYSDATE) || EXTRACT(MONTH FROM SYSDATE) || 
   EXTRACT(DAY FROM SYSDATE) "Current Date" FROM DUAL;

-- the following adds 3 months to the hire_date of an employee
SELECT employee_id, hire_date, ADD_MONTHS(hire_date, 3) FROM employees;

-- LAST_DAY finds the last day of the month for a specific date, such as hire_date
SELECT employee_id, hire_date, LAST_DAY(hire_date) "Last day of month" 
   FROM employees;

-- the following returns the system date, including fractional seconds 
-- and time zone, of the system on which the database resides
SELECT SYSTIMESTAMP FROM DUAL;

Using Conversion Functions

Oracle Database XE provides a set of conversion functions that for use in SQL statements to convert a value from one datatype to another datatype. For example, you can convert a character value to a numeric or date datatype or you can convert a numeric or date value to a character datatype. Conversion functions are useful when inserting values into a column of a table and when displaying data.

When converting a value, you can also specify a format model. A format model is a character literal that specifies the format of data. A format model does not change the internal representation of the value in the database.

Example 3-20 shows how to use the character conversion function with format models.

Example 3-20 Using the SQL Character Conversion Function

-- you can convert the system date (SYSDATE) to a character string and format
-- with various format models and then display the date as follows
SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY AD') "Today" FROM DUAL;
-- FM removes all leading or trailing blanks from Month
SELECT TO_CHAR(SYSDATE, 'FMMonth DD YYYY') "Today" FROM DUAL;
-- the following displays the system date and time with a format model
SELECT TO_CHAR(SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "Now" FROM DUAL;

-- you can convert and format a date column using format models 
-- for Short or Long Date format
SELECT hire_date, TO_CHAR(hire_date,'DS') "Short Date" FROM employees;
SELECT hire_date, TO_CHAR(hire_date,'DL') "Long Date" FROM employees;

-- the following extracts the year, month, and date from SYSDATE, then converts 
-- and formats the result with leading zeros and removes any leading blanks (FM)
SELECT TO_CHAR(EXTRACT(YEAR FROM SYSDATE)) || 
  TO_CHAR(EXTRACT(MONTH FROM SYSDATE),'FM09') || 
  TO_CHAR(EXTRACT(DAY FROM SYSDATE),'FM09') "Current Date" FROM DUAL;

-- the following returns the current date in the session time zone, 
-- in a value in the Gregorian calendar of datatype DATE, 
-- the returned value is converted to character and displayed with a format model
SELECT TO_CHAR(CURRENT_DATE, 'DD-MON-YYYY HH24:MI:SS') "Current Date" FROM DUAL;

-- you can convert and format numeric currency data as a character string 
-- with a format model to add a $, commas, and deciaml point
SELECT TO_CHAR(salary,'$99,999.99') salary FROM employees;

Example 3-21 shows how to use the number conversion function.

Example 3-21 Using the SQL Number Conversion Function

-- you can convert a character string to a number
SELECT TO_NUMBER('1234.99') + 500 FROM DUAL;

-- the format model must match the format of the string you want to convert
SELECT TO_NUMBER('11,200.34', '99G999D99') + 1000 FROM DUAL;

Example 3-22 shows how to use some date conversion functions.

Example 3-22 Using SQL Date Conversion Functions

-- the following converts the character string to a date with 
-- the specified format model
SELECT TO_DATE('27-OCT-98', 'DD-MON-RR') FROM DUAL;

-- the following converts the character string to a date with 
-- the specified format model
SELECT TO_DATE('28-Nov-05 14:10:10', 'DD-Mon-YY HH24:MI:SS') FROM DUAL;

-- the following converts the character string to a date with 
-- the specified format model
SELECT TO_DATE('January 15, 2006, 12:00 A.M.', 'Month dd, YYYY, HH:MI A.M.')
  FROM DUAL;

-- the following converts a character stirng to a timestamp with 
-- the specified datetime format model
SELECT TO_TIMESTAMP('10-Sep-05 14:10:10.123000', 'DD-Mon-RR HH24:MI:SS.FF')
  FROM DUAL;

Be careful when using a date format such as DD-MON-YY. The YY indicates the year in the current century. For example, 31-DEC-92 is December 31, 2092, not 1992 as you might expect. If you want to indicate years in any century other than the current one, use a format model such as the default RR.


See Also:

Oracle Database SQL Reference for detailed information about format models

Using Aggregate Functions

Aggregate or group functions operate on sets of rows to give one result for each group. These sets can be the entire table or the table split into groups.

Example 3-23 shows how to use aggregate functions on collections of data in the database. Aggregate functions include AVG, COUNT, DENSE_RANK, MAX, MIN, PERCENT_RANK, RANK, STDDEV, and SUM. The GROUP BY clause is used to select groups of rows by a specified expression, and returns one row of summary information for each group. The HAVING clause is used to specify which groups to include, or exclude, from the output based on a group condition. The DISTINCT clause causes an aggregate function to consider only distinct values of the argument expression. The ALL clause, which is the default behavior, causes an aggregate function to consider duplicate values.

Example 3-23 Using SQL Aggregate Functions

-- you can use COUNT to count the employees with manager 122
-- note the use of a column alias Employee Count
SELECT COUNT(*) "Employee Count" FROM employees WHERE manager_id = 122;

-- count the employees grouped by manager, also sort the groups
SELECT COUNT(*) "Employee Count", manager_id  FROM employees 
  GROUP BY manager_id 
  ORDER BY manager_id;

-- count the number of employees that receive a commission 
-- this returns the count where the commission_pct is not NULL
SELECT COUNT(commission_pct) FROM employees;

-- count the number of distinct department IDs assigned to the employees
-- this returns a number that does not include duplicates
SELECT COUNT(DISTINCT department_id) FROM employees;

-- you can use MIN, MAX, and AVG to find the minimum, maximum, and average
-- salaries for employees with manager 122
SELECT MIN(salary), MAX(salary), AVG(salary) FROM employees 
  WHERE manager_id = 122;

-- this computes the minimum, maximum, and average salary by job ID groups
-- the job ID groups are sorted in alphabetical order
SELECT MIN(salary), MAX(salary), AVG(salary), job_id FROM employees 
  GROUP BY job_id 
  ORDER BY job_id;

-- the following returns the minimum and maximum salaries for employees grouped
-- by department for those groups having a minimum salary less than $7,000
SELECT department_id, MIN(salary), MAX (salary) FROM employees
   GROUP BY department_id 
   HAVING MIN(salary) < 7000
   ORDER BY MIN(salary);

-- the following uses the PERCENT_RANK function to return the percent ranking
-- for a $11,000 salary among the employees who are managers
-- in this example, a percent ranking of 0 corresponds to the highest salary
SELECT PERCENT_RANK(11000) WITHIN GROUP
   (ORDER BY salary DESC) "Rank of $11,000 among managers" 
   FROM employees WHERE job_id LIKE '%MAN' OR job_id LIKE '%MGR';

-- the following uses the RANK function to return the ranking for a $2,600 salary 
-- among the employees who are clerks, 
-- in this example a ranking of 1 corresponds to the highest salary in the group
SELECT RANK(2600) WITHIN GROUP
   (ORDER BY salary DESC) "Rank of $2,600 among clerks"
   FROM employees WHERE job_id LIKE '%CLERK';

-- the following uses RANK to show the ranking of SH_CLERK employees by salary
-- identical salary values receive the same rank and cause nonconsecutive ranks
SELECT job_id, employee_id, last_name, salary, RANK() OVER
   (PARTITION BY job_id ORDER BY salary DESC) "Salary Rank"
   FROM employees WHERE job_id = 'SH_CLERK';

-- the following uses DENSE_RANK to show the ranking of SH_CLERK employees 
-- by salary, identical salary values receive the same rank and 
-- rank numbers are consecutive (no gaps in the ranking)
SELECT job_id, employee_id, last_name, salary, DENSE_RANK() OVER
   (PARTITION BY job_id ORDER BY salary DESC) "Salary Rank (Dense)"
   FROM employees WHERE job_id = 'SH_CLERK';

-- the following computes the cumulative standard deviation of the salaries 
-- for ST CLERKs ordered by hire_date
SELECT employee_id, salary, hire_date, STDDEV(salary) 
   OVER (ORDER BY hire_date) "Std Deviation of Salary"
   FROM employees WHERE job_id = 'ST_CLERK';

Using NULL Value Functions

Oracle Database XE provides functions that you can use in your SQL statements to work with NULL values. For example, you can substitute a different value if value in a column of a table is NULL.

Example 3-24 shows the use of the SQL NVL function. This function substitutes the specified value when a NULL value is encountered.

Example 3-24 Using the SQL NVL Function

-- use the NVL function to substitute 0 for a NULL value in commission_pct
SELECT commission_pct, NVL(commission_pct, 0) FROM employees;

-- use the NVL function to substitute MISSING for a NULL value in phone_number
SELECT phone_number, NVL(phone_number, 'MISSING') FROM employees;


Example 3-25 shows the use of the SQL NVL2 function. This function returns the second specified expression when the first expression is not NULL. If the first expression is NULL, the third expression is returned.

Example 3-25 Using the SQL NVL2 Function

-- use the NVL2 function to return salary + (salary * commission_pct) 
-- if commission_pct is not NULL; otherwise, if commission_pct is NULL, 
-- then return salary
SELECT employee_id , last_name, salary, 
  NVL2(commission_pct, salary + (salary * commission_pct), salary) income
  FROM employees;

Using Conditional Functions

Oracle Database XE provides conditional functions that you can use in your SQL statements to return a value based on multiple search conditions values.

Example 3-26 shows the use of the SQL CASE functions.

Example 3-26 Using the SQL CASE Function

-- CASE can compare a column or expression or search conditions, returning
-- a result when there is a match. CASE is similar to IF_THEN-ELSE logic.
-- In the following, the value of the hire_date column is compared against various
-- dates. When there is a match, the corresponding calculated result is returned, 
-- otherwise the default calculated salary is returned.
SELECT employee_id, hire_date , salary,
  CASE WHEN hire_date < TO_DATE('01-JAN-90') THEN salary*1.20
       WHEN hire_date < TO_DATE('01-JAN-92') THEN salary*1.15
       WHEN hire_date < TO_DATE('01-JAN-94') THEN salary*1.10 
       ELSE salary*1.05 END  "Revised Salary"
  FROM employees;

Example 3-27 shows the use of the SQL DECODE functions.

Example 3-27 Using the SQL DECODE Function

-- DECODE compares a column or expression to search values, returning a result
-- when there is a match. DECODE is similar to IF_THEN-ELSE logic.
-- In the following, the value of the job_id column is compared against PU_CLERK,
-- SH_CLERK, and ST_CLERK. 
-- When there is a match, the corresponding calculated result is returned,
-- otherwise the original salary is returned unchanged.
SELECT employee_id, job_id , salary,
  DECODE(job_id, 'PU_CLERK', salary*1.05,
                 'SH_CLERK', salary*1.10,
                 'ST_CLERK', salary*1.15,
                             salary) "Revised Salary"
  FROM employees;

Manipulating Data With SQL Statements

Data manipulation language (DML) statements query or manipulate data in existing schema objects. They enable you to:

DML statements are the most frequently used SQL statements.

This section contains the following topics:

Adding Data With the INSERT Statement

You can use the SQL INSERT statement to add a row of data to a table. The data inserted must be valid for the datatype and size of each column of the table. See "Managing Database Objects With Object Browser".

Example 3-28 shows how to use INSERT to add a row to the employees table. In the first INSERT statement, values are inserted into all columns in a row of the table. In the second INSERT statement, values are inserted only into the specified columns of the table and the remaining columns are set to NULL. If the those remaining columns had been specified with a NOT NULL constraint for the table, an error would occur. For information about constraints, see "Managing Tables" and "NOT NULL Constraint".

Example 3-28 Using the SQL INSERT Statement to Add Rows to a Table

-- the following inserts data for all the columns in a row
INSERT INTO employees VALUES 
  (10, 'Enrique', 'Borges', 'enrique.borges', '555.111.2222', 
   '01-AUG-05', 'AC_MGR', 9000, .1, 101, 110);

-- the following inserts data into the columns specified by name
-- NULLs are inserted in those columns not explicitly named 
INSERT INTO employees (employee_id, last_name, email, hire_date, job_id, salary)
  VALUES (11, 'Doe', 'jane.doe', '31-AUG-05', 'SH_CLERK', 2400); 

-- the following shows the rows that were inserted 
SELECT employee_id, last_name FROM employees 
  WHERE employee_id = 10 or employee_id = 11;


See Also:

Oracle Database SQL Reference for information about the INSERT statement

Updating Data With the UPDATE Statement

You can use the SQL UPDATE statement to update data in a row of a table. The updated data must be valid for the datatype and size of each column of the table.

Example 3-29 shows how to use UPDATE to update data in the employees table. Note the use of the multiplication operator * to calculate a new salary. For information about arithmetic operators, See "Using Arithmetic Operators".

Example 3-29 Using the SQL UPDATE Statement to Update Data in a Table

SELECT salary FROM employees WHERE employee_id = 11;

-- update the salary for employee 11, multiply the salary by 105%
UPDATE employees SET salary = salary * 1.05 WHERE employee_id = 11;

-- the following should show a change in salary
SELECT salary FROM employees WHERE employee_id = 11;


See Also:

Oracle Database SQL Reference for information about the UPDATE statement

Deleting Data With the DELETE Statement

With the SQL DELETE statement, you can delete all or specific rows in a table.

When you delete all the rows in a table, the empty table still exists. If you want to remove the entire table from the database, use the SQL DROP statement. See "Dropping a Table With SQL".

Example 3-30 shows how to use DELETE to delete selected rows in the employees table. Note the use of the WHERE clause. Without that clause, all the rows would be deleted.

Example 3-30 Using the SQL DELETE Statement to Remove Rows From a Table

DELETE FROM employees WHERE employee_id = 10 OR employee_id = 11;

-- the following query should not find any records
SELECT * FROM employees WHERE employee_id = 10 OR employee_id = 11;

If you accidentally delete rows, you can restore the rows with the ROLLBACK statement. See "Rolling Back a Transaction".


See Also:

Oracle Database SQL Reference for information about the DELETE statement

Using Transaction Control Statements

Transaction control statements manage the changes made by DML statements and group DML statements into transactions. They enable you to:

This section contains the following topics:

Committing Transaction Changes

The SQL COMMIT statement saves any changes made to the database. When a COMMIT has been issued, all the changes since the last COMMIT, or since you logged on as the current user, are saved.


Note:

If you are using SQL Commands, the Autocommit feature can be set to automatically commit changes after issuing SQL statements.

Example 3-31 shows how to use COMMIT to commit (save) changes to the employees table in the database.

Example 3-31 Using the SQL COMMIT Statement to Save Changes

-- add a row and then update the data
INSERT INTO employees (employee_id, last_name, email, hire_date, job_id, salary)
  VALUES (12, 'Doe', 'john.doe', '31-AUG-05', 'SH_CLERK', 2400); 

UPDATE employees SET salary = salary*1.10 WHERE employee_id = 12;

-- commit (save) the INSERT and UPDATE changes in the database
COMMIT;


See Also:

Oracle Database SQL Reference for information about the COMMIT statement

Rolling Back a Transaction

You can use the SQL ROLLBACK statement to rollback (undo) any changes you made to the database before a COMMIT was issued.

Example 3-32 shows how to use ROLLBACK to rollback the deletions made to the employees table. Note that the ROLLBACK was issued before a COMMIT was issued.


Note:

If you are using SQL Commands, disable the Autocommit feature when trying this example.

Example 3-32 Using the SQL ROLLBACK Statement to Undo Changes

-- delete a row (record)
DELETE FROM employees WHERE last_name = 'Doe';

-- rollback the delete statement because the previous DELETE was incorrect
ROLLBACK;

-- the following is valid
SELECT * FROM employees WHERE last_name = 'Doe';


See Also:

Oracle Database SQL Reference for information about the ROLLBACK statement

Using Data Definition Language Statements to Manage Database Objects

Data definition language (DDL) statements include CREATE, ALTER, and DROP to manage database objects. When managing database objects, the Object Browser page provides a Web-based user interface that can be used instead of SQL DDL statements. See "Managing Database Objects With Object Browser".

In this guide, some basic SQL DDL statements are used in the code examples and a brief description of some DDL statements are discussed in this section.

This section contains the following topics:

Creating a Table With SQL

To create a database object, such as a table, use the SQL CREATE statement as shown in Example 3-33. When you create a table, you need to provide datatypes for each column. For more information about tables, see "Managing Tables".

Example 3-33 Creating a Simple Table Using SQL

-- create a simple table for keeping track of birthdays
CREATE TABLE my_birthdays
  ( first_name     VARCHAR2(20),
    last_name      VARCHAR2(25),
    bday_date      DATE
  ); 

Optionally, you can provide NOT NULL constraints, as shown in Example 3-34. The NOT NULL constraint is discussed in "NOT NULL Constraint".

Example 3-34 Creating a Table With NOT NULL Constraints Using SQL

-- create a table with NOT NULL constraints in the HR schema
CREATE TABLE personal_info (
    employee_id         NUMBER(6,0) NOT NULL,
    birth_date          DATE NOT NULL,
    social_security_id  VARCHAR2(12) NOT NULL,
    marital_status      VARCHAR2(10),
    dependents_claimed  NUMBER(2,0) DEFAULT 1,
    contact_name        VARCHAR2(45) NOT NULL,
    contact_phone       VARCHAR2(20) NOT NULL,
    contact_address     VARCHAR2(80) NOT NULL
);

For information about creating a table with the Object Browser page, see "Creating a Table".

Adding, Altering, and Dropping a Table Column With SQL

To alter a database object, such as a table, use the SQL ALTER statement, as shown in Example 3-35.

Example 3-35 Adding, Altering, and Dropping a Table Column Using SQL

-- add a new column
ALTER TABLE personal_info ADD
(contact_email VARCHAR2(30) NULL);

-- modify a column
ALTER TABLE personal_info MODIFY
(contact_email VARCHAR2(40) NOT NULL);

-- drop a column
ALTER TABLE personal_info DROP COLUMN
contact_address;

For information about adding, modifying, and dropping a table column with the Object Browser page, see "Adding a Column To a Table", "Modifying a Column In a Table", and "Dropping a Column From a Table".

Creating and Altering a Constraint With SQL

To add, alter, or drop a constraint on a table, use the SQL ALTER statement, as shown in Example 3-36. For information about primary key, foreign key, unique, and check constraints, see "Ensuring Data Integrity in Tables With Constraints".

Example 3-36 Creating, Altering, and Dropping Constraints Using SQL

-- add a primary key constraint 
ALTER TABLE personal_info 
  ADD CONSTRAINT personal_info_pkey 
  PRIMARY KEY (employee_id);

-- add a foreign key constraint
ALTER TABLE personal_info 
  ADD CONSTRAINT personal_info_fkey 
  FOREIGN KEY (employee_id) REFERENCES employees (employee_id) 
  ON DELETE CASCADE;

-- add a unique constraint
ALTER TABLE personal_info 
  ADD CONSTRAINT personal_info_unique_con 
  UNIQUE (social_security_id);

-- add a check constraint
ALTER TABLE personal_info 
  ADD CONSTRAINT personal_info_check_con 
  CHECK ( dependents_claimed > 0);

-- disable a constraint
ALTER TABLE personal_info 
  DISABLE CONSTRAINT personal_info_check_con;

-- enable a constraint
ALTER TABLE personal_info 
  ENABLE CONSTRAINT personal_info_check_con;

-- drop a constraint
ALTER TABLE personal_info 
  DROP CONSTRAINT personal_info_check_con;

For information about adding a constraint with the Object Browser page, see "Adding a Primary Key Constraint", "Adding a Foreign Key Constraint", "Adding a Unique Constraint", and "Adding a Check Constraint".

Renaming a Table With SQL

To rename a database object, such as a table, use the SQL ALTER statement, as shown in Example 3-37.

Example 3-37 Renaming a Table Using SQL

-- rename the my_birthdays table
ALTER TABLE my_birthdays RENAME to birthdays; 

Dropping a Table With SQL

To drop (remove completely) a table from the database, use the SQL DROP statement, as shown in Example 3-38. Be careful when using the DROP statement to remove database objects.

If you want to delete the rows in the table and keep the table, use the DELETE statement. See "Deleting Data With the DELETE Statement".

Example 3-38 Dropping a Table Using SQL

-- drop tables from the database
-- use caution when use the DROP statement!
DROP TABLE birthdays;
DROP TABLE personal_info;

Creating, Altering, and Dropping an Index With SQL

To create, modify, or drop an index, use the SQL CREATE, ALTER, or DROP INDEX statement, as shown in Example 3-39. For more information about indexes, see "Managing Indexes".

Example 3-39 Creating, Modifying, and Dropping an Index Using SQL

-- create an index on a single column to make queries faster on that column
CREATE INDEX emp_hiredate_idx ON employees (hire_date);

-- rename the index
ALTER INDEX emp_hiredate_idx 
  RENAME TO emp_hire_date_idx;

-- drop the index
DROP INDEX emp_hire_date_idx;

-- create an index on two columns to make queries faster on the first column
-- or both columns
CREATE INDEX emp_mgr_id_ix ON employees (employee_id, manager_id);
DROP INDEX emp_mgr_id_ix;

-- a function-based index precalculates the result and speeds up queries that
-- use the function for searching or sorting, in this case UPPER(last_name)
CREATE INDEX emp_upper_last_name_ix ON employees (UPPER(last_name));
DROP INDEX emp_upper_last_name_ix;

For information about creating an index with the Object Browser page, see "Creating an Index".

Creating and Dropping a View With SQL

To create a database object, such as a view, use the SQL CREATE statement as shown in Example 3-40. For more information about views, see "Managing Views".

Example 3-40 Creating a View Using SQL

-- create a view to display data from departments and employees
CREATE OR REPLACE VIEW my_emp_view AS
SELECT d.department_id, d.department_name,
  e.employee_id, e.first_name, e.last_name 
  FROM employees e 
  JOIN departments d ON d.manager_id = e.employee_id;

Example 3-41 shows how to drop the view that you previously created.

Example 3-41 Dropping a View Using SQL

-- drop the view with the DROP VIEW statement
DROP VIEW my_emp_view;

For information about creating and dropping a view with the Object Browser page, see "Creating a View" and "Dropping a View". For an additional example of creating a view, see Example 6-3.

Creating and Dropping a Sequence With SQL

A sequence is a database object that generates unique sequential values, often used for primary and unique keys. You can refer to sequence values in SQL statements with the CURRVAL and NEXTVAL pseudocolumns.

To generate a sequence number, you call the sequence using the CURRVAL or NEXTVAL keywords. You must qualify CURRVAL and NEXTVAL with the name of the sequence, such as employees_seq.CURRVAL or employees_seq.NEXTVAL. Before you use CURRVAL for a sequence in your session, you must first initialize the sequence with NEXTVAL.

Example 3-42 shows how to create a sequence that can be used with the employees table. The sequence can also be used with other tables. For more information about sequences, see "Managing Sequences".

Example 3-42 Creating a Sequence Using SQL

-- create a new sequence to use with the employees table
-- this sequence starts at 1000 and increments by 1
CREATE SEQUENCE new_employees_seq START WITH 1000 INCREMENT BY 1;

-- to use the sequence, first initialize the sequence with NEXTVAL
SELECT new_employees_seq.NEXTVAL FROM DUAL;

-- after initializing the sequence, use CURRVAL as the next value in the sequence
INSERT INTO employees VALUES 
  (new_employees_seq.CURRVAL, 'Pilar', 'Valdivia', 'pilar.valdivia',
  '555.111.3333', '01-SEP-05', 'AC_MGR', 9100, .1, 101, 110);

-- query the employees table to check the current value of the sequence
-- which was inserted used as employee_id in the previous INSERT statement
SELECT employee_id, last_name FROM employees WHERE last_name = 'Valdivia';

Example 3-43 shows how to drop the sequence that you previously created.

Example 3-43 Dropping a Sequence Using SQL

-- drop the sequence
DROP SEQUENCE new_employees_seq;

For information about creating and dropping a sequence with the Object Browser page, see "Creating a Sequence" and "Dropping a Sequence".

Creating and Dropping a Synonym With SQL

Example 3-44 shows how to create a synonym that is an alias for the employees table. For more information about synonyms, see "Managing Synonyms".

Example 3-44 Creating a Synonym Using SQL

-- create a synonym for the employees table
CREATE SYNONYM emps for HR.employees;

-- query the employees table using the emps synonym
SELECT employee_id, last_name FROM emps WHERE employee_id < 105;

Example 3-45 show how to drop a synonym.

Example 3-45 Dropping a Synonym Using SQL

-- drop the synonym
DROP SYNONYM emps;

For information about creating and dropping a synonym with the Object Browser page, see "Creating a Synonym" and "Dropping a Synonym".