+ All Categories
Home > Documents > Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL...

Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL...

Date post: 22-Apr-2021
Category:
Upload: others
View: 3 times
Download: 0 times
Share this document with a friend
36
© 2013 ITCourseware, LLC Rev 2.1.0 Page iii Introduction to Oracle 11g SQL Programming Contents Chapter 1 - Course Introduction ............................................................................................................. 9 Course Objectives .......................................................................................................................... 10 Course Overview ........................................................................................................................... 12 Using the Workbook ...................................................................................................................... 13 Suggested References ..................................................................................................................... 14 Chapter 2 - Relational Database and SQL Overview ............................................................................. 17 Review of Relational Database Terminology .................................................................................... 18 Relational Database Management Systems ...................................................................................... 20 SQL Datatypes ............................................................................................................................... 22 Introduction to SQL ....................................................................................................................... 24 Chapter 3 - Oracle Database ................................................................................................................ 27 Oracle Versioning and History ......................................................................................................... 28 Logical and Physical Storage Structures .......................................................................................... 30 Datatypes ....................................................................................................................................... 32 Overview of Oracle Architecture ..................................................................................................... 34 Connecting to Oracle ...................................................................................................................... 36 SQL*Plus ...................................................................................................................................... 38 Graphical Clients ............................................................................................................................ 40 The Oracle Data Dictionary ............................................................................................................ 42 Sample Database ............................................................................................................................ 44 Labs ............................................................................................................................................... 48 Chapter 4 - SQL Queries — The SELECT Statement ........................................................................... 51 The SELECT Statement ................................................................................................................. 52 Choosing Rows with the WHERE Clause ........................................................................................ 54 NULL Values ................................................................................................................................. 56 Compound Expressions .................................................................................................................. 58 IN and BETWEEN ........................................................................................................................ 60 Pattern Matching: LIKE and REGEXP_LIKE ................................................................................. 62 The CASE...WHEN Expression ..................................................................................................... 64 Creating Some Order ..................................................................................................................... 66 Labs ............................................................................................................................................... 68 EVALUATION COPY Unauthorized reproduction or distribution is prohibited.
Transcript
Page 1: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

© 2013 ITCourseware, LLC Rev 2.1.0 Page iii

Introduction to Oracle 11g SQL Programming

Contents

Chapter 1 - Course Introduction ............................................................................................................. 9

Course Objectives .......................................................................................................................... 10Course Overview ........................................................................................................................... 12Using the Workbook ...................................................................................................................... 13Suggested References ..................................................................................................................... 14

Chapter 2 - Relational Database and SQL Overview ............................................................................. 17

Review of Relational Database Terminology .................................................................................... 18Relational Database Management Systems ...................................................................................... 20SQL Datatypes ............................................................................................................................... 22Introduction to SQL ....................................................................................................................... 24

Chapter 3 - Oracle Database ................................................................................................................ 27

Oracle Versioning and History ......................................................................................................... 28Logical and Physical Storage Structures .......................................................................................... 30Datatypes ....................................................................................................................................... 32Overview of Oracle Architecture ..................................................................................................... 34Connecting to Oracle ...................................................................................................................... 36SQL*Plus ...................................................................................................................................... 38Graphical Clients ............................................................................................................................ 40The Oracle Data Dictionary ............................................................................................................ 42Sample Database ............................................................................................................................ 44Labs ............................................................................................................................................... 48

Chapter 4 - SQL Queries — The SELECT Statement ........................................................................... 51

The SELECT Statement ................................................................................................................. 52Choosing Rows with the WHERE Clause ........................................................................................ 54NULL Values ................................................................................................................................. 56Compound Expressions .................................................................................................................. 58IN and BETWEEN ........................................................................................................................ 60Pattern Matching: LIKE and REGEXP_LIKE ................................................................................. 62The CASE...WHEN Expression ..................................................................................................... 64Creating Some Order ..................................................................................................................... 66Labs ............................................................................................................................................... 68

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 2: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

Page iv Rev 2.1.0 © 2013 ITCourseware, LLC

Introduction to Oracle 11g SQL Programming

Chapter 5 - Scalar Functions ................................................................................................................ 71

SQL Functions ............................................................................................................................... 72Using SQL Functions ...................................................................................................................... 74String Functions .............................................................................................................................. 76Regular Expression Functions .......................................................................................................... 78Numeric Functions .......................................................................................................................... 80Date Functions ............................................................................................................................... 82Date Formats ................................................................................................................................. 84Conversion Functions ..................................................................................................................... 86Literal Values .................................................................................................................................. 88Intervals ......................................................................................................................................... 90Oracle Pseudocolumns ................................................................................................................... 92Labs ............................................................................................................................................... 94

