Guide to Oracle 10g1 Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data.

Slides:



Advertisements
Similar presentations
Advanced SQL Topics Edward Wu.
Advertisements

© Abdou Illia MIS Spring 2014
TURKISH STATISTICAL INSTITUTE 1 /34 SQL FUNDEMANTALS (Muscat, Oman)
Introduction to Structured Query Language (SQL)
XP Chapter 3 Succeeding in Business with Microsoft Office Access 2003: A Problem-Solving Approach 1 Analyzing Data For Effective Decision Making.
Introduction to Structured Query Language (SQL)
A Guide to Oracle9i1 Using SQL Queries to Insert, Update, Delete, and View Data Chapter 3.
1 Chapter 3: Using Oracle to Add, View, and Update Data.
Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data
A Guide to Oracle9i1 Advanced SQL And PL/SQL Topics Chapter 9.
Introduction to Structured Query Language (SQL)
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
1 Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data.
Using SQL Queries to Insert, Update, Delete, and View Data © Abdou Illia MIS Spring 2015 Wednesday 1/28/2015 Chapter 3A.
Microsoft Access 2010 Chapter 7 Using SQL.
Guide to Oracle10G1 Using SQL Queries to Insert, Update, Delete, and View Data Chapter 3.
ASP.NET Programming with C# and SQL Server First Edition
Using SQL Queries to Insert, Update, Delete, and View Data Date Retrieval from a single table & Calculations © Abdou Illia MIS Spring 2015.
Relational DBs and SQL Designing Your Web Database (Ch. 8) → Creating and Working with a MySQL Database (Ch. 9, 10) 1.
Chapter 3 Single-Table Queries
Chapter 6 Additional Database Objects
Analyzing Data For Effective Decision Making Chapter 3.
Chapter 10 Selected Single-Row Functions Oracle 10g: SQL.
ITBIS373 Database Development
About the Presentations The presentations cover the objectives found in the opening of each chapter. All chapter objectives are listed in the beginning.
Chapter 6 Additional Database Objects Oracle 10g: SQL.
SQL: Data Manipulation Presented by Mary Choi For CS157B Dr. Sin Min Lee.
SQL SQL Server : Overview SQL : Overview Types of SQL Database : Creation Tables : Creation & Manipulation Data : Creation & Manipulation Data : Retrieving.
Concepts of Database Management Seventh Edition
1 Creating and Modifying Database Objects. 2 An Oracle database consists of multiple user accounts Each user account owns database objects Tables Views.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
ADVANCED SQL SELECT QUERIES CS 260 Database Systems.
Database Programming Sections 11 & 12 – Creating, and Managing Views, Sequences, Indexes, and Synonymns.
Oracle 11g: SQL Chapter 10 Selected Single-Row Functions.
SQL SELECT QUERIES CS 260 Database Systems. Overview  Introduction to SQL  Single-table select queries  Using the DBMS to manipulate data output 
Oracle 11g DATABASE DEVELOPMENT LAB1. Introduction  Oracle 11g Database:-  Oracle 11g database is designed for some features, which helps to the organizations.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
BIS Database Systems School of Management, Business Information Systems, Assumption University A.Thanop Somprasong Chapter # 7 Introduction to Structured.
ITBIS373 Database Development Lecture 3a - Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data.
Chapter 3 Selected Single-Row Functions and Advanced DML & DDL.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.
Database Lab Lecture 1. Database Languages Data definition language ( DDL ) Data definition language –defines data types and the relationships among them.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
Database Programming Sections 11 & 12 –Sequences, Indexes, and Synonymns.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
Chapter 9: Advanced SQL and PL/SQL Guide to Oracle 10g.
Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join.
1 Creating and Maintaining Database Objects Part 1 Database Systems.
Enhanced Guide to Oracle 10g Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data.
1 Chapter 2: Creating and Modifying Database Objects.
Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
Lecture3b - Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data Guide to Oracle 10g ITBIS373 Database Development.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
 CONACT UC:  Magnific training   
