Oracle Database 10g: SQL Fundamentals I Electronic Presentation D17108GC11 Production 1.1 August 2004 D39769
Author Nancy Greenberg Technical Contributors and Reviewers Wayne Abbott Christian Bauwens Perry Benson Brian Boxx Zarko Cesljas Dairy Chan Laszlo Czinkoczki Marjolein Dekkers Matthew Gregory Stefan Grenstad Joel Goodman Rosita Hanoman Sushma Jagannath Angelika Krupp Christopher Lawless Marcelo Manzano Isabelle Marchand Malika Marghadi Valli Pataballa Elspeth Payne Ligia Jasmin Robayo Bryan Roberts Helen Robertson Lata Shivaprasad John Soltani Priya Vennapusa Ken Woolfe This documentation contains proprietary information of Oracle Corporation. It is provided under a license agreement containing restrictions on use and disclosure and is also protected by copyright law. Reverse engineering of the software is prohibited. If this documentation is delivered to a U.S. Government Agency of the Department of Defense, then it is delivered with Restricted Rights and the following legend is applicable: Restricted Rights Legend Use, duplication or disclosure by the Government is subject to restrictions for commercial computer software and shall be deemed to be Restricted Rights software under Federal law, as set forth in subparagraph (c)(1)(ii) of DFARS 252.227-7013, Rights in Technical Data and Computer Software (October 1988). This material or any portion of it may not be copied in any form or by any means without the express prior written permission of Oracle Corporation. Any other copying is a violation of copyright law and may result in civil and/or criminal penalties. If this documentation is delivered to a U.S. Government Agency not within the Department of Defense, then it is delivered with Restricted Rights, as defined in FAR 52.227-14, Rights in Data- General, including Alternate III (June 1987). The information in this document is subject to change without notice. If you find any problems in the documentation, please report them in writing to Education Products, Oracle Corporation, 500 Oracle Parkway, Box SB-6, Redwood Shores, CA 94065. Oracle Corporation does not warrant that this document is error-free. Oracle and all references to Oracle products are trademarks or registered trademarks of Oracle Corporation. All other products or company names are used for identification purposes only, and may be trademarks of their respective owners. Publisher Jobi Varghese
Introduction
Lesson Objectives After completing this lesson, you should be able to do the following: List the features of Oracle10g Discuss the theoretical and physical aspects of a relational database Describe the Oracle implementation of the RDBMS and ORDBMS Understand the goals of the course
Goals of the Course After completing this course, you should be able to do the following: Identify the major structural components of Oracle Database 10g Retrieve row and column data from tables with the SELECT statement Create reports of sorted and restricted data Employ SQL functions to generate and retrieve customized data Run data manipulation language (DML) statements to update data in Oracle Database 10g Obtain metadata by querying the dictionary views
Oracle10g Scalability One vendor Reliability Unified management Single development model Common skill sets
Oracle10g
Oracle Database 10g Object relational data Documents Multimedia Messages
Oracle Application Server 10g Portals Transactional applications Business intelligence Integration Application development framework Application server
Oracle Enterprise Manager 10g Grid Control Software provisioning Application service level monitoring
Relational and Object Relational Database Management Systems Relational model and object relational model User-defined data types and objects Fully compatible with relational database Support of multimedia and large objects High-quality database server features
Oracle Internet Platform Clients Any browser Any mail client Any FTP client System management Internet applications Business logic and data Databases Presentation and business logic Application servers Development tools SQL PL/SQL Java Network services
System Development Life Cycle Strategy and analysis Design Build and document Transition Production
Data Storage on Different Media Electronic spreadsheet Filing cabinet Database
Relational Database Concept Dr. E. F. Codd proposed the relational model for database systems in 1970. It is the basis for the relational database management system (RDBMS). The relational model consists of the following: Collection of objects or relations Set of operators to act on the relations Data integrity for accuracy and consistency
Definition of a Relational Database A relational database is a collection of relations or two-dimensional tables. Oracle server Table name: EMPLOYEES Table name: DEPARTMENTS
Data Models Model of system in client s mind Entity model of client s model Table model of entity model Oracle server Tables on disk
Entity Relationship Model Create an entity relationship diagram from business specifications or narratives: EMPLOYEE #* number * name o job title assigned to composed of DEPARTMENT #* number * name o location Scenario... Assign one or more employees to a department...... Some departments do not yet have assigned employees...
Entity Relationship Modeling Conventions Entity Singular, unique name Uppercase Soft box Synonym in parentheses Attribute Singular name Lowercase Mandatory marked with * Optional marked with o EMPLOYEE #* number * name o job title assigned to composed of DEPARTMENT #* number * name o location Unique identifier (UID) Primary marked with # Secondary marked with (#)
Relating Multiple Tables Each row of data in a table is uniquely identified by a primary key (PK). You can logically relate data from multiple tables using foreign keys (FK). Table name: EMPLOYEES Table name: DEPARTMENTS Primary key Foreign key Primary key
Relational Database Terminology 2 3 4 5 6 1
Relational Database Properties A relational database: Can be accessed and modified by executing structured query language (SQL) statements Contains a collection of tables with no physical pointers Uses a set of operators
Communicating with an RDBMS Using SQL SQL statement is entered. SELECT department_name FROM departments; Statement is sent to Oracle server. Oracle server
Oracle s Relational Database Management System Oracle server User tables Data dictionary
SQL Statements SELECT INSERT UPDATE DELETE MERGE CREATE ALTER DROP RENAME TRUNCATE COMMENT GRANT REVOKE COMMIT ROLLBACK SAVEPOINT Data manipulation language (DML) Data definition language (DDL) Data control language (DCL) Transaction control
Tables Used in the Course EMPLOYEES DEPARTMENTS JOB_GRADES
Summary Oracle Database 10g is the database for grid computing. The database is based on the object relational database management system. Relational databases are composed of relations, managed by relational operations, and governed by data integrity constraints. With the Oracle server, you can store and manage information by using the SQL language and PL/SQL engine.
Retrieving Data Using the SQL SELECT Statement
Objectives After completing this lesson, you should be able to do the following: List the capabilities of SQL SELECT statements Execute a basic SELECT statement Differentiate between SQL statements and isql*plus commands
Capabilities of SQL SELECT Statements Projection Selection Table 1 Table 1 Join Table 1 Table 2
Basic SELECT Statement SELECT * {[DISTINCT] column expression [alias],...} FROM table; SELECT identifies the columns to be displayed FROM identifies the table containing those columns
Selecting All Columns SELECT * FROM departments;
Selecting Specific Columns SELECT department_id, location_id FROM departments;
Writing SQL Statements SQL statements are not case-sensitive. SQL statements can be on one or more lines. Keywords cannot be abbreviated or split across lines. Clauses are usually placed on separate lines. Indents are used to enhance readability. In isql*plus, SQL statements can optionally be terminated by a semicolon (;). Semicolons are required if you execute multiple SQL statements. In SQL*plus, you are required to end each SQL statement with a semicolon (;).
Column Heading Defaults isql*plus: Default heading alignment: Center Default heading display: Uppercase SQL*Plus: Character and Date column headings are leftaligned Number column headings are right-aligned Default heading display: Uppercase
Arithmetic Expressions Create expressions with number and date data by using arithmetic operators. Operator + - * / Description Add Subtract Multiply Divide
Using Arithmetic Operators SELECT last_name, salary, salary + 300 FROM employees;
Operator Precedence SELECT last_name, salary, 12*salary+100 FROM employees; 1 SELECT last_name, salary, 12*(salary+100) FROM employees; 2
Defining a Null Value A null is a value that is unavailable, unassigned, unknown, or inapplicable. A null is not the same as a zero or a blank space. SELECT last_name, job_id, salary, commission_pct FROM employees;
Null Values in Arithmetic Expressions Arithmetic expressions containing a null value evaluate to null. SELECT last_name, 12*salary*commission_pct FROM employees;
Defining a Column Alias A column alias: Renames a column heading Is useful with calculations Immediately follows the column name (There can also be the optional AS keyword between the column name and alias.) Requires double quotation marks if it contains spaces or special characters or if it is casesensitive
Using Column Aliases SELECT last_name AS name, commission_pct comm FROM employees; SELECT last_name "Name", salary*12 "Annual Salary" FROM employees;
Concatenation Operator A concatenation operator: Links columns or character strings to other columns Is represented by two vertical bars ( ) Creates a resultant column that is a character expression SELECT FROM last_name job_id AS "Employees" employees;
Literal Character Strings A literal is a character, a number, or a date that is included in the SELECT statement. Date and character literal values must be enclosed by single quotation marks. Each character string is output once for each row returned.
Using Literal Character Strings SELECT last_name ' is a ' job_id AS "Employee Details" FROM employees;
Alternative Quote (q) Operator Specify your own quotation mark delimiter Choose any delimiter Increase readability and usability SELECT department_name q'[, it's assigned Manager Id: ]' manager_id AS "Department and Manager" FROM departments;
Duplicate Rows The default display of queries is all rows, including duplicate rows. SELECT department_id FROM employees; 1 SELECT DISTINCT department_id FROM employees; 2
SQL and isql*plus Interaction Internet browser SQL statements Oracle server Client isql*plus commands Formatted report Query results
SQL Statements Versus isql*plus Commands SQL A language ANSI standard Keyword cannot be abbreviated Statements manipulate data and table definitions in the database SQL statements isql*plus An environment Oracle-proprietary Keywords can be abbreviated Commands do not allow manipulation of values in the database Runs on a browser Centrally loaded; does not have to be implemented on each machine isql*plus commands
Overview of isql*plus After you log in to isql*plus, you can: Describe table structures Enter, execute, and edit SQL statements Save or append SQL statements to files Execute or edit statements that are stored in saved script files
Logging In to isql*plus From your browser environment:
isql*plus Environment 8 9 7 1 6 2 3 4 5
Displaying Table Structure Use the isql*plus DESCRIBE command to display the structure of a table: DESC[RIBE] tablename
Displaying Table Structure DESCRIBE employees
Interacting with Script Files SELECT last_name, hire_date, salary FROM employees; 1 2
Interacting with Script Files
Interacting with Script Files 1
Interacting with Script Files D:\TEMP\emp_data.sql 2 3
isql*plus History Page 3 2 1
isql*plus History Page 3 4
Setting isql*plus Preferences 1 2 3
Setting the Output Location Preference 2 1
Summary In this lesson, you should have learned how to: Write a SELECT statement that: Returns all rows and columns from a table Returns specified columns from a table Uses column aliases to display more descriptive column headings Use the isql*plus environment to write, save, and execute SQL statements and isql*plus commands SELECT * {[DISTINCT] column expression [alias],...} FROM table;
Practice 1: Overview This practice covers the following topics: Selecting all data from different tables Describing the structure of tables Performing arithmetic calculations and specifying column names Using isql*plus
Restricting and Sorting Data
Objectives After completing this lesson, you should be able to do the following: Limit the rows that are retrieved by a query Sort the rows that are retrieved by a query Use ampersand substitution in isql*plus to restrict and sort output at run time
Limiting Rows Using a Selection EMPLOYEES retrieve all employees in department 90
Limiting the Rows That Are Selected Restrict the rows that are returned by using the WHERE clause: SELECT * {[DISTINCT] column expression [alias],...} FROM table [WHERE condition(s)]; The WHERE clause follows the FROM clause.
Using the WHERE Clause SELECT employee_id, last_name, job_id, department_id FROM employees WHERE department_id = 90 ;
Character Strings and Dates Character strings and date values are enclosed by single quotation marks. Character values are case-sensitive, and date values are format-sensitive. The default date format is DD-MON-RR. SELECT last_name, job_id, department_id FROM employees WHERE last_name = 'Whalen' ;
Comparison Conditions Operator <> BETWEEN...AND... IN(set) LIKE = > >= < <= IS NULL Meaning Equal to Greater than Greater than or equal to Less than Less than or equal to Not equal to Between two values (inclusive) Match any of a list of values Match a character pattern Is a null value
Using Comparison Conditions SELECT last_name, salary FROM employees WHERE salary <= 3000 ;
Using the BETWEEN Condition Use the BETWEEN condition to display rows based on a range of values: SELECT last_name, salary FROM employees WHERE salary BETWEEN 2500 AND 3500 ; Lower limit Upper limit
Using the IN Condition Use the IN membership condition to test for values in a list: SELECT employee_id, last_name, salary, manager_id FROM employees WHERE manager_id IN (100, 101, 201) ;
Using the LIKE Condition Use the LIKE condition to perform wildcard searches of valid search string values. Search conditions can contain either literal characters or numbers: % denotes zero or many characters. _ denotes one character. SELECT first_name FROM employees WHERE first_name LIKE 'S%' ;
Using the LIKE Condition You can combine pattern-matching characters: SELECT last_name FROM employees WHERE last_name LIKE '_o%' ; You can use the ESCAPE identifier to search for the actual % and _ symbols.
Using the NULL Conditions Test for nulls with the IS NULL operator. SELECT last_name, manager_id FROM employees WHERE manager_id IS NULL ;
Logical Conditions Operator AND OR NOT Meaning Returns TRUE if both component conditions are true Returns TRUE if either component condition is true Returns TRUE if the following condition is false
Using the AND Operator AND requires both conditions to be true: SELECT employee_id, last_name, job_id, salary FROM employees WHERE salary >=10000 AND job_id LIKE '%MAN%' ;
Using the OR Operator OR requires either condition to be true: SELECT employee_id, last_name, job_id, salary FROM employees WHERE salary >= 10000 OR job_id LIKE '%MAN%' ;
Using the NOT Operator SELECT last_name, job_id FROM employees WHERE job_id NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP') ;
Rules of Precedence Operator 1 2 3 4 5 6 7 8 9 Meaning Arithmetic operators Concatenation operator Comparison conditions IS [NOT] NULL, LIKE, [NOT] IN [NOT] BETWEEN Not equal to NOT logical condition AND logical condition OR logical condition You can use parentheses to override rules of precedence.
Rules of Precedence SELECT last_name, job_id, salary FROM employees WHERE job_id = 'SA_REP' OR job_id = 'AD_PRES' AND salary > 15000; 1 SELECT last_name, job_id, salary FROM employees WHERE (job_id = 'SA_REP' OR job_id = 'AD_PRES') AND salary > 15000; 2
Using the ORDER BY Clause Sort retrieved rows with the ORDER BY clause: ASC: ascending order, default DESC: descending order The ORDER BY clause comes last in the SELECT statement: SELECT last_name, job_id, department_id, hire_date FROM employees ORDER BY hire_date ;
Sorting Sorting in descending order: SELECT last_name, job_id, department_id, hire_date FROM employees ORDER BY hire_date DESC ; 1 Sorting by column alias: SELECT employee_id, last_name, salary*12 annsal FROM employees ORDER BY annsal ; 2 Sorting by multiple columns: SELECT last_name, department_id, salary FROM employees ORDER BY department_id, salary DESC; 3
Substitution Variables... salary =? department_id =?... last_name =?... I want to query different values.
Substitution Variables Use isql*plus substitution variables to: Temporarily store values with single-ampersand (&) and double-ampersand (&&) substitution Use substitution variables to supplement the following: WHERE conditions ORDER BY clauses Column expressions Table names Entire SELECT statements
Using the & Substitution Variable Use a variable prefixed with an ampersand (&) to prompt the user for a value: SELECT employee_id, last_name, salary, department_id FROM employees WHERE employee_id = &employee_num ;
Using the & Substitution Variable 101 1 2
Character and Date Values with Substitution Variables Use single quotation marks for date and character values: SELECT last_name, department_id, salary*12 FROM employees WHERE job_id = '&job_title' ;
Specifying Column Names, Expressions, and Text SELECT employee_id, last_name, job_id,&column_name FROM employees WHERE &condition ORDER BY &order_column ; salary salary > 15000 last_name
Using the && Substitution Variable Use the double ampersand (&&) if you want to reuse the variable value without prompting the user each time: SELECT employee_id, last_name, job_id, &&column_name FROM employees ORDER BY &column_name ;
Using the isql*plus DEFINE Command Use the isql*plus DEFINE command to create and assign a value to a variable. Use the isql*plus UNDEFINE command to remove a variable. DEFINE employee_num = 200 SELECT employee_id, last_name, salary, department_id FROM employees WHERE employee_id = &employee_num ; UNDEFINE employee_num
Using the VERIFY Command Use the VERIFY command to toggle the display of the substitution variable, both before and after isql*plus replaces substitution variables with values: SET VERIFY ON SELECT employee_id, last_name, salary, department_id FROM employees WHERE employee_id = &employee_num; old 3: WHERE employee_id = &employee_num new 3: WHERE employee_id = 200
Summary In this lesson, you should have learned how to: Use the WHERE clause to restrict rows of output: Use the comparison conditions Use the BETWEEN, IN, LIKE, and NULL conditions Apply the logical AND, OR, and NOT operators Use the ORDER BY clause to sort rows of output: SELECT * {[DISTINCT] column expression [alias],...} FROM table [WHERE condition(s)] [ORDER BY {column, expr, alias} [ASC DESC]] ; Use ampersand substitution in isql*plus to restrict and sort output at run time
Practice 2: Overview This practice covers the following topics: Selecting data and changing the order of the rows that are displayed Restricting rows by using the WHERE clause Sorting rows by using the ORDER BY clause Using substitution variables to add flexibility to your SQL SELECT statements