Chapter 6 - SQL Queries — Joins ........................................................................................................ 97

Selecting from Multiple Tables ......................................................................................................... 98Joining Tables ............................................................................................................................... 100Self Joins ...................................................................................................................................... 102Outer Joins ................................................................................................................................... 104Equijoins, Non-equijoins, and Antijoins ......................................................................................... 106Labs ............................................................................................................................................. 108

Chapter 7 - Aggregate Functions and Advanced Techniques ................................................................. 111

Subqueries ................................................................................................................................... 112Correlated Subqueries .................................................................................................................. 114The EXISTS Operator ................................................................................................................. 116The Aggregate Functions ............................................................................................................... 118Nulls and DISTINCT ................................................................................................................... 120Grouping Rows ............................................................................................................................ 122Combining SELECT Statements ................................................................................................... 124Labs ............................................................................................................................................. 126

Chapter 8 - Data Manipulation and Transactions ................................................................................. 129

The INSERT Statement ................................................................................................................ 130The UPDATE Statement ............................................................................................................... 132The DELETE Statement ............................................................................................................... 134Transaction Management .............................................................................................................. 136Concurrency ................................................................................................................................. 138

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 3: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

© 2013 ITCourseware, LLC Rev 2.1.0 Page v

Introduction to Oracle 11g SQL Programming

Explicit Locking ............................................................................................................................ 140Data Inconsistencies ..................................................................................................................... 142Loading Tables From External Sources ......................................................................................... 144Labs ............................................................................................................................................. 146

Chapter 9 - Data Definition and Control Statements ............................................................................ 149

Datatypes ..................................................................................................................................... 150Defining Tables ............................................................................................................................. 152Constraints ................................................................................................................................... 154Inline Constraints .......................................................................................................................... 156Modifying Table Definitions ........................................................................................................... 158Deleting a Table Definition ............................................................................................................. 160Controlling Access to Your Tables ................................................................................................. 162Labs ............................................................................................................................................. 164

Chapter 10 - Other Database Objects ................................................................................................ 167

Views ........................................................................................................................................... 168Creating Views ............................................................................................................................. 170Updatable Views .......................................................................................................................... 172Sequences .................................................................................................................................... 174Indexes ........................................................................................................................................ 176Labs ............................................................................................................................................. 178

Appendix A - Using Oracle SQL*Plus ................................................................................................ 181

SQL*Plus .................................................................................................................................... 182The SQL Buffer ............................................................................................................................ 184Buffer Manipulation Commands .................................................................................................... 186Running SQL*Plus Scripts ............................................................................................................ 188Tailoring Your SQL*Plus Environment ........................................................................................... 190Viewing Table Characteristics ........................................................................................................ 192SQL*Plus Substitution Variables ................................................................................................... 194Interactive SQL*Plus Scripts ........................................................................................................ 196SQL*Plus LOB Support .............................................................................................................. 198Labs ............................................................................................................................................. 200

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 4: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

Page vi Rev 2.1.0 © 2013 ITCourseware, LLC

Introduction to Oracle 11g SQL Programming

Appendix B - The Data Dictionary ...................................................................................................... 203

Introducing the Data Dictionary ..................................................................................................... 204DBA, ALL, and USER Data Dictionary Views .............................................................................. 206Some Useful Data Dictionary Queries ........................................................................................... 208

Solutions ............................................................................................................................................ 211

Index .................................................................................................................................................. 229

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 5: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

© 2013 ITCourseware, LLC Rev 2.1.0 Page vii

Introduction to Oracle 11g SQL Programming

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 6: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

Page viii Rev 2.1.0 © 2013 ITCourseware, LLC

Introduction to Oracle 11g SQL Programming

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 7: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

Course IntroductionChapter 1

© 2013 ITCourseware, LLC Rev 2.1.0 Page 9

Chapter 1 - Course IntroductionEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 8: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

Introduction to Oracle 11g SQL Programming

Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC

Describe the features of a Relational Database.

Interact with a Relational Database Management System.

Use SQL*Plus to connect to an Oracle database and submit SQL statements.

Write SQL queries.

Use SQL functions.

Use a query to join together data items from multiple tables.

Write nested queries.

Perform summary analysis of data in a query.

Add, change, and remove data in a database.

Manage database transactions.

Work in a multi-user database environment.

Create and manage tables and other database objects.

Control access to data.

Course ObjectivesEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 9: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

Course IntroductionChapter 1

© 2013 ITCourseware, LLC Rev 2.1.0 Page 11

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 10: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

Introduction to Oracle 11g SQL Programming

Page 12 Rev 2.1.0 © 2013 ITCourseware, LLC

Audience: This course is designed for database application developers.

Prerequisites: Familiarity with relational database concepts.

Student Materials:

Student workbook