Database Design lecture 3_2 Slide 1 Database Design Lecture 3_2 Data Manipulation in SQL Simple SQL queries References: Text Chapter 8 Oracle SQL Manual.
Oracle 11g: SQL Chapter 5 Data Manipulation and Transaction Control.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
SQL Query Getting to the data ……..
Relational Database Design
Chapter 10 Selected Single-Row Functions Oracle 10g: SQL
Client/Server Databases and the Oracle 10g Relational Database
Basic Nested Queries and Views
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
Creating and Maintaining
Index Note: A bolded number or letter refers to an entire lesson or appendix. A Adding Data Through a View ADD_MONTHS Function 03-22, 03-23,
Contents Preface I Introduction Lesson Objectives I-2
Chapter 8 Advanced SQL.
Presentation transcript:

Guide to Oracle 10g1 Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data

Guide to Oracle 10g2  Queries are the DML commands that allow users to retrieve database data, because the retrieved data are answers to questions.  Action queries are the DML commands that insert, update, or delete database data, because the commands perform an action that change the data value. Queries and action queries

Guide to Oracle 10g3  Script: text file that contains a sequence of SQL commands. Usually have.sql extension  Running a script: SQL> START path_to_script_file; OR path_to_script_file;  Path cannot contain any blank spaces SQL Scripts

Guide to Oracle 10g4  Syntax: INSERT INTO tablename VALUES (column1_value, column2_value, …);  You must insert a value or a NULL placeholder for every field.  Fields must be entered in the order they appear in the table when you issue the DESCRIBE command. Inserting a Value Into Every Field in a Record

Guide to Oracle 10g5 Inserting a Value Into Every Field in a Record Example:

Guide to Oracle 10g6  Command to insert values for selected record fields: INSERT INTO tablename (column1_name, column2_name, …) VALUES (column1_value, column2_value, …); Inserting Selected Table Fields

Guide to Oracle 10g7  Example: Inserting Selected Table Fields

Guide to Oracle 10g8 Format Models (Masks) All data is stored in the database in a standard binary format Format masks are alphanumeric text strings that specify the format of input and output data Table 3-1: Number format masks Table 3-2: Date format masks

Guide to Oracle 10g9  Date values must be converted from characters to dates using the TO_DATE function and a format mask  Example: Inserting Date Values

Guide to Oracle 10g10  Must be enclosed in single quotes  Is case-sensitive  To insert a string with a single quote, type the single quote twice  Example: 'Mike''s Motorcycle Shop' Inserting Text Data

Guide to Oracle 10g11  Year To Month Interval: TO_YMINTERVAL(‘years-months’) e.g. TO_YMINTERVAL(‘3-2’)  Day To Second Interval: TO_DSINTERVAL(‘days HH:MI:SS.99’) e.g. TO_DSINTERVAL(‘-0 01:15:00’) Inserting Interval Values

Guide to Oracle 10g12  Oracle stores LOB data in a separate physical location from other types of data in a row.  Before inserting data in a LOB column, a locator must be inserted first.  A locator is a structure that contains information that identifies the LOB data type and points to the alternate memory location.  After that a program or a utility is needed to insert the data into the DB (chapter 10).  Ex. To create a locator for a BLOB data:  EMPTY_BLOB();  Another example page 96. Inserting LOB Column Locators

Guide to Oracle 10g13  Transaction  Logical unit of work consisting of one or more SQL DML commands  INSERT, UPDATE, DELETE  All transaction commands must succeed or none can succeed  Transaction results are not visible to other users until they are “committed” to the database (this is not the case with DDL commands)  Until a transaction is committed, it can easily be “rolled back” (undone) Transactions

Guide to Oracle 10g14  A transaction starts when you type one or more DML commands in SQL*Plus  A transaction ends when you issue either the COMMIT or ROLLBACK command SQL>COMMIT; SQL>ROLLBACK; Transactions

Guide to Oracle 10g15 Committing and Rolling Back Data COMMIT Makes transaction command changes permanent in the database and visible to other users ROLLBACK Rolls back transaction command changes and restores database to its state before the transaction

Guide to Oracle 10g16  Used to mark individual sections of a transaction  You can roll back a transaction to a savepoint Savepoints

Guide to Oracle 10g17  Format: WHERE fieldname operator expression  Operators  Equal (=)  Greater than, Less than (>, <)  Greater than or Equal to (>=)  Less than or Equal to (<=)  Not equal (, !=, ^=)  LIKE  BETWEEN  IN  NOT IN Search Conditions

Guide to Oracle 10g18 WHERE s_name = ‘Sarah’ WHERE s_age > 18 WHERE s_class <> ‘SR’  Text in single quotes is case sensitive Search Condition Examples

Guide to Oracle 10g19  Syntax: UPDATE tablename SET column1 = new_value, column2 = new_value, … WHERE search_condition;  Each update statement can update row(s) in one table only  Can update multiple records if they all match the search condition Updating Records

Guide to Oracle 10g20  Syntax: DELETE FROM tablename WHERE search_condition;  Deletes multiple records if search condition specifies multiple records  If search condition is omitted, all table records are deleted  You can’t delete a record if it contains a primary key value that is referenced as a foreign key Deleting Records

Guide to Oracle 10g21 Truncating Tables Removes ALL table data WITHOUT saving any rollback information (DELETE needs to save a copy of all the deleted records for a rollback possibility) Advantage: fast way to delete table data Disadvantage: can’t be undone (rollback) Syntax: TRUNCATE TABLE tablename;

Guide to Oracle 10g22 Truncating Tables You can not truncate a table that has an enabled foreign key constrain. So you need to disable the constraint first: Syntax: TRUNCATE TABLE tablename DISABLE CONSTRAINT constraint_name;

Guide to Oracle 10g23  Sequential list of numbers that is automatically generated by the database  Used to generate unique values for surrogate keys Sequences

Guide to Oracle 10g24  Syntax: CREATE SEQUENCE sequence_name [optional parameters];  Example: CREATE SEQUENCE f_id_sequence START WITH 200; Creating Sequences

Guide to Oracle 10g25 Viewing Sequence Information Query the SEQUENCE Data Dictionary View: (user_sequences) see table 2.3 p.69

Guide to Oracle 10g26 Pseudocolumns To use sequences, psedocolumns should be understood first. Psedocolumns acts like a column in a database table, but it is actually a command that returns a specific value. Used to retrieve: Current system date Name of the current database user Next or Current values of a sequence

Guide to Oracle 10g27 Pseudocolumn Examples Pseudocolumn Name Output CURRVALMost recently retrieved sequence value NEXTVALNext value in a sequence SYSDATECurrent system date from database server USERUsername of current user

Guide to Oracle 10g28  Retrieving the current system date : SELECT SYSDATE FROM DUAL; Retrieving the name of the current user: SELECT USER FROM DUAL;  DUAL is a system table that is used with pseudocolumns. It contains one column. Its value can not be deleted or modified. ( P.110 ) Using Pseudocolumns

Guide to Oracle 10g29  Accessing the next value in a sequence: sequence_name.NEXTVAL (Can you know the retrieved value before using it?) see next slide.  Inserting a new record using a sequence: INSERT INTO my_faculty VALUES (f_id_sequence.nextval, ‘Professor Jones’); Using Pseudocolumns With Sequences

Guide to Oracle 10g30  The following command shows the NEXT value of the sequence:  SELECT sequence_name.NEXTVAL FROM DUAL;  The following command shows the current value of the sequence:  SELECT sequence_name.CURRVAL FROM DUAL;  See example page 111.  Accessing CURRVAL without NEXTVAL in advance cause an error. See example page 112. Seeing value of sequences

Guide to Oracle 10g31  The following DDL command drops sequences from a DB:  DROP SEQUENCE sequence_name;  No need for commit with DDL commands. Deleting Sequencing

Guide to Oracle 10g32 Permissions that you can grant to other users to allow them to access or modify your database objects Object Privileges Object TypePrivilegeDescription Table, Sequence ALTERAllows user to change object’s structure using the ALTER command Table, Sequence DROPAllows user to drop object Table, Sequence SELECTAllows user to view object TableINSERT, UPDATE, DELETE Allows user to insert, update, delete table data Any database object ALLAllows user to perform any operation on object