Classroom Environment:

One workstation per student

Oracle 11g

Course OverviewEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 11: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

Course IntroductionChapter 1

© 2013 ITCourseware, LLC Rev 2.1.0 Page 13

Using the Workbook

Chapter 2 Servlet Basics

© 2002 ITCourseware, LLC Rev 2.0.0 Page 17

Add an init() method to your Today servlet that initializes a bornOn date, then print the bornOn date

along with the current date:

Today.java

...

public class Today extends GenericServlet {

private Date bornOn;

public void service(ServletRequest request,

ServletResponse response) throws ServletException, IOException

{

...

// Write the document

out.println("This servlet was born on " + bornOn.toString());

out.println("It is now " + today.toString());

}

public void init() {

bornOn = new Date();

}

}

Hands On:

The init() method is

called when the servlet is

loaded into the container.

This workbook design is based on a page-pair, consisting of a Topic page and a Support page. When youlay the workbook open flat, the Topic page is on the left and the Support page is on the right. The Topicpage contains the points to be discussed in class. The Support page has code examples, diagrams, screenshots and additional information. Hands On sections provide opportunities for practical application of keyconcepts. Try It and Investigate sections help direct individual discovery.

In addition, there is an index for quick look-up. Printed lab solutions are in the back of the book as well ason-line if you need a little help.

Java Servlets

Page 16 Rev 2.0.0 © 2002 ITCourseware, LLC

� The servlet container controls the life cycle of the servlet.

� When the first request is received, the container loads the servlet class

and calls the init() method.

� For every request, the container uses a separate thread to call

the service() method.

� When the servlet is unloaded, the container calls the destroy()

method.

� As with Java’s finalize() method, don’t count on this being

called.

� Override one of the init() methods for one-time initializations, instead of

using a constructor.

� The simplest form takes no parameters.

public void init() {...}

� If you need to know container-specific configuration information, use

the other version.

public void init(ServletConfig config) {...

� Whenever you use the ServletConfig approach, always call the

superclass method, which performs additional initializations.

super.init(config);

The Servlet Life Cycle

The Topic page providesthe main topics for

classroom discussion.

The Support page hasadditional information,

examples and suggestions.

Code examples are in afixed font and shaded. Theon-line file name is listedabove the shaded area.

Screen shots showexamples of what youshould see in class.

Topics are organized intofirst ( ), second ( ) and

third ( ) level points.

Pages are numberedsequentially throughoutthe book, making lookup

easy.

Callout boxes point outimportant parts of the

example code.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 12: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

Introduction to Oracle 11g SQL Programming

Page 14 Rev 2.1.0 © 2013 ITCourseware, LLC

Beaulieu, Alan. 2009. Learning SQL. O'Reilly & Associates, Sebastopol, CA. ISBN 0596520823

Celko, Joe. 2010. Joe Celko's SQL for Smarties, Fourth Edition: Advanced SQL Programming.Academic Press/ Morgan Kaufman, San Francisco, CA. ISBN 0123820227

Celko, Joe. 2006. Joe Celko's SQL Puzzles and Answers. Morgan Kaufmann, San Francisco,CA.ISBN 0123735963

Churcher, Clare. 2008. Beginning SQL Queries: From Novice to Professional. Apress, Inc.,Berkeley, CA. ISBN 9781590599433

Date, C.J. and Hugh Darwen. 1996. A Guide to The SQL Standard, Fourth Edition. Addison-Wesley, Reading, MA. ISBN 0201964260

Date, C. J.. 2011. SQL and Relational Theory, Second Edition: How to Write Accurate SQLCode. O'Reilly Media, Sebastopol, CA. ISBN 1449316409

Gennick, Jonathan. 2004. Oracle Sql*Plus Pocket Reference, Third Edition. O'Reilly & Associates,Sebastopol, CA. ISBN 0596008856

Gruber, Martin. 2000. SQL Instant Reference, Second Edition. SYBEX, Alameda, CA.ISBN 0782125395

Kline, Kevin. 2009. SQL in a Nutshell, Third Edition. O'Reilly & Associates, Sebastopol, CA.ISBN 0596518847

Kreines, David. 2003. Oracle Data Dictionary Pocket Reference. O'Reilly & Associates, Sebastopol,CA. ISBN 0596005172

Loney, Kevin. 2008. Oracle Database 11g: The Complete Reference. McGraw-Hill Osborne Media,ISBN 0071598758

Mishra, Sanjay. 2009. Mastering Oracle SQL, Second Edition. O'Reilly & Associates, Sebastopol,CA. ISBN 0596006322

http://tahiti.oracle.com http://www.oracle.comhttp://www.dbasupport.com http://www.searchdatabase.comhttp://www.orafaq.com http://www.toadworld.comhttp://asktom.oracle.com

Suggested ReferencesEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 13: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

Course IntroductionChapter 1

© 2013 ITCourseware, LLC Rev 2.1.0 Page 15

Your single most important reference is the SQL Language Reference book, which is part of the OracleDatabase Online Documentation Library. You may have received this on CD-ROM with your Oracledistribution. If not, you can access it online at Oracle's web site. This is the official, complete description ofOracle's implementation of SQL. It includes many examples and discussions.

An easy way to find it is to go to:

http://tahiti.oracle.com/

Find the documentation for your version of Oracle Database. Locate the SQL Language Reference, andopen the HTML table of contents.

If you have web access in the classroom, open a browser now and find the SQL Language Reference. Seta browser bookmark, and have the SQL Language Reference at hand throughout this class.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 14: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

Introduction to Oracle 11g SQL Programming

Page 16 Rev 2.1.0 © 2013 ITCourseware, LLC

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 15: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

Relational Database and SQL OverviewChapter 2

© 2013 ITCourseware, LLC Rev 2.1.0 Page 17

Chapter 2 - Relational Database and SQLOverview

Objectives

Describe the features of a Relational Database.

Describe the features of a Relational DatabaseManagement System.

Describe the standard SQL datatypes.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 16: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

Introduction to Oracle 11g SQL Programming

Page 18 Rev 2.1.0 © 2013 ITCourseware, LLC

Relational Databases:

A Relational Database consists of tables, each with a specific name.

A table is organized in columns, each with a specific name and eachcapable of storing a specific datatype.

A row is a distinct set of values, one value for each column (although acolumn value might be empty (null) for a particular row).

Each table can have a primary key, consisting of one or more columns.

The set of values in the primary key column or columns must beunique and not null for each row.

One table might contain a column or columns that correspond to theprimary key or unique key of another table; this is called a foreign key.

Review of Relational Database TerminologyEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 17: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

Relational Database and SQL OverviewChapter 2

© 2013 ITCourseware, LLC Rev 2.1.0 Page 19

A Relational Database (RDB) is a database which conforms to Foundation Rules defined by Dr. E. F.Codd. It is a particular method of organizing information.

A Relational Database Management System (RDBMS) is a software system that allows you tocreate and manage a Relational Database. Minimum requirements for such a system are defined by bothANSI and ISO. The most recent standard is named SQL2, since most of the standard simply defines thelanguage (SQL) used to create and manage such a database and its data. Some people use the term SQLDatabase as a synonym for Relational Database.

Each row (sometimes called a record) represents a single entity in the real world. Each column(sometimes called a field) in that row represents an attribute of that entity.

Entity Relationship Modeling is the process of deciding which attributes of which entities you willstore in your database, and how different entities are related to one another.

The formal word for row is tuple; that is, each row in a table that has three columns might be called atriple (a set of three attribute values); five columns, a quintuple; eight columns, an octuple; or, ingeneral, however many attributes describe an entity of some sort, the set of column values in a rowthat represents one such entity is a tuple. The formal word for column is attribute.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 18: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

Introduction to Oracle 11g SQL Programming

Page 20 Rev 2.1.0 © 2013 ITCourseware, LLC

A Relational Database Management System (RDBMS) provides for users.

Each user is identified by an account name.

A user can access data and create database objects based onprivileges granted by the database administrator.

Users own the tables they create; the set of tables (and other databaseobjects) owned by a user is called a schema.

Users can grant privileges so that other users can access theschema.

A session starts when you connect to the system.

Once you connect to the database system, all your changes are considered asingle transaction until you either commit or rollback your work.

SQL is a standard language for querying, manipulating data, and creating andmanaging objects in your schema.

The Data Dictionary (also called a System Catalog or Online Catalog) is a setof ordinary relational tables, maintained by the system, whose rows describe thetables in your schema.

You can query a system catalog table just like any other table.

Each database vendor has its own system catalog.

Relational Database Management SystemsEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 19: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

Relational Database and SQL OverviewChapter 2

© 2013 ITCourseware, LLC Rev 2.1.0 Page 21

You can use the Oracle Enterprise Manager to graphically display database schemas, users, and objectdetails, as well as to perform a variety of administrative tasks. You may also use SQL*Plus to perform manyof the same tasks. For example, you can use SQL*Plus to query the Data Dictionary:

dictionary.sqlSELECT * FROM dictionary WHERE table_name LIKE 'USER%';

user_tables.sqlSELECT table_name FROM user_tables;

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 20: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

Introduction to Oracle 11g SQL Programming

Page 22 Rev 2.1.0 © 2013 ITCourseware, LLC

SQL Datatypes

Each column in a table has a specific, predefined datatype.

Only values of the correct type can be stored in the column.

Many datatype definitions also include a limit on the size of the values thatare allowed.

The details of how data values are stored vary among database vendors.

Most database vendors provide similar sets of datatypes, though.

The most important ANSI/ISO standard datatypes are:

CHARACTER — Text values of a specific predefined length; thedatabase pads shorter values to the correct length with spaces.

CHARACTER VARYING — Text values whose length can vary, up toa predefined maximum length for each column.

BIT, BIT VARYING — Fixed or varying-length bit strings for binarydata such as images or documents.

INTEGER — Whole number values, possibly with predefined precision.

FLOAT, DOUBLE PRECISION FLOAT— Floating-point numbers.

NUMERIC/DECIMAL — Fixed-point numbers, with predefinedprecision and scale.

DATE, TIME, DATETIME, TIMESTAMP — Calendar date, clocktime, combined date/time, date/time with predefined precision.

INTERVAL — Time interval, perhaps with predefined precision.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 21: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

Relational Database and SQL OverviewChapter 2

© 2013 ITCourseware, LLC Rev 2.1.0 Page 23

While most SQL database vendors provide all the ANSI/ISO standard datatypes in one form or another,they vary widely in their implementation and internal storage format. Examples:

INTEGER:* MySQL has TINYINT (1 byte, signed or unsigned), SMALLINT (2 bytes, signed or unsigned), INT

or INTEGER (4 bytes, signed or unsigned), and BIGINT (8 bytes, signed or unsigned.)

* Microsoft SQL Server has TINYINT (1 byte, unsigned), SMALLINT (2 bytes, signed), INT (4bytes, signed), and BIGINT (8 bytes, signed).

* Oracle Database has NUMBER(p), where p specifies precision as the number of decimal digits (up to38); values stored in a varying length proprietary binary format, consuming only as many bytes as areneeded for each number.

CHARACTER VARYING:* MySQL has VARCHAR(n) where n is the maximum number of characters allowed, up to 65,536.

* Microsoft SQL Server has VARCHAR(n), where n is either the maximum number of bytes allowed,up to 8,000; or the word max indicating strings up to 2GB are allowed.

* Oracle Database has VARCHAR2(n), where n is the maximum number of bytes allowed, up to 4,000.

DATE, TIME, DATETIME:* MySQL has DATE (calendar date, from 1000-01-01 ad to 9999-12-31 A.D.), TIME (clock time),

and DATETIME (combined date and clock time), all stored in compact binary formats.

* Microsoft SQL Server has DATE (calendar date, from 0001-01-01 to 9999-12-31 A.D.), TIME(clock time), DATETIME (combined date and time from 1753-01-01 to 9999-12-31 A.D),DATETIME2 (combined date and time from 0001-01-01 to 9999-12-31 A.D), andSMALLDATETIME (combined date and time from 1900-01-01 to 2079-06-06 A.D).

* Oracle Database has DATE (combined date and time from 4712-01-01 B.C to 9999-12-31 A.D.),stored in a compact 7-byte binary format.

In addition, each database product has its own rules for presenting and accepting dates as human-readablestrings.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 22: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

Introduction to Oracle 11g SQL Programming

Page 24 Rev 2.1.0 © 2013 ITCourseware, LLC

SQL is the abbreviation for Structured Query Language.

It is often pronounced as "sequel."

SQL was first developed by IBM in the mid-1970s.

SQL is the international standard language for relational database managementsystems.

SQL is considered a fourth-generation language.

It is English-like and intuitive.

SQL is robust enough to be used by:

Users with non-technical backgrounds.

Professional developers.

Database administrators.

SQL is a non-procedural language that emphasizes what to get, but not how toget it.

Each vendor has its own implementation of SQL; most large vendors complywith the more recent ANSI/ISO standards, and may include proprietary languageextensions for greater functionality.

Introduction to SQLEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 23: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

Relational Database and SQL OverviewChapter 2

© 2013 ITCourseware, LLC Rev 2.1.0 Page 25

SQL statements can be placed in two main categories:

Data Manipulation Language (DML):

Query: SELECT

Data Manipulation: INSERTUPDATEDELETE

Transaction Control: COMMITROLLBACK

Data Definition Language (DDL):

Data Definition: CREATEALTERDROP

Data Control: GRANTREVOKE

SQL is actually an easy language to learn (many users pick up the basics with no additionalinstruction). SQL statements look more like natural language than many other programming languages. Wecan parse them into "verbs," "clauses," and "predicates." Additionally, SQL is a compact language, making iteasy to learn and remember. Users and programmers spend most of their time working with only four simplekeywords (the Query and DML verbs in the list above). Of course, as we'll learn in this class, you can usethem in sophisticated ways.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 24: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

SQL Queries — JoinsChapter 6

© 2013 ITCourseware, LLC Rev 2.1.0 Page 97

Chapter 6 - SQL Queries — Joins

Objectives

Collect data from multiple tables witha single query.

Use the relational aspects of yourdatabase in queries.

Relate columns within the sametable.

Use LEFT, RIGHT, and FULLouter joins.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 25: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

Introduction to Oracle 11g SQL Programming

Page 98 Rev 2.1.0 © 2013ITCourseware, LLC

To retrieve data from more than one table in the same SELECT statement, thetables are joined together.

Specify the tables in the FROM clause using the INNER JOIN keywords.

Use the ON clause with a join condition to specify how the rows in thesecond table should match the original rows.

emp.sqlSELECT lastname, title FROM person INNER JOIN employee ON person.id = employee.id;

The word INNER is optional.

If you reference a column whose name appears in more than one table, you mustprecede the column name with the table name, often called a qualified reference.

...ON person.id = employee.id;

Using a table alias can save you some typing.

emp2.sqlSELECT p.id AS id, lastname, title FROM person p JOIN employee e ON p.id = e.id;

If the join clause involves columns with the same name, you may use theUSING clause, omitting the explicit join condition:

using.sqlSELECT id, lastname, title FROM person JOIN employee USING (id)

With USING, the table name or alias cannot be used to qualify the columnname, as the join columns are rolled together into a single column.

Selecting from Multiple TablesEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 26: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

SQL Queries — JoinsChapter 6

© 2013 ITCourseware, LLC Rev 2.1.0 Page 99

When you join two tables, the result set consists of all of the rows that matched the join condition (and anyother conditions). All rows that do not have a corresponding row in the other table are thrown out. This iscalled an inner join.

The following query will return information only for employees; no other people from the person table willhave a matching id in the employee table.

emp2.sqlSELECT p.id AS id, lastname, title FROM person p JOIN employee e ON p.id = e.id;

In fact, we know that we will get information for all employees, because the foreign key from employee.idto person.id means every employee record must have a matching person record.

Additional types of joins are supported, although they are not as commonly used.

NATURAL JOIN — A type of inner join that matches records based on columns from the two tables thathave the same column name.

natural.sqlSELECT id, pay_amount, pay_type_name FROM employee NATURAL JOIN pay_type;

This natural join is equivalent to the following inner join.inner.sqlSELECT id, pay_amount, pay_type_name FROM employee JOIN pay_type USING (pay_type_code);

CROSS JOIN — A join done without any join conditions. Every row in the first table is matched withevery row in the second table. This is also called a Cartesian product.

cross.sqlSELECT store_number, product_id FROM store CROSS JOIN product;

This cross join will return a list of each product for each store in the database.

Note:The examples in this chapter use the ANSI standard syntax for joins, which you should always use.However, you might see older join syntax, which is still valid SQL, in which the join conditions are mingledwith selection predicates in the WHERE clause:

emp4.sqlSELECT p.id AS id, lastname, title FROM person p, employee e WHERE p.id = e.id;

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 27: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

Introduction to Oracle 11g SQL Programming

Page 100 Rev 2.1.0 © 2013ITCourseware, LLC

Though you can join tables using any columns with compatible data types,parent/child relationships are often used in the join criteria.

emp5.sqlSELECT lastname, firstname, title, pay_amount FROM person p JOIN employee e USING (id) WHERE id = 9996;

This relationship is implemented with a foreign key.

There is no limit to the number of tables that can be joined together.

Each table joined into the query will have its own join criteria, matching itsdata to data from any of the previously listed tables.

multitable.sqlSELECT lastname, title, pay_amount, pay_type_name FROM person p JOIN employee e ON p.id = e.id JOIN pay_type ON pt.pay_type_code = e.pay_type_code;

The join condition can also be complex, involving multiple columns.

multicolumn.sqlSELECT id, p.city, store_number, s.city FROM person p JOIN store s ON p.state = s.state AND p.area_code = s.area_code;

All fields from a table can be selected.

emp6.sqlSELECT lastname, firstname, e.* FROM person p JOIN employee e ON p.id = e.id WHERE p.id = 9996;

Joining TablesEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 28: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

SQL Queries — JoinsChapter 6

© 2013 ITCourseware, LLC Rev 2.1.0 Page 101

Joining the same tables using different columns will retrieve very different result sets.

This query retrieves the names of the store managers.

store1.sqlSELECT id, lastname, store_number FROM person p JOIN store s ON p.id = s.manager_id ORDER BY id;

This query retrieves the names of people living in the same city as one of our stores.

store2.sqlSELECT id, lastname, store_number FROM person p JOIN store s ON p.city = s.city ORDER BY id;

You will also need to carefully decide which tables are joined to which other tables in your query. In this firstquery, the person table is joined with the order_header table, which is then joined to the store table. Weare retrieving a list of all customers' orders.

multi1.sqlSELECT p.lastname, oh.invoice_number, s.city, s.state FROM person p JOIN order_header oh ON p.id = oh.customer_id JOIN store s ON s.store_number = oh.store_number;

This next query involves the same three tables, but they are joined together differently. We are joining theorder_header table to the person table and the person table to the store table. We are retrieving a list ofmanagers and what orders they have placed.

multi2.sqlSELECT p.lastname, oh.invoice_number, s.city, s.state FROM person p JOIN order_header oh ON p.id = oh.customer_id JOIN store s ON s.manager_id = p.id;

These two queries retrieve very different result sets.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 29: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

Introduction to Oracle 11g SQL Programming

Page 102 Rev 2.1.0 © 2013ITCourseware, LLC

di.pme eltit.pme di_rosivrepus.pme

8269 repeekkooB 4346

8737 peRselaS 4346

0599 peRselaS 4346

4346 reganaMerotS

... ... ...

A self join queries a single table as though it were two separate tables.

Self joins are most frequently performed on tables that model hierarchicaldata, having foreign keys back into the same table.

You must use table aliases to perform a self join.

self_join.sqlSELECT emp.id, emp.title, sup.id, sup.title FROM employee emp JOIN employee sup ON emp.supervisor_id = sup.id;

emp (employee)

sup (employee)

di.pus eltit.pus di_rosivrepus.pus

8269 repeekkooB 4346

8737 peRselaS 4346

0599 peRselaS 4346

4346 reganaMerotS

... ... ...

Self JoinsEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 30: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

SQL Queries — JoinsChapter 6

© 2013 ITCourseware, LLC Rev 2.1.0 Page 103

Additional tables may also need to be joined in multiple times if more than one row needs to be used in theresult set record.

Here the name of the employee and the name of their supervisor are both being displayed. These names arefound in two different records in the person table.

emp_name.sqlSELECT ep.lastname || ', ' || ep.firstname "Emp.", emp.title, 'Supervisor: ' || sp.firstname || ' ' || sp.lastname "Sup.", 'Sup. Title: ' || sup.title "Sup. Title" FROM person ep JOIN employee emp ON emp.id = ep.id JOIN employee sup ON emp.supervisor_id = sup.id JOIN person sp ON sup.id = sp.id;

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 31: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

Introduction to Oracle 11g SQL Programming

Page 104 Rev 2.1.0 © 2013ITCourseware, LLC

An outer join retrieves all rows from one table, plus the matching rows from thesecond table.

The column values for the non-matched rows (which would have comefrom the second table) will be NULL.

Standard join syntax specifies which table, the LEFT or RIGHT, will have all ofits rows returned.

outer_join1.sqlSELECT oh.invoice_number, oh.order_date, a.account_name FROM order_header oh LEFT OUTER JOIN account a USING (account_number);

All records from the LEFT table will be returned, with NULLs in columnswhere information from the RIGHT table was not available.

The OUTER keyword is optional.

FULL [OUTER] JOIN — All matching rows from the two tables, plus rowsfrom each table that have no matching rows in the other.

If you join another table to an outer joined table, you will also need to outer jointhe new table.

outer_join2.sqlSELECT oh.invoice_number, oh.order_date, a.account_name, p.lastname FROM order_header oh LEFT OUTER JOIN account a USING (account_number) LEFT OUTER JOIN person p ON id = a.customer_id;

Without the second outer join, you will not be able to match against NULLvalues in the result set, and the rows will be lost.

outer_join3.sqlSELECT oh.invoice_number, oh.order_date, a.account_name, p.lastname FROM order_header oh LEFT OUTER JOIN account a USING (account_number) JOIN person p ON id = a.customer_id;

Outer JoinsEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 32: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

SQL Queries — JoinsChapter 6

© 2013 ITCourseware, LLC Rev 2.1.0 Page 105

When a row in one joined table does not have a matching row in the other table, the row is left out of theresult set of an ordinary (INNER) join.

mgr1.sqlSELECT city, manager_id, title FROM store s JOIN employee e ON e.id = s.manager_id;

With an OUTER join, when a row in one joined table does not have a match in the other table, theunmatched row remains in the result set. NULL values are supplied for the columns that would have comefrom the other table.

mgr2.sqlSELECT city, manager_id, title FROM store s LEFT OUTER JOIN employee e ON e.id = s.manager_id;

The following left outer join:

left_outer.sqlSELECT oh.invoice_number, oh.order_date, a.account_name, a.balance FROM order_header oh LEFT OUTER JOIN account a

ON oh.account_number = a.account_number WHERE oh.amount_due > 0;

Can be turned into this right outer join:

right_outer.sqlSELECT oh.invoice_number, oh.order_date, a.account_name, a.balance FROM account a RIGHT OUTER JOIN order_header oh ON a.account_number = oh.account_number WHERE oh.amount_due > 0;

In versions of Oracle prior to 9i, joins simply listed the tables in the FROM clause. Join conditions werejust ordinary column comparison expressions in the WHERE clause. For an outer join, you would modifythe join conditions, adding (+) next to any columns from the inner table:

old_outer_join.sqlSELECT oh.invoice_number, oh.order_date, a.account_name, a.balance FROM order_header oh, account a WHERE oh.amount_due > 0 AND oh.account_number = a.account_number(+);

This syntax, which is unique to Oracle, is still supported in Oracle 11g. Always use the new, or ANSI, joinsyntax unless your SQL must be compatible with very old versions of Oracle. ANSI join syntax has manyadvantages. The old syntax does not allow a full outer join, requiring a UNION to get similar results.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 33: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

Introduction to Oracle 11g SQL Programming

Page 106 Rev 2.1.0 © 2013ITCourseware, LLC

Most joins are equijoins - the join columns are compared for equality.

equijoin.sqlSELECT id, minimum_wage, pay_amount, pay_type_name FROM employee e JOIN pay_type pt ON e.pay_type_code = pt.pay_type_code AND e.pay_amount = pt.minimum_wage;

A non-equijoin uses a condition other than equality, such as <, >,BETWEEN, or LIKE to compare the join columns.

nonequijoin1.sqlSELECT e.id, pt.minimum_wage, e.pay_amount, pt.pay_type_name FROM employee e JOIN pay_type pt ON e.pay_type_code = pt.pay_type_code AND e.pay_amount > pt.minimum_wage;

nonequijoin2.sqlSELECT lastname, title FROM employee e JOIN person p ON p.id = e.id AND lastname LIKE substr(title,1,1) || '%';

An antijoin is an outer join with the matched rows omitted.

antijoin.sqlSELECT p.product_id, description FROM product p LEFT OUTER JOIN inventory i ON p.product_id = i.product_id AND i.store_number = 7 WHERE i.product_id IS NULL;

Equijoins, Non-equijoins, and AntijoinsEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 34: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

SQL Queries — JoinsChapter 6

© 2013 ITCourseware, LLC Rev 2.1.0 Page 107

joins.sqlEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 35: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

Introduction to Oracle 11g SQL Programming

Page 108 Rev 2.1.0 © 2013ITCourseware, LLC

Using joins, write queries to:

a. List of all of the store locations and their manager's first and last name.(Solution: join_a.sql)

b. Find the name of the person who manages the store in Las Vegas.(Solution: join_b.sql)

c. Find the names of all employees supervised by the manager of the Las Vegas store.(Solution: join_c.sql)

d. List the names of everyone living in Glendale, California who has an account.(Solution: join_d.sql)

Using joins, write queries to:

a. List the first and last name of each employee.(Solution: emp_a.sql)

b. List the first name, last name, and pay type name of each employee.(Solution: emp_b.sql)

Write a query to list orders. It should retrieve invoice number, name of the person who placedthe order, product ids, and quantities.(Solution: invoice.sql)

Modify the query from to include the product description of each item.(Solution: invoice2.sql)

Modify the query from to include the total price to the customer (quantity times price minusdiscount) of each item; don't try subtotaling these!(Solution: invoice3.sql)

LabsEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 36: Introduction to Oracle 11g SQL Programming · 2020. 9. 29. · Introduction to Oracle 11g SQL Programming Page 10 Rev 2.1.0 © 2013 ITCourseware, LLC Describe the features of a Relational

SQL Queries — JoinsChapter 6

© 2013 ITCourseware, LLC Rev 2.1.0 Page 109

Write a query that lists all stores and their manager's names, including those that do not currentlyhave a manager.(Solution: manager.sql)

Write a query that will list the first and last name, along with the supervisor's id and title, of eachemployee.(Solution: supervisor.sql)

(Optional) Modify the query from so that it lists all employees, even those with no supervisor.(Solution: supervisor2.sql)

(Optional) Modify the query from so that it also lists the supervisor's first and last name.(Solution: supervisor3.sql)

(Optional) The product table lists the stock threshold for everything we sell. If this value is 0, thenthe product is a special-order item that is not normally carried in stock. If the value of the stockthreshold is greater than zero, then the product must be reordered whenever the quantity on handdrops below that value.

Find all products that are low on inventory and must be reordered for Store #1. Don't reorder ifthere is already a quantity_on_order for this item; note that quantity_on_order might be null.(Solution: product.sql)

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.


Recommended