Guide to Oracle 10g33 Syntax Granting object privileges: GRANT privilege1, privilege2, … ON object_name TO user1, user 2, …; Revoking (cancel) object privileges: REVOKE privilege1, privilege2, … ON object_name FROM user1, user 2, …;

Guide to Oracle 10g34 Granting and Revoking Object Privileges

Guide to Oracle 10g35  Syntax: SELECT column1, column2, … FROM tablename WHERE search_condition; Retrieving Data From a Single Table

Guide to Oracle 10g36  To retrieve every column in a table: SELECT * FROM …  To retrieve every record in a table, omit the search condition SELECT column1, column2, … FROM tablename; Retrieving Data From a Single Table

Guide to Oracle 10g37 Qualifying Table Names If you retrieve data from a table that is owned by another user, you must qualify the table name by prefacing it with the owner’s name. ( we will study it again when joining multiple tables P.159 )

Guide to Oracle 10g38  Sometimes queries retrieve duplicate records  To suppress duplicate outputs, use the DISTINCT qualifier : SELECT DISTINCT column1, column2, … FROM... Suppressing Duplicate Records

Guide to Oracle 10g39  Use the search condition (where) to retrieve rows matching specific criteria.  Combining search conditions  AND: both conditions must be true  OR: either condition can be true  Combining AND and OR in a single operation  AND comparisons are evaluated first  Always use parentheses to force conditions to be evaluated in the correct order Using Multiple Search Conditions

Guide to Oracle 10g40 SQL> SELECT room 2.FROM location 3.WHERE bldg_code = ‘BUS’ 4.AND capacity >= 40; Example

Guide to Oracle 10g41  NULL: not defined  Use IS NULL search condition SELECT s_name, s_class FROM my_students WHERE s_class IS NULL; Searching for NULL Records

Guide to Oracle 10g42  Use IS NOT NULL operator SELECT s_name, s_age FROM my_students WHERE s_class IS NOT NULL; Searching for NOT NULL Records

Guide to Oracle 10g43 Using the IN and NOT IN Operators IN retrieves all values where the search column value matches a set of values SELECT * FROM enrollment WHERE grade IN (‘A’, ‘B’); Either A or B.

Guide to Oracle 10g44 Using the IN and NOT IN Operators NOT IN retrieves all values where the search column value matches a set of values SELECT * FROM enrollment WHERE grade NOT IN (‘A’, ‘B’); Neither A or B.

Guide to Oracle 10g45 Using the LIKE Operator Performs inexact searches by matching part of a character string WHERE fieldname LIKE character_string;

Guide to Oracle 10g46 Using the LIKE Operator Character string must be in single quotes and use wildcard characters (%) represents multiple wildcard characters ‘%2006’ Exact search of a string its right characters same as ‘2006’, it ignores anything on the left (no matter how many characters are there). ‘FALL%’ all rows in which the first 4 characters are FALL. (_) Underscore represents a single wildcard character ‘_R’ retrieve all values its first character can be any value, but the second must be ‘R’. Wildcard characters can be placed at beginning or end of string

Guide to Oracle 10g47 Examples Using the LIKE Operator SELECT * from term WHERE term_desc LIKE ‘Fall%’; SELECT course_no FROM course WHERE course_no LIKE ‘%1__’; Two underscores

Guide to Oracle 10g48  Use the ORDER BY clause  Specify sort key, which is the column used as a basis for ordering the output data SELECT s_name, s_age FROM my_students ORDER BY s_age; Sorting Query Output

Guide to Oracle 10g49  Default sort order  Numerical: ascending  Character: A - Z  Date: oldest - newest  To force the sort order: use ASC or DESC  Example SELECT s_name, s_age FROM my_students ORDER BY s_age DESC;  You can specify multiple sort keys. Example P Sorting Query Data

Guide to Oracle 10g50  Calculation using SQL directly is efficient, because the result is returned to the client calculated.  Arithmetic operations on retrieved data  Addition (+)  Subtraction (-)  Multiplication (*)  Division (/)  Calculations are performed on NUMBER, DATE, and INTERVAL data types. Using Calculations in Queries

Guide to Oracle 10g51  SELECT inv_id, inv_qoh * inv_price FROM inventory;  Date calculations involve the current date.  To retrieve the current date from the server use:  SELECT SYSDATE FROM DUAL;  And then use it in equations:  SYSDATE – o_date Example Calculations in Queries

Guide to Oracle 10g52  Remember that time_enrolled is an INTERVAL data type in STUDENT table.  SELECT s_id, s_last, SYSDATE – time_enrolled FROM student;  Remember to use SELECT SYSDATE FROM DUAL first. Example Calculations in Queries

Guide to Oracle 10g53  Called so, because they return a single result for each row of data retrieved.  ABS - absolute value  CEIL – rounds a number up to the next integer  FLOOR – rounds a number down to the previous integer  MOD – returns the remainder of a number and a divisor  POWER - raises a number to an exponent  ROUND - rounds a number  SQRT – returns the square root of a value  TRUNC - truncates a number to the nearest whole number  Table 3-7 P Single-Row Number Functions

Guide to Oracle 10g54  Example: SELECT s_name, TRUNC((SYSDATE - s_dob)/365) FROM my_students; Using Single-Row Number Functions

Guide to Oracle 10g55  CONCAT – joins 2 character strings  INITCAP – returns a string with the initial letter only uppercase  LENGTH – returns the length of a string  LPAD, RPAD – returns a string with a specific number of characters added on the left or right side  LTRIM, RTRIM – returns a string with all instances of a specific character trimmed from the left or right side  REPLACE – replaces all instances of a character with another character  UPPER/LOWER – returns a string in all upper/lower case letters  Table 3-8 P. 139 Single-Row Character Functions

Guide to Oracle 10g56  Example: SELECT UPPER(s_name) FROM my_students; Using Single-Row Character Functions

Guide to Oracle 10g57  To find a date that is a specific number of days before or after a known date, add or subtract the number from the known date  Example: SELECT order_date + 30 FROM cust_order; Date Arithmetic

Guide to Oracle 10g58  To find the number of days between two known dates, subtract the later date from the earlier date  Example: SELECT SYSDATE – s_dob FROM my_students; Date Arithmetic

Guide to Oracle 10g59  ADD_MONTHS  returns a date that is a specific number of months after a given date  Example: SELECT ADD_MONTHS(SYSDATE, 6) FROM dual; Single-row Date Functions

Guide to Oracle 10g60  LAST_DATE  Returns the date that is the last day of the month specified in the current date  Example: SELECT LAST_DATE(order_date) FROM cust_order WHERE order_id = 1057; Date Functions

Guide to Oracle 10g61  MONTHS_BETWEEN  Returns the number of months between two input dates  Example: SELECT MONTHS_BETWEEN(order_date, SYSDATE) FROM cust_order WHERE order_id = 1057; Date Functions

Guide to Oracle 10g62  Used to perform an operation on a field from a group of retrieved records  AVG (average of all retrieved values)  COUNT (number of records retrieved)  MAX (maximum value retrieved)  MIN (minimum value retrieved)  SUM (sum of all retrieved values) Group Functions

Guide to Oracle 10g63 SELECT AVG (s_age) FROM my_students; SELECT MAX (s_age) FROM my_students; SELECT MIN (s_age) FROM my_students; SELECT SUM (s_age) FROM my_students; Group Function Examples

Guide to Oracle 10g64  Group the output by the column with duplicate values and apply group functions to the grouped data.  Example: SELECT bldg_code, SUM(capacity) FROM location GROUP BY bldg_code;  The bldg_code has 3 values(CR,BUS,LIB) see page 31. Each value has several occurrences, BUS=7 times. So the query group the occurrences of each value and AVG the capacity of each. See result page 145.  Note that AVG(capacity)without group by gives different results. NOT as desired. THINK! Using the GROUP BY Clause

Guide to Oracle 10g65  Is used to filter grouped data. It can be used to place condition on the results of queries that display group function calculation.  Example: SELECT bldg_code, SUM(capacity) FROM location HAVING SUM(capacity) >= 100 GROUP BY bldg_code;  Here we are interested in the total capacity of more than 99 for each building. Using the HAVING Clause

Guide to Oracle 10g66 Creating Alternate Column Headings in SQL*Plus Formatting output: did you notice the output of the queries? the column name appeared as it is in the DB or the calculation formula. To display a different headings: Syntax: SELECT column1 “heading1”, column2 “heading2”, … Example : SELECT bldg_code “Building”, SUM(capacity) “Building Capacity” FROM location GROUP BY bldg_code; Might contain spaces. Example (Building Capacity) See output page 147.

Guide to Oracle 10g67 Creating a Column Alias Column alias: is an alternate column name that can be referenced in the ORDER BY and GROUP BY clauses Syntax: SELECT column1 AS alias1 …  Example: SELECT (SYSDATE – s_dob) AS age_alias ORDER BY age_alias Can NOT contain space.

Guide to Oracle 10g68 SQL* Plus Environment Options  Environment Linessize  Custom  120 (char/line) Pagesize  Custom  40 (line/page) OK

Guide to Oracle 10g69 Formatting Data Using the TO_CHAR Function Used to display NUMBER and DATE values using a specific format mask (model table 3-2 page 92) Syntax: TO_CHAR(fieldname, ‘format_mask’); Note the single quote. Example SELECT c_sec_id, sec_num,c_sec_day, TO_CHAR(c_sec_time, ‘HH:M1 AM’) FROM course_section; See output page 152. See example page 152 for currency format.

Guide to Oracle 10g70 Join Queries Retrieve data from multiple tables by joining tables using foreign key references Syntax SELECT col1, col2, … FROM table1, table2 WHERE table1.joincol = table2.joincol AND search_condition(s); Qualify a column by specifying the table that contains the column followed by a period and then the column name. The WHERE clause contains the join condition, which contains the foreign key reference and the primary key in the other table. Search condition is added using AND or OR operators.

Guide to Oracle 10g71 Join Queries Types Join query types: Inner (equality) Outer Self Inequality

Guide to Oracle 10g72 Inner Joins Occurs when joining two tables based on values in one table being equal to values in another table.

Guide to Oracle 10g73  Syntax: SELECT column1, column2, … FROM table1, table2 WHERE table1.join_column = table2.join_column  You must include a join condition for every link between 2 tables Inner Joins Join condition

Guide to Oracle 10g74  Example: SELECT s_name, f_name FROM student, faculty WHERE student.f_id = faculty.f_id;  If you have N tables in the FROM clause, you must have (N - 1) join conditions Inner Joins

Guide to Oracle 10g75  If the tables have a single commonly named and defined column, you can use the NATURAL JOIN keywords to join the tables. See example figure page 161.  Example SELECT s_name, f_name FROM student NATURAL JOIN faculty; Note:  No commas between table names, just the key words.  No qualifiers are needed. Inner Joins

Guide to Oracle 10g76 Qualifying Field Names If a field in the SELECT clause exists in multiple tables in the FROM clause, you must qualify the field name by prefacing it with either table’s name

Guide to Oracle 10g77 1.Identify all of the tables involved in the query, and label:  Display fields  Join fields  Search fields 2.Write the query  List all display fields in the SELECT clause  List all table names in the FROM clause  List all join condition links in the WHERE clause  List all search fields in the WHERE clause Process for Designing Complex Inner Join Queries

Guide to Oracle 10g78 1.What happens if you omit a join condition in a multiple-table query?  The output retrieves more rows than expected. (Cartesian product).  See example page 166. Process for Designing Complex Inner Join Queries

Guide to Oracle 10g79 Outer Joins Limitation of inner joins: some records may be omitted if corresponding records don’t exist in one of the tables Example: retrieve records for all students, along with their corresponding ENROLLMENT information

Guide to Oracle 10g80 Outer Joins Student 105 (Michael Connoly) does not have any ENROLLMENT records. So no information about 105 will be retrieved when using inner join.

Guide to Oracle 10g81 Outer Joins No records retrieved for Michael:

Guide to Oracle 10g82 Outer Joins To include records in first (inner) table, even when they do not have matching records in second (outer) table: place outer join marker (+) beside outer table name in join clause The (+) signals the DBMS to insert a NULL value for the columns in the outer table that do not have matching rows in the inner table.

Guide to Oracle 10g83 Outer Joins Outer join marker

Guide to Oracle 10g84 Self Joins Used to join a table to itself when the table has a foreign key that references a column in the same table.

Guide to Oracle 10g85 Self Joins To create a self-join, you need to create a table alias, which gives an alternate name to the table so you can create a join condition Syntax to create table alias in FROM clause: FROM table1 alias1, table2 alias2

Guide to Oracle 10g86 Self Joins PARENT_PROJECT PROJECT SUB_PROJECT Alias 1 Alias 2

Guide to Oracle 10g87 Self Join Example Note: the table alias is used in the select clause and in join conditions. NOT the table name.

Guide to Oracle 10g88 Inequality Joins Join created by placing making join condition satisfy an inequality condition(, !=) Only makes sense when primary/foreign key values are not surrogate keys

Guide to Oracle 10g89 Inequality Joins

Guide to Oracle 10g90 Nested Queries Created when a subquery is nested within a main query Main query: first query listed in SELECT command Subquery: retrieves one or more values that specify the main query’s search condition

Guide to Oracle 10g91 Nested Query Where Subquery Returns a Single Value Syntax: SELECT column1, column2, … FROM table1, table2, … WHERE join conditions AND search_column1 = (SELECT column1 FROM table1, table2, … WHERE search and join conditions) Subquery that returns one value

Guide to Oracle 10g92 Nested Query Where Subquery Returns Multiple Values Syntax: SELECT column1, column2, … FROM table1, table2, … WHERE join conditions AND search_column1 IN (SELECT column1 FROM table1, table2, … WHERE search and join conditions) Subquery that returns multiple values

Guide to Oracle 10g93 Performs set operations on outputs of two unrelated queries Both queries must have: same number of display fields corresponding display fields must have same data type Using Set Operators in Queries

Guide to Oracle 10g94 UNION: combines results, suppresses duplicate rows UNION ALL: combines results, displays duplicates INTERSECT: finds matching rows MINUS: returns the difference between returned record sets Query Set Operators

Guide to Oracle 10g95 Logical table based on a query Does not physically exist in the database Presents data in a different format from underlying tables Uses: Security Simplifying complex queries Database Views

Guide to Oracle 10g96 Creating a view: CREATE VIEW view_name AS SQL_command; Views can be queried just like tables: SELECT * FROM view_name; Database Views

Guide to Oracle 10g97 Simple Views Based on SQL query that retrieves data from only one table View can support all table DML operations: INSERT UPDATE DELETE

Guide to Oracle 10g98 Complex Views Based on query that retrieves data from multiple tables Can only be used to support SELECT operations No DML operations supported

Guide to Oracle 10g99 Synonyms Alternate name for a table Allows you to not have to preface table with owner’s username when you are querying a table that belongs to another user

Guide to Oracle 10g100 Public Synonyms Can only be created by a DBA Syntax: CREATE PUBLIC SYNONYM synonym_name FOR owner_name.tablename; All users with privileges to use table can then use synonym instead of owner_name.tablename

Guide to Oracle 10g101 Private Synonyms You can create private synonyms for any tables that you have privileges to use Only you can use the synonym Syntax: CREATE SYNONYM synonym_name FOR table_name.table_name;

Guide to Oracle 10g102 Dynamic SQL Queries Queries that allow users to specify search conditions at runtime Approaches Substitution Values Runtime Variables

Guide to Oracle 10g103 Using Substitution Values Created when search expression is prefaced with an ampersand (&) System then prompts user for value

Guide to Oracle 10g104 Using Runtime Variables Runtime variable: variable defined in SQL*Plus environment Syntax: DEFINE variable_name = variable_value; You can then substitute the variable name for a query search condition value

Guide to Oracle 10g105 Using Runtime Variables Example: