+ All Categories
Home > Documents > Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the...

Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the...

Date post: 09-Jun-2018
Category:
Upload: dinhnga
View: 224 times
Download: 0 times
Share this document with a friend
386
C:\Program Files\Adobe\FrameMaker8\UniData 7.2\7.2rebranded\SQL\SQLUTITL.fm March 9, 2010 11:38 am Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta UniData Using UniData SQL UDT-720-SQLU-1
Transcript
Page 1: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

C:\Program Files\Adobe\FrameMaker8\UniData 7.2\7.2rebranded\SQL\SQLUTITL.fmMarch 9, 2010 11:38 am

Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta

UniData

Using UniData SQL

UDT-720-SQLU-1

Page 2: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

ii Using UniData SQ

C:\Program Files\Adobe\FrameMaker8\UniData 7.2\7.2rebranded\SQL\SQLUTITL.fmMarch 9, 2010 11:38 am

Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta

Notices

EditionPublication date: July 2008Book number: UDT-720-SQLU-1Product version: UniData 7.2

Copyright© Rocket Software, Inc. 1988-2008. All Rights Reserved.

TrademarksThe following trademarks appear in this publication:

Trademark Trademark Owner

Rocket Software™ Rocket Software, Inc.

Dynamic Connect® Rocket Software, Inc.

RedBack® Rocket Software, Inc.

SystemBuilder™ Rocket Software, Inc.

UniData® Rocket Software, Inc.

UniVerse™ Rocket Software, Inc.

U2™ Rocket Software, Inc.

U2.NET™ Rocket Software, Inc.

U2 Web Development Environment™ Rocket Software, Inc.

wIntegrate® Rocket Software, Inc.

Microsoft® .NET Microsoft Corporation

Microsoft® Office Excel®, Outlook®, Word Microsoft Corporation

Windows® Microsoft Corporation

Windows® 7 Microsoft Corporation

Windows Vista® Microsoft Corporation

Java™ and all Java-based trademarks and logos Sun Microsystems, Inc.

UNIX® X/Open Company Limited

L

Page 3: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The above trademarks are property of the specified companies in the United States, other countries, or both. All other products or services mentioned in this document may be covered by the trademarks, service marks, or product names as designated by the companies who own or market them.

License agreementThis software and the associated documentation are proprietary and confidential to Rocket Software, Inc., are furnished under license, and may be used and copied only in accordance with the terms of such license and with the inclusion of the copyright notice. This software and any copies thereof may not be provided or otherwise made available to any other person. No title to or ownership of the software and associated documentation is hereby transferred. Any unauthorized use or reproduction of this software or documentation may be subject to civil or criminal liability. The information in the software and documentation is subject to change and should not be construed as a commitment by Rocket Software, Inc.

Restricted rights notice for license to the U.S. Government: Use, reproduction, or disclosure is subject to restrictions as stated in the “Rights in Technical Data-General” clause (alternate III), in FAR section 52.222-14. All title and ownership in this computer software remain with Rocket Software, Inc.

NoteThis product may contain encryption technology. Many countries prohibit or restrict the use, import, or export of encryption technologies, and current use, import, and export regulations should be followed when exporting this product.

Please be aware: Any images or indications reflecting ownership or branding of the product(s) documented herein may or may not reflect the current legal ownership of the intellectual property rights associated with such product(s). All right and title to the product(s) documented herein belong solely to Rocket Software, Inc. and its subsidiaries, notwithstanding any notices (including screen captures) or any other indications to the contrary.

Contact informationRocket Software275 Grove Street Suite 3-410Newton, MA 02466-2272 USA Tel: (617) 614-4321 Fax: (617) 630-7100Web Site: www.rocketsoftware.com

Using UniData SQL iii

Page 4: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Table of Contents

:\ProgMarch

Table of Contents

Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta

Chapter 1 Introduction to UniData SQLUniData SQL Commands Reference . . . . . . . . . . . 1-2Additional Reading . . . . . . . . . . . . . . . . . 1-2

The UniData RDBMS. . . . . . . . . . . . . . . . . . 1-3Elements of the UniData Database . . . . . . . . . . . . 1-3

UniData Demo Databases . . . . . . . . . . . . . . . . 1-4Overview of UniData SQL . . . . . . . . . . . . . . . . 1-5

Features of UniData SQL . . . . . . . . . . . . . . . 1-5Elements of UniData SQL . . . . . . . . . . . . . . . . 1-7

UniData SQL Tables . . . . . . . . . . . . . . . . 1-7The SELECT Statement . . . . . . . . . . . . . . . 1-8Multivalued Attributes . . . . . . . . . . . . . . . . 1-9Associations . . . . . . . . . . . . . . . . . . . 1-9Unnesting Multivalued Attributes . . . . . . . . . . . . 1-9

The UniData Dictionary . . . . . . . . . . . . . . . . . 1-10Elements of Dictionary Records . . . . . . . . . . . . . 1-10

Chapter 2 Getting StartedStarting UniData SQL. . . . . . . . . . . . . . . . . . 2-4Creating a Table . . . . . . . . . . . . . . . . . . . 2-7Inserting Data into a Table . . . . . . . . . . . . . . . . 2-8Updating Data in a Table . . . . . . . . . . . . . . . . . 2-9Deleting Data from a Table . . . . . . . . . . . . . . . . 2-10Selecting Data from a Table . . . . . . . . . . . . . . . . 2-11Removing Tables . . . . . . . . . . . . . . . . . . . 2-12Exporting Selected Data to a Sequential File . . . . . . . . . . 2-13Exporting Selected Data to a Temporary Table . . . . . . . . . . 2-14

Chapter 3 Creating and Modifying TablesCreating a New Table . . . . . . . . . . . . . . . . . . 3-3

ram Files\Adobe\FrameMaker8\UniData 7.2\7.2rebranded\SQL\SQLUTOC.fm (bookTOC.template)9 2010 11:30 am

Page 5: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Defining Attributes. . . . . . . . . . . . . . . . . . . 3-6Default Format and Conversion Codes . . . . . . . . . . . 3-7Defining Attribute Name . . . . . . . . . . . . . . . 3-7Defining Data Type . . . . . . . . . . . . . . . . . 3-8Defining Virtual Attributes. . . . . . . . . . . . . . . 3-11Defining Location . . . . . . . . . . . . . . . . . 3-12Defining Display Name. . . . . . . . . . . . . . . . 3-13Defining Format . . . . . . . . . . . . . . . . . . 3-13Defining Value Type. . . . . . . . . . . . . . . . . 3-15Defining Associations . . . . . . . . . . . . . . . . 3-16

Examining Table Definitions. . . . . . . . . . . . . . . . 3-19Modifying Table Definitions . . . . . . . . . . . . . . . . 3-21

ALTER TABLE Keywords. . . . . . . . . . . . . . . 3-21Adding Attributes . . . . . . . . . . . . . . . . . 3-22

Modifying Tables . . . . . . . . . . . . . . . . . . . 3-25Using the MODIFY Keyword . . . . . . . . . . . . . . 3-25Modifying Association Names . . . . . . . . . . . . . 3-25Modifying an Association . . . . . . . . . . . . . . . 3-26Deleting Attributes . . . . . . . . . . . . . . . . . 3-28Resizing Tables . . . . . . . . . . . . . . . . . . 3-30

Removing Tables . . . . . . . . . . . . . . . . . . . 3-31Indexing Tables . . . . . . . . . . . . . . . . . . . . 3-32

What Is Indexing? . . . . . . . . . . . . . . . . . 3-32Creating and Dropping Indexes . . . . . . . . . . . . . 3-32

Chapter 4 The Command StackIntroduction to the Command Stack . . . . . . . . . . . . . 4-3Using the Command Stack . . . . . . . . . . . . . . . . 4-4

Command Stack Operators. . . . . . . . . . . . . . . 4-4Appending to an Existing Statement . . . . . . . . . . . . 4-5Changing Statements in the Stack . . . . . . . . . . . . 4-6Deleting Statements in the Stack . . . . . . . . . . . . . 4-7Inserting a Statement Line into the Stack . . . . . . . . . . 4-8Listing Statements in the Stack . . . . . . . . . . . . . 4-9Recalling a Statement in the Stack . . . . . . . . . . . . 4-9Storing Statements for Later Use . . . . . . . . . . . . . 4-10

Chapter 5 Manipulating DataInserting Data into a Table . . . . . . . . . . . . . . . . 5-3

The INSERT Command . . . . . . . . . . . . . . . 5-3

Table of Contents v

Page 6: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

vi Usin

Inserting a Single Record . . . . . . . . . . . . . . . 5-4Inserting Data into Specified Attributes . . . . . . . . . . 5-5Inserting Empty Strings and the Null Value . . . . . . . . . 5-5Inserting a Record with Multiple Values . . . . . . . . . . 5-6Copying Multiple Records from Other Tables . . . . . . . . 5-8

Updating Data in a Table . . . . . . . . . . . . . . . . 5-10The UPDATE Command . . . . . . . . . . . . . . . 5-10Updating Specific Attributes. . . . . . . . . . . . . . 5-12Updating Multiple Records . . . . . . . . . . . . . . 5-12Updating Multivalued Attributes . . . . . . . . . . . . 5-12Adding Values and Subvalues . . . . . . . . . . . . . 5-13

Deleting Data from a Table . . . . . . . . . . . . . . . . 5-16The DELETE Command . . . . . . . . . . . . . . . 5-16Deleting a Set of Records. . . . . . . . . . . . . . . 5-18Deleting All Records in a Table . . . . . . . . . . . . . 5-19Deleting Data in Multivalued Attributes . . . . . . . . . . 5-19

Restoring the Database . . . . . . . . . . . . . . . . . 5-22

Chapter 6 The SELECT StatementRetrieving Data with SELECT. . . . . . . . . . . . . . . 6-5

Separation Characters . . . . . . . . . . . . . . . . 6-7Writing Simple Queries . . . . . . . . . . . . . . . . . 6-8

Selecting Rows from the Result Table . . . . . . . . . . . 6-8Selecting Specific Attributes. . . . . . . . . . . . . . 6-8Selecting All Attributes . . . . . . . . . . . . . . . 6-9Selecting or Excluding Duplicate Values . . . . . . . . . . 6-11Selecting Multivalued Attributes . . . . . . . . . . . . 6-12Selecting Multi-Subvalued Attributes . . . . . . . . . . . 6-13Selecting Virtual Attributes . . . . . . . . . . . . . . 6-14Selecting Records by Specifying Record IDs . . . . . . . . 6-15

Selecting Tables with FROM . . . . . . . . . . . . . . . 6-17Qualifying Attribute Names with Table Labels . . . . . . . . 6-17Joining Tables . . . . . . . . . . . . . . . . . . 6-18Types of Joins . . . . . . . . . . . . . . . . . . 6-19How to Join Tables. . . . . . . . . . . . . . . . . 6-20Inner Joins . . . . . . . . . . . . . . . . . . . 6-23Outer Joins . . . . . . . . . . . . . . . . . . . 6-26

Unnesting Query Results with UNNEST . . . . . . . . . . . 6-31How to Unnest . . . . . . . . . . . . . . . . . . 6-31Unnesting Multivalued Attributes . . . . . . . . . . . . 6-32

g UniData SQL

Page 7: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Unnesting Multi-Subvalued Attributes . . . . . . . . . . . 6-34Unnesting Multivalued and Multi-Subvalued Attributes . . . . . 6-36

Selecting Records with WHERE . . . . . . . . . . . . . . 6-40Using Greater Than in a WHERE Clause . . . . . . . . . . 6-41Combining Selection Criteria with AND . . . . . . . . . . 6-41Combining Selection Criteria with OR . . . . . . . . . . . 6-43Combining the AND and OR Operators . . . . . . . . . . 6-43Selecting Values That Do Not Meet Conditions . . . . . . . . 6-44Applying Conditions to Every Value. . . . . . . . . . . . 6-47Selecting Records That Match Patterns . . . . . . . . . . . 6-48Searching for Patterns with the LIKE Operator . . . . . . . . 6-49Using Range Specifiers . . . . . . . . . . . . . . . . 6-50Using Wild Cards in Patterns . . . . . . . . . . . . . . 6-51Dictionary Conversions and the LIKE Operator . . . . . . . . 6-52LIKE Clauses and Strings . . . . . . . . . . . . . . . 6-53Incorrect Pattern Specification . . . . . . . . . . . . . 6-53The IN Operator . . . . . . . . . . . . . . . . . . 6-54Selecting Records within a Range . . . . . . . . . . . . 6-55

Sorting Query Results . . . . . . . . . . . . . . . . . . 6-57Sorting in Ascending Order . . . . . . . . . . . . . . 6-57Sorting in Descending Order . . . . . . . . . . . . . . 6-58Sorting by Multiple Attributes . . . . . . . . . . . . . 6-58Combining Ascending and Descending Operators . . . . . . . 6-60Sorting Based on Multivalued Attributes . . . . . . . . . . 6-60Unnesting and Sorting Based on Multivalued Attributes . . . . . 6-61Unnesting an Association and Sorting . . . . . . . . . . . 6-62Sorting and Unnesting . . . . . . . . . . . . . . . . 6-62

Subqueries . . . . . . . . . . . . . . . . . . . . . 6-64Combining Multiple Queries into a Single Query. . . . . . . . 6-64Using ANY, ALL, and IN with Subqueries. . . . . . . . . . 6-65Writing Compound Queries . . . . . . . . . . . . . . 6-67Passing Data from Query to Subquery . . . . . . . . . . . 6-70

Group Functions . . . . . . . . . . . . . . . . . . . 6-71Selecting Summary Information from One Group . . . . . . . 6-71Multiple Group Functions . . . . . . . . . . . . . . . 6-75Correct and Incorrect Group Function Use . . . . . . . . . . 6-75Using DISTINCT and COUNT with Attributes . . . . . . . . 6-76Writing Column Headings . . . . . . . . . . . . . . . 6-76Selecting Summary Information from Multiple Groups . . . . . . 6-77

Table of Contents vii

Page 8: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

viii Usi

Including Multiple Attribute Names in a GROUP BY Clause . . . 6-78Specifying a Search Condition for Groups . . . . . . . . . 6-78Group Functions with Multivalued Attributes . . . . . . . . 6-81

Expressions and Functions . . . . . . . . . . . . . . . . 6-83Arithmetic Expressions . . . . . . . . . . . . . . . 6-83Arithmetic Functions . . . . . . . . . . . . . . . . 6-86Arithmetic Expressions and Functions in Group Functions . . . . 6-91Character String Functions . . . . . . . . . . . . . . 6-92Date Functions . . . . . . . . . . . . . . . . . . 6-99

Chapter 7 Creating and Querying ViewsWhat Is a View? . . . . . . . . . . . . . . . . . . . 7-3

How to Use Views . . . . . . . . . . . . . . . . . 7-3How View Queries Are Processed . . . . . . . . . . . . 7-3

Creating Views . . . . . . . . . . . . . . . . . . . 7-5Creating a View from a Single Table . . . . . . . . . . . 7-5Creating a View from Multiple Tables. . . . . . . . . . . 7-6Creating a View Using Expressions . . . . . . . . . . . 7-7Creating a View on a View . . . . . . . . . . . . . . 7-8

Querying Views . . . . . . . . . . . . . . . . . . . 7-9Optimizing Processing on View Queries . . . . . . . . . . 7-9

Dropping Views . . . . . . . . . . . . . . . . . . . 7-14

Chapter 8 Creating ReportsUnderstanding UniData SQL Reports . . . . . . . . . . . . 8-4Constructing Report Columns . . . . . . . . . . . . . . . 8-6

Using the COLUMN Command . . . . . . . . . . . . 8-6Setting Up Column Headings . . . . . . . . . . . . . 8-9Justifying Text in a Column Heading . . . . . . . . . . . 8-11Controlling Column Spacing . . . . . . . . . . . . . 8-11Controlling Spaces between Two Columns . . . . . . . . . 8-12Controlling Spaces Between Specific Columns . . . . . . . . 8-13

Formatting Report Columns . . . . . . . . . . . . . . . 8-14Copying a Format . . . . . . . . . . . . . . . . . 8-16Displaying Long Values . . . . . . . . . . . . . . . 8-16

Defining Report Titles . . . . . . . . . . . . . . . . . 8-19Turning Titles On or Off . . . . . . . . . . . . . . . 8-19Formatting Headers . . . . . . . . . . . . . . . . 8-19Formatting Footers . . . . . . . . . . . . . . . . . 8-23Including Attribute Values in Headers and Footers . . . . . . . 8-25

ng UniData SQL

Page 9: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Organizing Reports by Group . . . . . . . . . . . . . . . 8-28Creating Breaks in a Report . . . . . . . . . . . . . . 8-28

Performing Computations at Breaks . . . . . . . . . . . . . 8-32Computing Subtotals . . . . . . . . . . . . . . . . 8-33Executing Multiple Computations . . . . . . . . . . . . 8-34Computing a Grand Total . . . . . . . . . . . . . . . 8-35Displaying and Clearing Breaks and Computations . . . . . . . 8-36

Setting the Report Environment . . . . . . . . . . . . . . . 8-37Setting Report Parameters . . . . . . . . . . . . . . . 8-39Wrapping Text Vertically . . . . . . . . . . . . . . . 8-40Displaying Report Environment Parameters . . . . . . . . . 8-41

Preparing Complex Reports . . . . . . . . . . . . . . . . 8-42Producing a Complex Report . . . . . . . . . . . . . . 8-42

Chapter 9 Security and AdministrationUniData SQL Security. . . . . . . . . . . . . . . . . . 9-3Viewing Privileges . . . . . . . . . . . . . . . . . . . 9-4Granting Privileges. . . . . . . . . . . . . . . . . . . 9-7

GRANT . . . . . . . . . . . . . . . . . . . . 9-7Revoking Privileges . . . . . . . . . . . . . . . . . . 9-10

REVOKE . . . . . . . . . . . . . . . . . . . . 9-10Converting Files for UniData SQL . . . . . . . . . . . . . . 9-14

Requirements . . . . . . . . . . . . . . . . . . . 9-15CONVERT.SQL . . . . . . . . . . . . . . . . . . 9-16Converting Demo Tables . . . . . . . . . . . . . . . 9-18

Chapter 10 UniData SQL Transaction ProcessingBenefits of UniData SQL TP. . . . . . . . . . . . . . . . 10-4

ACID Properties . . . . . . . . . . . . . . . . . . 10-4UniData SQL TP and Other UniData Products . . . . . . . . . . 10-5

UniData SQL TP and RFS . . . . . . . . . . . . . . . 10-5UniData SQL TP and UniBasic . . . . . . . . . . . . . 10-5

Transaction Semantics. . . . . . . . . . . . . . . . . . 10-6Initiation . . . . . . . . . . . . . . . . . . . . 10-6Termination . . . . . . . . . . . . . . . . . . . 10-6

UniData SQL TP Locks . . . . . . . . . . . . . . . . . 10-7Other Types of Locks . . . . . . . . . . . . . . . . 10-7

Transaction Isolation . . . . . . . . . . . . . . . . . . 10-8Types of Transaction Errors . . . . . . . . . . . . . . 10-8UniData SQL Isolation Levels . . . . . . . . . . . . . 10-10

Table of Contents ix

Page 10: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

x Using

UniData SQL TP Commands . . . . . . . . . . . . . . . 10-15TP Commands . . . . . . . . . . . . . . . . . . 10-15Transaction-Initiating Commands . . . . . . . . . . . . 10-15Unsupported Commands . . . . . . . . . . . . . . . 10-15

SET DISPLAY TPMESSAGE. . . . . . . . . . . . . . . 10-17SET TRANSACTION . . . . . . . . . . . . . . . . . 10-19COMMIT . . . . . . . . . . . . . . . . . . . . . 10-21ROLLBACK . . . . . . . . . . . . . . . . . . . . 10-22AUTO COMMIT . . . . . . . . . . . . . . . . . . . 10-23LOCK TABLE . . . . . . . . . . . . . . . . . . . 10-25Examples of UniData SQL TP. . . . . . . . . . . . . . . 10-27

Example 1 – Read Committed vs. Repeatable Read . . . . . . 10-27Default Transaction Settings . . . . . . . . . . . . . . 10-29

Other UniData SQL TP Considerations . . . . . . . . . . . . 10-33System Administration . . . . . . . . . . . . . . . 10-33Performance . . . . . . . . . . . . . . . . . . . 10-34Interaction of UniData SQL with Other Transactional Environments . 10-35

Tips on Transactions . . . . . . . . . . . . . . . . . . 10-39Optimizing Performance . . . . . . . . . . . . . . . 10-39Limitations . . . . . . . . . . . . . . . . . . . 10-39

Chapter 11 UniData SQL and 1NF MappingTerminology . . . . . . . . . . . . . . . . . . . . 11-31NF Mapping . . . . . . . . . . . . . . . . . . . . 11-5

NF2 Data Model vs. 1NF Data Model . . . . . . . . . . . 11-5What Is a 1NF Mapping View? . . . . . . . . . . . . . 11-5

Subtables . . . . . . . . . . . . . . . . . . . . . 11-7Rules for Updating Subtables . . . . . . . . . . . . . 11-7Primary and Foreign Keys . . . . . . . . . . . . . . 11-8Creating Subtables . . . . . . . . . . . . . . . . . 11-10Creating Keys . . . . . . . . . . . . . . . . . . 11-12

Examples of Read-Only Mapping. . . . . . . . . . . . . . 11-14Creating a View for Singlevalued Attributes . . . . . . . . . 11-15Creating a View for the Multivalued Attribute . . . . . . . . 11-15Creating a View for Multivalued and Multi-Subvalued Attributes . . 11-16

Examples of Updatable Mapping . . . . . . . . . . . . . . 11-18Create a Nested Level 0 Subtable . . . . . . . . . . . . 11-18Create a Nested Level 1 Subtable . . . . . . . . . . . . 11-19Create a Nested Level 2 Subtable . . . . . . . . . . . . 11-20

Updatable Mapping Commands . . . . . . . . . . . . . . 11-22

UniData SQL

Page 11: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

CREATE SUBTABLE . . . . . . . . . . . . . . . . 11-22NLn_KEY . . . . . . . . . . . . . . . . . . . . 11-26DROP SUBTABLE . . . . . . . . . . . . . . . . . 11-28

Chapter 12 Null and Missing ValuesWhat Are Missing Values? . . . . . . . . . . . . . . . 12-2What Are Null Values? . . . . . . . . . . . . . . . . 12-3

Effects of Null and Missing Values in UniData SQL . . . . . . . . 12-5Null and Missing Values in ODBC . . . . . . . . . . . . . . 12-7Working with Null Values . . . . . . . . . . . . . . . . 12-9

Points to Remember . . . . . . . . . . . . . . . . . 12-9Examples . . . . . . . . . . . . . . . . . . . . 12-10

Appendix A UniData SQL Reserved WordsUsing Reserved Words . . . . . . . . . . . . . . . . . A-2List of Reserved Words . . . . . . . . . . . . . . . . . A-3

Appendix B More Table JoinsTables for Join Examples . . . . . . . . . . . . . . . . . B-2Examples of Outer Joins . . . . . . . . . . . . . . . . . B-3

Full Outer Join . . . . . . . . . . . . . . . . . . B-3Joining Tables on Attributes of the Same Name . . . . . . . . B-3Full Outer Join Combined with WHERE Condition . . . . . . . B-4Joining on Multivalued Attributes . . . . . . . . . . . . B-5Left Outer Join . . . . . . . . . . . . . . . . . . B-6Left Outer Join Combined with WHERE Condition . . . . . . . B-6Right Outer Join . . . . . . . . . . . . . . . . . . B-7Right Outer Join Combined with WHERE Condition . . . . . . B-7Joining Three Tables. . . . . . . . . . . . . . . . . B-8Joining Tables in a Subquery . . . . . . . . . . . . . . B-8Sorting Join Results . . . . . . . . . . . . . . . . . B-9Combining Results of Queries Containing Joins . . . . . . . . B-9Creating a View from Joined Tables . . . . . . . . . . . . B-10

Examples of Inner Joins . . . . . . . . . . . . . . . . . B-11Stacking JOIN Clauses . . . . . . . . . . . . . . . . B-12Combining Inner Join Results with UNION . . . . . . . . . B-12Creating a View from an Inner Join . . . . . . . . . . . . B-13

Table of Contents xi

Page 12: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

1Chapter

Introduction to UniData SQL

UniData SQL Commands Reference . . . . . . . . . . . 1-2 Additional Reading . . . . . . . . . . . . . . . . 1-2The UniData RDBMS . . . . . . . . . . . . . . . . . 1-3 Elements of the UniData Database . . . . . . . . . . . . 1-3UniData Demo Databases . . . . . . . . . . . . . . . . 1-4Overview of UniData SQL. . . . . . . . . . . . . . . . 1-5 Features of UniData SQL. . . . . . . . . . . . . . . 1-5Elements of UniData SQL . . . . . . . . . . . . . . . . 1-7 UniData SQL Tables . . . . . . . . . . . . . . . . 1-7 The SELECT Statement . . . . . . . . . . . . . . . 1-8 Multivalued Attributes . . . . . . . . . . . . . . . 1-9 Associations . . . . . . . . . . . . . . . . . . . 1-9 Unnesting Multivalued Attributes . . . . . . . . . . . . 1-9The UniData Dictionary . . . . . . . . . . . . . . . . 1-10 Elements of Dictionary Records . . . . . . . . . . . . 1-10

Page 13: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Using UniData SQL shows you how to use the UniData implementation of Struc-tured Query Language (SQL). UniData SQL is a query language that enables you to interact with a UniData database to organize, manage, and retrieve data stored in a database.

This chapter presents an overview of the UniData SQL product. It defines database elements and introduces the unique concepts UniData uses to implement SQL with the Non-First Normal Form data model.

By the time you complete this chapter, you should be able to do the following:

Understand the UniData RDBMS.Identify the basic components of UniData SQL.Understand UniData dictionaries.

UniData SQL Commands ReferenceAs you go through each chapter in this manual, you will find references to the UniData SQL Commands Reference, which contains detailed information about each of the UniData SQL commands. Be sure to keep this reference guide handy.

Additional ReadingThis manual assumes you are familiar with basic computer, operating, and SQL concepts. If you are a beginning user, you may want to refer to the following reading materials before using UniData SQL:

For operating system information, see your operating system guide, or see Administering UniData.

1-2

Page 14: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The UniData RDBMS UniData is a relational database management system (RDBMS) that enables you to easily design and build a database and create reports. It also allows ad hoc queries and provides exceptional performance.

UniData’s technology is based on the nested relational database model. The nested relational model extends the standard relational model from a redundant, flat-table structure to a three-dimensional database.

UniData uses several access methods to store, manipulate, and report data. UniData SQL is a query language for defining and manipulating data. It contains two elements:

A language for defining the structures and integrity constraints of your database, known as the data definition language (DDL).A language for declaring procedures and executable statements for opera-tions on the database, known as the data manipulation language (DML).

Elements of the UniData DatabaseThe UniData database and other relational databases consist of several components that start with basic elements and build on them to form more complex elements. See Using UniData for more detailed descriptions of these relational database compo-nents. The terms for these components are:

RecordPrimary KeyAttributeTupleTableDatabase

1-3 Using UniData SQL

Page 15: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

UniData Demo DatabasesThere are two sample databases that this manual uses for example purposes. These sample databases are located in your UniData system on the Unidata installation media. This manual draws all of its examples from these sample databases.

Video ClassicsUniversity

The Video Classics database contains records for a videotape rental store called Video Classics. This database organizes its customer and inventory information to include:

Tapes in circulation.Tapes available for rent.Customer data (such as where the customers live, how old they are, and what kind of tapes they like and have checked out).Accounting information (such as daily, weekly, monthly, and yearly store income).

The University database provides information most universities would use to keep track of students and staff. This database organizes the following types of student and staff information:

Students’ majors and minors.Students’ courses and grades.Teachers’ names, titles, and courses they are teaching.

1-4

Page 16: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Overview of UniData SQLUniData SQL is an implementation of SQL. This standard, nonprocedural language enables you to create, access, and manipulate data across relational databases.

Features of UniData SQLThe following sections describe the main features of UniData SQL.

Defining and Manipulating Data

UniData SQL implements the SQL data definition language (SQL-DDL) and the data manipulation language (SQL-DML). The differences between each are:

The data definition language (SQL-DDL) enables you to define or change the structure of your database, and establish and maintain the integrity constraints for your database using the commands in the following list.

CREATE TABLE DROP INDEX

ALTER TABLE GRANT

DROP TABLE REVOKE

CREATE INDEX

The data manipulation language (SQL-DML) enables you to query and modify data, but not change the structure of the data that’s stored in your database, using the commands in the following list.

SELECT UPDATE

INSERT DELETE

Note: UniData SQL commands are not case-sensitive. You can enter UniData SQL commands in either uppercase or lowercase letters.

1-5 Using UniData SQL

Page 17: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The Vocabulary Table

UniData supports its own account structure with a unique local repository called the vocabulary file, or VOC. This file is the backbone of the system. It is a dictionary, sometimes called the master dictionary, that contains a reference to virtually all UniData files, commands, and processes. This file forms part of the data definition environment and supporting features that are not available in other systems.

See Using UniData for specific information regarding setting up and using the VOC file.

Additional Highlights

UniData SQL also enables you to do a variety of other functions:

Supports joins between tables.Enables you to nest queries.Provides increased security of data through privileges and views.Enables extensive report formatting.Enables you to access UniData SQL from UniBasic by using the EXECUTESQL command.Enables you to work with third-party desktop tools.

These highlights are discussed in detail in the chapters that follow.

1-6

Page 18: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Elements of UniData SQL

UniData SQL TablesA table is a collection of interrelated attributes. Attributes become more meaningful once they are related in a table. For example, a name has little meaning by itself, but when you relate a name to other attributes like address, date of birth, and sex, you have a single relation that describes a human being. So, you need to combine a set of attributes together in a single table or “relation” to define a complex entity.

For example, in the video store database, the data for a customer is dependent on a set of information rather than on a single piece of information; Harry Smith is a man living at 1414 W. 8th in the state of California, and he was born March 13, 1952. The CUSTOMER table in this database is actually a relation of certain attributes that define a customer. Such a relation appears in the following table.

Example of a Table

Tip: In UniData SQL, the term “table” is synonymous with the term “file.”

COLUMNS

ROWSHarry Smith

Bonnie Partner

Carrie Fischer

Dick Barrie

Name Address

1414 W. 8th

19th & Elm

640 E. Evans

2112 S. Florida

Englewood

Golden

Arvada

Lakewood

City

(Records,Tuples)

(Attributes, Fields)

1-7 Using UniData SQL

Page 19: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The SELECT StatementTo retrieve data from your database in UniData SQL, you must use SELECT state-ments. The SELECT statement is the foundation of the SQL language. A SELECT statement can be simple or complex; it looks very much like an English sentence.

For example, the following SELECT statement tells UniData to retrieve the names of the customers in the database:

sql>SELECT NAME FROM CUSTOMER;Page 1Customer Name---------------Jones, BobFrobisher,KamalSteven SpenderJamieson, DaleChase, Carl

You can embellish the SELECT statement to retrieve more data from your database by using UniData SQL clauses, like the WHERE clause.

For example, in the following statement, the WHERE clause directs UniData to a table that meets specific criteria. In addition, the ORDER BY clause sorts the result of the SELECT statement by placing the customer names in alphabetic order.

sql> SELECT NAME FROM CUSTOMER ORDER BY NAME ASC;Page 1Customer Name---------------Barrie, DickBelafonte, HarryBest, GeorgeBoorman, RickBowie, DavidByles, Marcy...

Tip: When you enter a SELECT statement, it may help you to keep track of different clauses if you put each clause on a separate line. In UniData SQL, until you place a semicolon (;) at the end of the statement, you can press ENTER without executing the statement.

1-8

Page 20: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Multivalued AttributesUniData employs a record concept that supports multivalued attributes. A multi-valued attribute is an attribute that usually consists of multiple tuples or rows. Within a record, such as a customer record, you can have:

An attribute for NAME that is singlevalued (since a customer has only one name).An attribute for TAPES_RENTED that is multivalued (since a customer can rent more than one tape).

This use of multiple rows within an attribute is one of the things that extends the UniData capabilities beyond the First Normal Form (1NF) database. UniData allows multiple rows within a record.

AssociationsAn association is a connection between two or more attributes. A UniData table or file contains logical records that can have simple or complex attributes. A simple attribute is one that is not associated with any other attribute. A complex attribute is one that UniData uses in association with several other attributes; it identifies a connection between two or more attributes.

Unnesting Multivalued AttributesYou can view data stored in multivalued attributes as independent rows or tuples if they are stored in conjunction with a single record. To view data in an unnested format, use the UniData SQL UNNEST keyword. When UniData SQL displays data with an UNNEST keyword, it repeats the name of the attribute with each value. This is equivalent to other commercial SQL-based relational databases.

1-9 Using UniData SQL

Page 21: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The UniData DictionaryA dictionary is a set of records that defines the records in the data table. A dictionary provides UniData processes with the information necessary to add, display, or change data in the database. UniData SQL generates reports by referencing the dictionary when you enter a SELECT statement.

Elements of Dictionary RecordsDictionaries contain descriptive information about the nature of the records that make up tables. The CUSTOMER table, for example, contains almost 30 kinds of records or attributes. The dictionary for the CUSTOMER table provides details about each kind of record in dictionary records that are also called attributes. Dictionaries contain attribute records, and each dictionary attribute contains attributes that describe how UniData must view it.

The following table lists the attributes that describe a dictionary attribute.

Attribute

Number Name Description

0 @ID ID

The name of the attribute being described; also known as the primary key.

1 Type Type of attribute being described. Possible values are:• D (Data) • V (or I) (Formula) • PH or ASSOC (Phrase) • X (User-defined)

2 Location or Formula If D-type: Attribute 2 contains a number to identify the location of the attribute within the table.If V-type: Attribute 2 contains a formula.If PH- or ASSOC-type: Attribute 2 contains the names of the attributes that are associated.If X-type: Attribute 2 contains any user-defined infor-mation that UniData ignores.

Dictionary Attributes

1-10

Page 22: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

See Using UniData for detailed information on setting up and using UniData dictionaries.

3 Conversion A code that converts data (like dates and times) between internal format and external (display) format.

4 Display Name The column heading used by UniData SQL to display the data attribute in a report.

5 Display Format

The number of spaces the display requires and the line justification.

6 Value Code Type A code for the attribute value:• S – Singlevalued; limits the attribute to one atomic value.• MV – Multivalued; allows multiple values.• MS – Multi-subvalued; allows multiple subvalued values.

7 Association The name of an association of multivalued and multi-subvalued attributes.

Attribute

Dictionary Attributes (continued)

1-11 Using UniData SQL

Page 23: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

2Chapter

Getting Started

Starting UniData SQL . . . . . . . . . . . . . . . . . 2-4Creating a Table . . . . . . . . . . . . . . . . . . . 2-7Inserting Data into a Table . . . . . . . . . . . . . . . . 2-8Updating Data in a Table . . . . . . . . . . . . . . . . 2-9Deleting Data from a Table . . . . . . . . . . . . . . . 2-10Selecting Data from a Table . . . . . . . . . . . . . . . 2-11Removing Tables. . . . . . . . . . . . . . . . . . . 2-12Exporting Selected Data to a Sequential File . . . . . . . . . . 2-13Exporting Selected Data to a Temporary Table . . . . . . . . . 2-14

Page 24: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

This chapter introduces you to the primary statements and functions of UniData SQL and gives you hands-on practice using UniData SQL statements. Experienced UniData SQL users may want to skip this chapter.

You can enter a UniData SQL statement on one or more lines as long as the last line of the statement ends with a semicolon (;). In this manual, statements may appear on several lines to make them easier to read.

This chapter introduces you to UniData SQL; detailed explanations of the topics introduced here appear in the chapters that follow.

The examples throughout this manual use tables in the demo databases that are provided with the UniData RBMS, and are located on your system in udthome/demo on UniData for UNIX, or udthome\demo on UniData for Windows Platforms. The UniData files have been converted with the ECL command CONVERT.SQL so that table and attribute names are ODBC-compliant. Converted files such as these are called base tables.

The databases contain the following data tables.

Data Tables in Demo Tables

Video Classics UniVersity

CUSTOMER STUDENT

TAPES STAFF

CATEGORIES COURSES

Note: If you are not familiar with the login procedures of your computer system or with the basic functions of UniData, see your system administrator. For a brief overview of database management and UniData SQL, see Chapter 1, “Introduction to UniData SQL,” or see Administering UniData. For an in-depth examination of the various tools available to build applications, as well as alternatives to structuring your database scheme, see Using UniData.

By the time you complete this chapter, you should be able to do the following:

Start UniData SQL.Create a table.Insert, update, and delete data in a table.Select data from a table.

2-2 Using UniData SQL

Page 25: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Drop a table.Export selected data to a sequential file.Export selected data to a temporary table.End a UniData SQL session.

2-3

Page 26: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Starting UniData SQLBefore you use UniData SQL, go to the UniData home directory where you installed UniData. From there, change your directory to the demo account or ask your system administrator to place you in the appropriate directory. All the database tables used in the examples in this manual are in the demo directory under your UniData home account. See your system administrator for information on your home account, or see Administering UniData.

When you are in the demo directory, one of the following prompts appears on your screen.

System Prompts

Prompt Description

: UniData colon prompt

% or $ UNIX shell prompt

To start UniData SQL, enter sql at the system prompt. This invokes the UniData SQL statement processor. The UniData SQL prompt appears on your screen, as follows:

:sqlsql>

From the UniData SQL prompt, you can enter any UniData SQL statement.

Note: If you attempt to enter UniData SQL and receive the error message “No UniData SQL privilege file in this account, creating privilege

file,” or if you successfully enter UniData SQL, but find you are unable to use the SELECT statement to retrieve table information from the demo database, contact your system administrator or see Chapter 9, “Security and Administration,” for information on properly configuring your system to enable you to access the demo database.

Methods for Starting UniData SQLYou can enter UniData SQL in any of the following ways:

Start from the UniData environment.Start from the UniData SQL prompt.

2-4 Using UniData SQL

Page 27: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Code EXECUTESQL statements in UniBasic programs. For further infor-mation, see the UniBasic Commands Reference.Submit SQL statements from the UniDesktop environment. For further information, see Developing UniData ODBC Applications, Developing UniData ObjectCall Applications, or Developing UniOLEDB Applications.Execute stand-alone UniData SQL statements using the UniBasic EXECUTE command.Execute stand-alone UniData SQL statements in UniData.Execute stand-alone UniData SQL statements in paragraphs.

UniData SQL Statements and the EXECUTE Command

The following example shows how to code a UniData SQL statement in a UniBasic program using the EXECUTE command. As you use this statement, notice that the error messages are captured into the string variable ERR_VAR: EXECUTE "SQL SELECT * FROM STUDENT;" RETURNING ERR_VAR

Note: It is important to note differences in the way the EXECUTESQL and EXECUTE commands function. The EXECUTESQL command can direct the output to a file. The READNEXTTUPLE command can later use the output so an application can go through the result set, record by record. The EXECUTE command can direct the result to the screen only, but it contains a set of options not found in EXECUTESQL, such as CAPTURING and RETURNING.

For further information concerning EXECUTE and EXECUTESQL, see the UniBasic Commands Reference.

UniData SQL Statements in UniData

The following example shows how to execute a stand-alone UniData SQL statement in the UniData environment: SQL SELECT NAME,COURSE_NAME FROM STUDENT;

2-5

Page 28: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

UniData SQL Statements in Paragraphs

The following example shows a paragraph that contains UniData SQL statements. Notice that the system executes each UniData SQL statement separately, and upon completion, the UniData environment regains control, which in turn, initiates execution of the next UniData SQL statement in the paragraph. However, all the options set during the execution of the previous UniData SQL statement remain in effect when the next UniData SQL statement is executed. In this example, both TTITLE options stay in effect for the execution of the SELECT statement.

ID: SAMPLE PARAGRAPH<1>:PA Example of using UniData SQL statements in a paragraph<2>:SQL TTITLE ON<3>:SQL TTITLE "Student Records"<4>:SQL SELECT * FROM STUDENT;<5>:IF @SYSTEM.RETURN.CODE>=0 THEN GO OK<6>:DISPLAY BAD<7>:GO FINI<8>:OK:DISPLAY OK<9>:FINI:DISPLAY END

2-6 Using UniData SQL

Page 29: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Creating a TableTo create a table, use the CREATE TABLE statement. This statement has two purposes:

To set up a table in your database.To define the properties of attributes in the table dictionary.

The following example demonstrates how to use CREATE TABLE to create the ST_EXAM table:

sql> CREATE TABLE ST_EXAMsql> (LNAME CHAR(15),sql> FNAME CHAR(15), sql> COURSE_NBR CHAR(5),sql> COURSE_GRD CHAR(1)) MODULO 1;Create file D_ST_EXAM, modulo/1,blocksize/1024Hash type = 0Create file ST_EXAM, modulo/1,blocksize/1024Hash type = 0Added "@ID", the default record for UniData to DICT ST_EXAM. 4 fields added. Create file ST_EXAM, modulo/1,blocksize/1024

For further information on creating tables, see Chapter 3, “Creating and Modifying Tables.” You can use other UniData tools (such as UniEntry or a UniBasic program) to enter data into tables. For further information about these tools, see Using UniData, the UniData Commands Reference, the UniBasic Commands Reference, or Developing UniBasic Applications.

2-7

Page 30: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Inserting Data into a TableTo add data to an existing table, use the INSERT command.

The following example demonstrates how to use an INSERT statement to add a record to the COURSES table:

sql> INSERT INTO COURSES sql> VALUES ("CS505","Advanced Programming",5,sql> "Gibson");COMMIT complete.1 record(s) created.

For further information on the INSERT statement, see Chapter 5, “Manipulating Data.”

2-8 Using UniData SQL

Page 31: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Updating Data in a TableTo modify data in a database, use the UPDATE statement.

For example, Mr. Codd is replacing Mr. Gibson as instructor for course CS505. You use the UPDATE statement to make the change in the COURSES table:

sql> UPDATE COURSES sql> SET TEACHER = "Codd" sql> WHERE @ID = "CS505";COMMIT complete.1 record(s) updated.

For further information on the UPDATE statement, see Chapter 5, “Manipulating Data.”

2-9

Page 32: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Deleting Data from a TableTo eliminate a record from a table, use the DELETE statement.

For example, the Computer Science Department no longer offers course CS505. Use the DELETE statement to eliminate this record from COURSES:

sql>DELETE FROM COURSES sql>WHERE @ID = "CS505";COMMIT complete.1 record(s) deleted or updated.

For further information on the DELETE statement, see Chapter 5, “Manipulating Data.”

2-10 Using UniData SQL

Page 33: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Selecting Data from a TableThe primary UniData SQL statement, SELECT, enables you to query your database. In its simplest form, SELECT has two parts:

The SELECT clause, which specifies the attributes to access.The FROM clause, which identifies the table(s) in which the data resides.

Note: Every SELECT statement must contain both the SELECT and FROM clauses. Also remember, all UniData SQL queries must end with a semicolon (;)

The following SELECT statement displays data from the COURSES table:

sql> SELECT @ID,NAME,CREDITS,TEACHER FROM COURSES;Page 1COURSES Course Name Credi Teacher---------- ------------------------- ----- ----------FA120 Finger Painting 5 FriedPY140 Abnornal Psychology 5 MastersPE100 Golf - I 3 FisherCS105 Database Design 3 GibsonMA101 Math Principals 3 OtisFA231 Photography Practicum 3 FriedPE220 Racquetball 3 FisherMA221 Calculus - II 5 OtisEG110 Engineering Principles 5 CarnesFA121 Watercorlors 3 CarnesEG140 Fluid Mechanics 3 AaronCS130 Intro to Operating 5 James SystemsHY101 Western Civilization 3 OtisCS100 Intro to Computer Science 3 Gibson...24 records listed

The report or list created by a SELECT statement is called the result table. Additional clauses, such as WHERE and HAVING, may further restrict the rows displayed from this result table.

For further information on the SELECT statement, see Chapter 6, “The SELECT Statement.”

2-11

Page 34: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Removing TablesWhen you no longer need a table, you can use the DROP TABLE statement to remove it from the database.

Warning: You cannot recover a dropped table. Once UniData SQL drops a table, the data in it is lost forever. Before you use this statement, make sure you will not lose data you intend to retain. For information on temporarily storing the data before issuing a DROP TABLE statement, see Chapter 5, “Manipulating Data.”

In the following example, ST_EXAM is removed:

sql> DROP TABLE ST_EXAM;Do you really want to delete file ST_EXAM?(y/n):yDeleting file D_ST_EXAM.Deleting file ST_EXAM.

For further information on removing a table, see Chapter 3, “Creating and Modifying Tables.”

2-12 Using UniData SQL

Page 35: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Exporting Selected Data to a Sequential FileIt is sometimes convenient to send the results of a query to a sequential file for these results to be used by other utilities and programs outside the UniData environment. In UniData SQL, you can use the TO keyword in a SELECT statement to do this. Using the TO keyword always requires a filename. You can also specify a pathname for the results file.

Note: UniData SQL does not apply conversion or formatting attributes to data output to a file.

The following example shows you how to send the result of the following SELECT statement to a sequential file named SAVED in the current directory:

sql>SELECT NAME,ADDRESS,CITY,STATE,ZIP,PHONEsql>FROM CUSTOMER sql>TO SAVED;

The next example shows you how to send the result of the SELECT statement shown in the previous example to a file residing in a different directory by specifying the UNIX pathname.

sql>SELECT NAME,ADDRESS,CITY,STATE,ZIP,PHONEsql>FROM CUSTOMER sql>TO /usr/ud72/myaccount/results/SAVED;

If you are using a Windows platform, you would instead specify a path such as the following:

sql>TO D:\UniData72\myaccount\results\saved

2-13

Page 36: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Exporting Selected Data to a Temporary TableIt is sometimes convenient to save the results of a query to a temporary table that can then be used in other SELECT statements. In UniData SQL, you can use the INTO keyword in a SELECT statement to do this. As an example, you may want to use a temporary table to take a snapshot of a subset of a large UniData table and perform calculations on that subset rather than accessing the larger table. As another example, you may find it difficult or impossible to formulate a report using only one UniData SQL statement. In this case, you can first collect some intermediate data into a temporary table, then issue a SELECT statement against the temporary table to achieve desired results.

Note: UniData SQL drops temporary tables when you exit UniData SQL.

The following example shows you how to collect some intermediate data to a temporary table named INTERMEDIATE:

sql>SELECT NAME,ADDRESS,CITY,STATE,ZIP,PHONEsql>FROM CUSTOMER WHERE CITY = 'Denver' sql>INTO INTERMEDIATE;

2-14 Using UniData SQL

Page 37: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

3Chapter

Creating and Modifying Tables

Creating a New Table . . . . . . . . . . . . . . . . . 3-4Defining Attributes . . . . . . . . . . . . . . . . . . 3-7 Default Format and Conversion Codes . . . . . . . . . . 3-8 Defining Attribute Name . . . . . . . . . . . . . . . 3-8 Defining Data Type . . . . . . . . . . . . . . . . 3-9 Defining Virtual Attributes . . . . . . . . . . . . . . 3-12 Defining Location . . . . . . . . . . . . . . . . . 3-13 Defining Display Name . . . . . . . . . . . . . . . 3-14 Defining Format . . . . . . . . . . . . . . . . . 3-14 Defining Value Type . . . . . . . . . . . . . . . . 3-16 Defining Associations . . . . . . . . . . . . . . . . 3-17Examining Table Definitions . . . . . . . . . . . . . . . 3-20Modifying Table Definitions . . . . . . . . . . . . . . . 3-22 ALTER TABLE Keywords . . . . . . . . . . . . . . 3-22 Adding Attributes . . . . . . . . . . . . . . . . . 3-23Modifying Tables . . . . . . . . . . . . . . . . . . 3-26 Using the MODIFY Keyword . . . . . . . . . . . . . 3-26 Modifying Association Names . . . . . . . . . . . . . 3-26 Modifying an Association . . . . . . . . . . . . . . 3-27 Deleting Attributes . . . . . . . . . . . . . . . . . 3-29 Resizing Tables . . . . . . . . . . . . . . . . . . 3-31Removing Tables. . . . . . . . . . . . . . . . . . . 3-32Indexing Tables . . . . . . . . . . . . . . . . . . . 3-33 What Is Indexing? . . . . . . . . . . . . . . . . . 3-33 Creating and Dropping Indexes . . . . . . . . . . . . . 3-33

Page 38: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

This chapter describes how to create tables and modify table definitions in UniData SQL by using the UniData SQL statements CREATE TABLE and ALTER TABLE.

By the time you complete this chapter, you should be able to do the following:

Create a new table.Define attributes.Modify table definitions.Remove tables.Create indexes for tables.

3-2 Using UniData SQL

Page 39: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Creating a New TableThe CREATE TABLE statement has two purposes:

To set up a table in your database.To define the properties of attributes in the table dictionary.

After you complete the database design, creating tables is the first step in building the database. Once you create a table and define the attributes, you can use a UniData SQL INSERT statement to enter data into the database table.

Tip: You can use other UniData tools, such as UniEntry or a UniBasic program, to enter data into tables. For further information about these tools, see Using UniData, the UniData Commands Reference, the UniBasic Commands Reference, and Developing UniBasic Applications.

The CREATE TABLE command performs two functions:

Creates a new base table in your database.Stores the attribute definitions in the table’s dictionary.

UniData SQL automatically creates the @ID, or primary key, as a singlevalued attribute at location 0 in the table’s dictionary. For further information about the dictionary structure, see Using UniData.

Note: If quotation marks are included in the definition, use single quotation marks in embedded definitions; for example: "TRANS('clients',client_nbr, 'client','X')".

Syntax:CREATE TABLE table_name (attribute_definition[,attribute_definition]...) [MODULO modulo_number] [DYNAMIC [KEYONLY | KEYDATA]] [TRANSACTION | RECOVERABLE]

3-3

Page 40: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

attribute_definition syntax:

attribute_name {CHAR(size[,“conv_code”]) | DATE[({“date_conv” | “time_conv”})] | NUMBER[({size | size,n | *}[,“conv_code”])] | LONG] [IDESC | VIRTUAL (“virt_definition”)] [LOC(n)] [DISP(“display_name”)] [FORMAT(“fmt_desc”)] [SM(“{S | MV | MS}”)] [ASSOC(“assoc_name”)]

The parameters for the CREATE TABLE command are described in the following sections and in the UniData SQL Commands Reference.

ExamplesThe following statement creates a table, NEW_TAB, that has three attributes: a character field and two numeric fields. The numeric attribute MONEY_FLD contains a conversion code that formats dollars with two decimal places and prefixes negative numbers with a minus sign (-).

sql> CREATE TABLE NEW_TABsql> (NUM_FLD NUMBER,sql> CHAR_FLD CHAR(10),sql> MONEY_FLD NUMBER(10,"MD2$,-")); 3 attribute(s) added. Create file NEW_TAB, modulo/1,blocksize/1024

The following statement lists the dictionary entry for this table:

sql> LISTDICT NEW_TAB;

Page 1@ID TYP LOC CONV NAME FORMAT SM ASSOC--------------- --- ------------- ---- --------------- ------ -- ----------@ID D 0 NEW_TAB 10L SNUM_FLD D 1 10R SCHAR_FLD D 2 10L SMONEY_FLD D 3 MD2$ 10R S ,-4 records listed

3-4 Using UniData SQL

Page 41: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The next statement creates a table that has the following attributes:

CHAR_FLD – Data type character, length of 5.DATE_FLD – Data type date, formatted as mm/dd/yy.NUM_FLD – Data type numeric, formatted with preceding dollar sign; including two decimal places.CHAR2_FLD – Data type character, length of 12, centered within a column 25 characters wide.

sql> CREATE TABLE TEST_TAB (CHAR_FLD CHAR(5), DATE_FLD DATE("D2/"),sql> NUM_FLD NUMBER(15,"MD2$"), CHAR2_FLD CHAR(12) FORMAT("25C")); 4 attribute(s) added. Create file TEST_TAB, modulo/1,blocksize/1024

The following example creates a table that contains a virtual field, VIRT_FLD, which displays the results of multiplying NUM_FLD and MONEY_FLD:

sql> CREATE TABLE NEW_TABsql> (NUM_FLD NUMBER, sql> CHAR_FLD CHAR(10),sql> MONEY_FLD NUMBER(10,"MD2$,-"),sql> VIRT_FLD NUMBER VIRTUAL("NUM_FLD * MONEY_FLD")); 4 attribute(s) added. Create file NEW_TAB, modulo/1,blocksize/1024

sql> LISTDICT NEW_TAB;Page 1@ID TYP LOC CONV NAME FORMAT SM ASSOC--------------- --- ------------- ---- --------------- ------ -- ----------@ID D 0 NEW_TAB 10L SNUM_FLD D 1 10R SCHAR_FLD D 2 10L SMONEY_FLD D 3 MD2$ 10R S ,-VIRT_FLD V NUM_FLD * MON 10R S EY_FLD5 records listed

3-5

Page 42: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Defining AttributesYou define attributes when you create a table with the CREATE TABLE command or change a table with the ALTER TABLE command. This section explains how to define an attribute when the UniData SQL syntax indicates attribute_definition.

Attribute definitions consist of the following elements:

Attribute name (required)Data type (required)Location Virtual attribute descriptionDisplay nameFormatValue type specificationAssociation description

The attribute name and data type are required. You must enter the attribute name first and the data type second. The other elements are optional and you can enter them in any order. The elements are described later in this chapter.

3-6 Using UniData SQL

Page 43: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Default Format and Conversion CodesWhen you define an attribute with the CREATE TABLE or ALTER TABLE command, the following default conversion codes and formats are applied if you do not specify a different conversion code or format. These conversion codes and formats control the way in which attribute values are displayed. Conversion is applied first, then format.

Default Attribute Display Format

Data TypeDefault Conversion

Default Format What is Displayed

character(x) none xL x characters wide, left-justified

date D2/ 10L 10 characters wide, left-justified, MM/DD/YY

number none 10R 10 digits wide, right-justified

long none 10R 10 digits wide, right-justified

Syntax:attribute_name {CHAR(size[,“conv_code”]) | DATE[({“date_conv” | “time_conv”})] | NUMBER[({size | size,n | *}[,“conv_code”])] | LONG] [IDESC | VIRTUAL (“virt_definition”)] [LOC(n)] [DISP(“display_name”)] [FORMAT(“fmt_desc”)] [SM(“{S | MV | MS}”)] [ASSOC(“assoc_name”)]

Defining Attribute NameYou must assign an attribute name when you define a new attribute. The following restrictions apply to attribute names:

3-7

Page 44: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Valid attribute names can contain the following types of characters:Alphabetic charactersNumbersSpecial characters: “_”, “@”, “#”, and “$”

The first character of an attribute name must be an alphabetic character, underscore (_), or at symbol (@).If you plan to access the data in a table, subtable, or view via ODBC, do not use @, #, or $ anywhere in the attribute name, and do not use an underscore (_) as the first character.An attribute name can be no longer than 30 characters.The name cannot be a UniData SQL reserved word.The name must be unique among attribute names within the table, subtable, or view.

Defining Data TypeData type describes the type of values that the attribute contains. You can specify four data types:

CHARDATENUMBERLONG

Syntax:{CHAR(size[,“conv_code”]) | DATE[({“date_conv” | “conv_code”})] | NUMBER[({size | size,n | *}[,“conv_code”])] | LONG]

You can enter any type of data into any attribute; however, be careful when you store a different type of data in an attribute than is indicated by the data type for that attribute. If a conversion is specified, it may produce unexpected results. Also, be aware that changing the data type for an attribute in some cases results in a different display of the data than originally intended.

3-8 Using UniData SQL

Page 45: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

You can also establish a FORMAT or conversion code that contradicts the data type. If the format or conversion is inappropriate for the data values contained in the attribute, it is ignored.

Note: Data type is optional for ALTER TABLE MODIFY.

CHAR

The CHAR data type tells UniData SQL that a particular attribute contains character string data.

Syntax:

CHAR(length[,“conv_code”])

length is the length of the character string in display format, including the mask. Length is a required parameter.

For an explanation of conv_code, see the options available for the UniBasic OCONV function in the UniBasic Commands Reference.

DATE

Use the DATE specification to tell UniData SQL that the attribute contains either date or time values. UniData stores a date as a single integer with 0 representing December 31, 1967, and 1 representing January 1, 1968, and so on. Negative numbers represent dates before December 31, 1967. UniData stores time as an integer between 0 and 86400 (seconds since midnight). Some points to remember about DATE data type:

Time – To specify time data type, use the DATE data type and conv_code MT. Negative input and numbers greater than 86,400 are invalid for time data-type attributes.Data Entry – Unless the date or time is enclosed in quotation marks, UniData assumes that it is an integer being entered in internal format. Defaults – The default format for a DATE data-type attribute is 10 characters, left-justified. Default conversion is “D2/”.

Syntax:

DATE[(“date_conv”)]

3-9

Page 46: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

For an explanation of date_conv, see the options available for the UniBasic OCONV function in the UniBasic Commands Reference.

NUMBER

The NUMBER specification tells UniData SQL how to convert input numeric values to the internal format and how to display the numeric values on output. When entering data, do not enclose data to be stored in numeric attributes in quotation marks.

Syntax:

NUMBER[({length | length,n | *} [,conv_code])]

Note: If you define an attribute as NUMBER or LONG, but specify a format of 10L (which implies CHAR data type) the attribute is considered to be CHAR, and attempts to perform arithmetic functions on that attribute result in the error “Invalid function on character field.”

Parameters

The following table describes each parameter of the syntax.

NUMBER Parameters

Parameter Description

length Column width.

n Specifies the number of decimal places to include in the formatted number.

* Uses the default column width of 10 digits.

conv_code For an explanation of conv_code, see the options available for the UniBasic OCONV function in the UniBasic Commands Reference.

Warning: Be aware that altering the num_conv or format for a numeric attribute could affect the values when they are displayed. For example, if you remove an MD2 formatting code, the decimal is no longer inserted when the data is retrieved, effectively multiplying the value by 100.

3-10 Using UniData SQL

Page 47: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

LONG

LONG describes an attribute that can hold numeric data. Although UniData SQL does not limit the size of an attribute, some systems do. The LONG description is provided for compatibility with other systems. The LONG data type has no options. When entering data, do not enclose data to be stored in numeric attributes in quotation marks.

The default format for a LONG data-type attribute is 10 digits, right-justified. No default conversion is performed on numbers.

Syntax:

LONG

Warning: Be aware that altering the conversion for a numeric attribute could affect the values stored. For example, if you remove an MD2 formatting code, the decimal point is no longer inserted when the data is retrieved, effectively multiplying the value by 100.

Defining Virtual AttributesA virtual attribute is a dictionary record definition that executes a formula to derive its value each time the attribute is retrieved.

Syntax:[IDESC | VIRTUAL] (“virt_definition”)

The IDESC or VIRTUAL keyword follows the data type keyword. The formula can be an expression, function, or UniBasic subroutine. For instructions on writing virtual attributes, see Using UniData.

You must enclose virtual attribute definitions in quotation marks.

The following example defines a virtual attribute that yields the due date for a tape. (DATE_DUE is the second day following the rental date.)

sql> CREATE TABLE EXAM (NAME CHAR(5), DATE_OUT DATE, sql> DATE_DUE DATE VIRTUAL ("DATE_OUT+2"));

3 fields added.Create file EXAM, modulo/1,blocksize/1024

3-11

Page 48: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

You must enclose virtual attribute descriptions in quotation marks, and you must enter them on one line. The text can exceed the display width of the screen and can wrap. You can continue typing, but do not press ENTER to move the text to the next line.

UniData SQL enables you to call UniBasic subroutines from virtual attributes. For further information about writing and using UniBasic subroutines, see Developing UniBasic Applications.

Defining LocationLOC places the attribute at position n relative to the beginning of the record. If LOC is not specified, UniData SQL assumes the input order to be the relative position of each attribute. @ID is at location 0.

Note: Only data attributes are assigned a location. Virtual attributes and phrase attributes are not.

UniData SQL allows two or more defined attributes to have the same location. This gives you the ability to view one piece of data in various ways. For example, the LONGNAME and NAME attributes have the same location, but differ in length. This tells UniData SQL that these attribute definitions are for the same location but the display lengths differ.

Syntax:

LOC(n)

The next example creates a table with two attributes at location 1, LONGNAME and NAME. UniData SQL recognizes both definitions because they have different attribute names.

sql> CREATE TABLE NEW_EXAM (sql> LONGNAME CHAR(25) LOC(1),sql> NAME CHAR(15) LOC(1)); 2 fields added.Create file NEW_EXAM, modulo/1,blocksize/1024

3-12 Using UniData SQL

Page 49: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Defining Display NameDISP provides a name for the attribute to be used as a column header. attribute_name is the default, but it is often not suitable for display purposes because it is abbreviated or is not meaningful.

Tip: Use the SET command with the HEADSEP option to set a character to print between columns. The default is ‘|’. Include the HEADSEP character in string.expr to make the header wrap to a new line and print the HEADSEP character between columns. Use the FORMAT and COLUMN keywords to add formatting characteristics to header and column text.

Syntax:

DISP (“string.expr”)

string.expr must be enclosed in quotation marks.

In the next example, the attribute is LONGNAME and the display name that follows the DISP keyword is Customer Name:

sql> CREATE TABLE NEW_CUST (LONGNAME CHAR(25)sql> LOC(1) DISP("Customer Name"), NAME CHAR(10); 2 fields added.Create file NEW_CUST, modulo/1,blocksize/1024

Defining FormatFORMAT stores a display format in the table dictionary. UniData SQL first applies the conversion codes specified in data type (using the CHAR, DATE, and NUMBER keywords) if they are present before applying format codes. If no conversion code or display format is coded, UniData SQL uses the system default for that data type.

Syntax:

FORMAT(“length[f.char]{L | R | T | C}[n][$][,][Z][mask]”)

3-13

Page 50: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Display Format Options

The following table shows the display format options.

Display Format Options

Option Description

length An integer specifying the width of the output value.

f.char A character used to fill the formatted string, if necessary. If a number is used in place of a character, you precede it with a “\” to clearly indicate that it is f.char.

L Specifies left-justification in a column of length spaces. If the text is longer than length, it is broken in length intervals.

R Specifies right-justification in a column of length spaces.

C Specifies centered text in the column of length spaces.

T Specifies text justification. If data must be broken to fit in a column, it is broken between words.

n Sets the maximum number of decimal places allowed, rounding if necessary. If you enter 0 as n, the number is rounded to an integer.

$ Precedes the output number with a dollar sign.

, Separates the number every three digits.

Z Suppresses leading zeros.

mask Specifies a pattern mask composed of numbers and other characters. UniData SQL sequentially places numeric data in the mask before justification. To create the mask, enter one # for each character, and enter special characters (such as comma and decimal point) where you want them to appear in the printed string. For example, enter ###,###.## to insert commas and the decimal point in the output string.

3-14 Using UniData SQL

Page 51: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Sample Display Formats

The next table illustrates sample display formats.

Sample Display Formats

Value Format Result

Harry Miller 15.L Harry Miller...

Harry Miller 15*R ***Harry Miller

Harry Miller 10T Harry Miller

5227113000 12L###-###-#### 522-711-3000

03031988 10L##/##/#### 03/03/1988

99.99 6R0$ $100

99.99 6R2$ $99.99

9999 6R0$, $9,999

9999 10R2$, $9,999.00

Defining Value Type

SM

SM specifies the value type. The default is singlevalued.

For further information about multivalued attributes, see Using UniData.

Syntax:

SM(“{S | MV | MS}”)

3-15

Page 52: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Valid types are listed in the following table.

Attribute Types

Type Explanation

MV Multivalued attribute

MS Multi-subvalued attribute

S Singlevalued attribute (default)

Defining AssociationsThe “association” is the mechanism UniData uses to establish a relationship between data from one nested level to the next.

Within an association, multivalued attributes and multi-subvalued attributes are related to, or associated with, each other.

An example of related information that would be stored in a UniData database as an association is the following:

A company’s inventory consists of parts that are sold in different colors. Each part is identified by a different part number and price, and a quantity on hand is recorded for each color of each part number. You do not want the price for one part getting mistaken for that of another, and you want the correct color to be related to the correct part number.

The information can be stored, retrieved, and manipulated based on the relationships established by the association. You can unnest all associated attributes by unnesting the association.

The keyword ASSOC and assoc_name are stored in the definition of each associated multivalued and multi-subvalued attribute.

Syntax:

ASSOC(“assoc_name”)

3-16 Using UniData SQL

Page 53: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The following example illustrates creating an association in the PERSON table using the ASSOC keyword:

sql> CREATE TABLE PERSON (NAME CHAR(25) DISP("Customer Name"), sql> SEX CHAR(6) DISP("Sex"), sql> CITY CHAR(10) DISP("City"), sql> PHONE_NUMBER CHAR(10) DISP("Phone Number"), sql> TAPES_RENTED CHAR(10) DISP("Rentals") SM("MV") ASSOC("P_INFO"), sql> TAPE_NAME CHAR(10) SM("MV") DISP("Tape Names") ASSOC("P_INFO")); 6 attribute(s) added. Create file PERSON, modulo/1,blocksize/1024

The next example shows the dictionary for the PERSON table. Notice that UniData SQL created the ASSOC attribute.

sql> LISTDICT PERSON;Page 1@ID TYP LOC CONV NAME FORMAT SM ASSOC--------------- --- ------------- ---- --------------- ------ -- ----------@ID D 0 PERSON 10L SNAME D 1 Customer Name 25L SSEX D 2 Sex 6L SCITY D 3 City 10L SPHONE_NUMBER D 4 Phone Number 10L STAPES_RENTED D 5 Rentals 10L MV P_INFOTAPE_NAME D 6 Tape Names 10L MV P_INFOP_INFO PH TAPE_NAME TAP ES_RENTED8 records listed

Sample CREATE TABLE Statement

A complete example of the CREATE TABLE statement follows. This example defines a table similar to the STUDENT table. Most of the keywords, clauses, conversion codes, and formats used in this example were discussed in preceding sections.

The example adheres to the following conventions:

Keywords can be in either uppercase or lowercase.The clauses in an attribute definition can be in arbitrary order, except that the first one must be the type specifier.

3-17

Page 54: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Different attributes at the same location can have different formats and display names.IDESC and VIRTUAL are interchangeable.

sql> CREATE TABLE ST_EXAMsql> (LNAME CHAR(15) DISP("Last Name") FORMAT("15T") LOC(1),sql> FNAME CHAR(15) DISP("First Name") LOC(2), sql> MAJOR CHAR(4) DISP("Major"),sql> MINOR CHAR(4) DISP("Minor"),sql> ADVISOR CHAR(8) DISP("Advisor"),sql> SEMESTER CHAR(4) DISP("Term") SM("MV") ASSOC("CGA"),sql> COURSE_NBR CHAR(5) DISP("Crs#") SM("MS") ASSOC(“CGA”),sql> COURSE_GRD CHAR(3) DISP("Grd") SM("MS") ASSOC("CGA"),sql> COURSE_HOUR NUMBER(5) DISP("Hours") SM("MS") ASSOC("CGA")sql> IDESC(“TRANS('COURSES',COURSE_NBR,CREDITS,'X')"),sql> COURSE_NAME CHAR(25) DISP("Course Name") SM("MS")ASSOC("CGA")sql> VIRTUAL(“TRANS('COURSES',COURSE_NBR,NAME,'X')"),sql> DEPT CHAR(4) DISP("Dept") SM("M") IDESC("COURSE[1,2]"),sql> GPA1 NUMBER(5,"MD3") DISP("GPA") sql> IDESC(“SUBR('GPA1',COURSE_HOURS,COURSE_GRD)"),sql> TEACHER CHAR(10) DISP("Teacher") SM("MS") ASSOC("CGA")sql> VIRTUAL(“TRANS('COURSES',COURSE_NBR,'TEACHER','X')"),sql> COURSE_HOUR TEACHER")) MODULO 1; 13 fields added.Create file ST_EXAM, modulo/1,blocksize/1024

When you use the CREATE TABLE statement to define a table, you can make data entry or logic mistakes. Critical mistakes may prevent UniData SQL from continuing the table creation process; in such cases, UniData SQL displays error messages. Minor mistakes might affect only one attribute, while UniData SQL records other, correctly specified, attributes in the dictionary. After you identify the source of the mistake, you can use either the UniData SQL ALTER TABLE statement or UniEntry to redefine the attribute.

See Using UniData for information about how to use UniEntry.

3-18 Using UniData SQL

Page 55: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Examining Table DefinitionsOnce you create a table and define the attributes, you can use the UniData SQL LISTDICT command to examine the definition. The next example illustrates a typical result of the LISTDICT command.

The first attribute in the display is @ID. UniData SQL creates the @ID to serve as the key to each record. The location of @ID is 0. You cannot change it; however, you can define an alternative display name or the format for the attribute.

3-19

Page 56: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

When you insert data into the table, you must supply a unique value for the @ID attribute of each record.

sql> LISTDICT ST_EXAM;Page 1@ID TYP LOC CONV NAME FORMAT SM ASSOC------------------------------------------------------------------@ID D 0 ST_EXAM 10L SLNAME D 1 Last Name 15T SFNAME D 2 First Name 15L SMAJOR D 3 Major 4L SMINOR D 4 Minor 4L SADVISOR D 5 Advisor 8L SSEMESTER D 6 Term 4L MV CGACOURSE_NBR D 7 Crs# 5L MS CGACOURSE_GRD D 8 Grd 3L MS CGACGA PH TEACHER COURS E_NAME COURSE _HOUR COURSE_ GRD COURSE_NBRCOURSE_HOUR V TRANS(’COURSE Hours 5R MS CGA S’,COURSE_NBR ,CREDITS,'X')COURSE_NAME V TRANS('COURSE Course Name 25L MS CGA S',COURSE_NBR ,NAME,'X')DEPT V COURSE[1,2] Dept 4L MGPA1 V SUBR('GPA1',C MD3 GPA 5R S OURSE_HOURS,C OURSE_GRD)TEACHER V TRANS('COURSE Teacher 10L MS CGA S',COURSE_NBR ,TEACHER,'X')17 records listed

Tip: If you find any incorrect entries, modify the table with the ALTER TABLE command. This command is discussed in “Modifying Table Definitions,” the next section.

3-20 Using UniData SQL

Page 57: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Modifying Table DefinitionsUniData SQL provides three ways to modify existing definitions:

Add a new definition.Modify the current definition.Delete old attribute definitions.

Use the ALTER TABLE command to modify table definitions.You must modify table definitions in the following situations:

Whenever business changes render definitions obsolete.When you must add new elements to the database.When some attributes are no longer necessary.

Note: In ANSI SQL, the ALTER TABLE statement modifies both the table definition and the data. In UniData SQL, only the table definition is affected, which means the data is not altered.

ALTER TABLE KeywordsKeywords of the ALTER TABLE statement are listed in the following table.

ALTER TABLE Keywords

Keyword Description

ADD Add an attribute definition to a table.

MODIFY Change information about an attribute in a table.

DELETE Delete an attribute from a table.

MODULO Change the modulo size of a table.

Note: Although you can use UniEntry to modify, add, or delete attribute definitions, IBM recommends that you use the UniData SQL ALTER TABLE command to perform these functions. When you execute ALTER TABLE, UniData SQL performs integrity checks on attribute definitions to ensure consistency. UniEntry does not perform these checks, and, if you mix the two, you may create inconsistent definitions. ALTER TABLE changes only the dictionary, it has no effect on the data.

3-21

Page 58: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Adding AttributesThe ADD keyword creates a new attribute definition or alias. If no location is specified, the new attribute is assigned the next available location.

After UniData SQL successfully executes ALTER TABLE ADD, it adds the attribute definitions into the dictionary for the specified table. To display the attribute definition, use a UniData SQL LISTDICT statement.

Syntax:

ALTER TABLE table_name ADD (attribute_definition[,attribute_definition]...)

See “Defining Attributes” on page 3-6 in this chapter for a description of attribute_definition. Notice that, as in the CREATE TABLE statement, attribute definitions require only the attribute name and the data type. You can omit other options or include them in any order.

The next example adds a new attribute, BIRTHDATE, to the ST_EXAM table. In this example, you drop the old ST_EXAM table and create a new ST_EXAM table. In the new table, you define only data type attributes (D type).

First, drop the ST_EXAM table:

sql> DROP TABLE ST_EXAM;Do you really want to delete file ST_EXAM?(y/n):yDeleting file D_ST_EXAM.Deleting file ST_EXAM.

3-22 Using UniData SQL

Page 59: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Next, create a new ST_EXAM table:

sql> CREATE TABLE ST_EXAM(LNAME CHAR(15) DISP("Last Name") sql> FORMAT("15T") LOC(1),sql> FNAME CHAR(15) DISP("First Name") LOC(2),sql> MAJOR CHAR(4) DISP("Major"),sql> MINOR CHAR(4) DISP("Minor"),sql> ADVISOR CHAR(8) DISP("Advisor"),sql> SEMESTER CHAR(4) DISP("Term") SM("MV") ASSOC("CGA"),sql> COURSE_NBR CHAR(5) DISP("Crs#") SM("MS") ASSOC("CGA"),sql> COURSE_GRD CHAR(3) DISP("Grd") SM("MS") ASSOC("CGA")) MODULO 1;

Create file D_ST_EXAM, modulo/1,blocksize/1024Hash type = 0Create file ST_EXAM, modulo/1,blocksize/1024Hash type = 0Added “@ID”, the default record for UniData to DICT ST_EXAM. 8 fields added.Create file ST_EXAM, modulo/1,blocksize/1024

Then, list the definition of the new ST_EXAM table:

sql> LISTDICT ST_EXAM;Page 1@ID TYP LOC CONV NAME FORMAT SM ASSOC-----------------------------------------------------------------@ID D 0 ST_EXAM 10L SLNAME D 1 Last Name 15T SFNAME D 2 First Name 15L SMAJOR D 3 Major 4L SMINOR D 4 Minor 4L SADVISOR D 5 Advisor 8L SSEMESTER D 6 Term 4L MV CGACOURSE_NBR D 7 Crs# 5L MS CGACOURSE_GRD D 8 Grd 3L MS CGACGA PH COURSE_GRD COURSE_NBR SEMESTER

10 records listed

3-23

Page 60: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Next, use the ALTER TABLE statement to add the attribute called BIRTHDATE, then review the effect:

sql> ALTER TABLE ST_EXAM ADD(BIRTHDATE DATE("D4,MDYA3") sql> DISP("Birth Day"));

1 fields added.

sql> LISTDICT ST_EXAM;

Page 1@ID TYP LOC CONV NAME FORMAT SM ASSOC-----------------------------------------------------------------@ID D 0 ST_EXAM 10L SLNAME D 1 Last Name 15T SFNAME D 2 First Name 15L SMAJOR D 3 Major 4L SMINOR D 4 Minor 4L SADVISOR D 5 Advisor 8L SSEMESTER D 6 Term 4L MV CGACOURSE_NBR D 7 Crs# 5L MS CGACOURSE_GRD D 8 Grd 3L MS CGABIRTHDATE D 9 D4,M Birth Day 10L S DYA3CGA PH COURSE_GRD COURSE_NBR SEMESTER

11 records listed

In the example shown above, the location number for BIRTHDATE is 9. Since the modification statement does not specify a location, UniData SQL assigned the location by default based on the current largest location number 8, plus 1.

The next example demonstrates an attempt to add an attribute that is already in the dictionary:

sql> ALTER TABLE ST_EXAM ADD(MAJOR CHAR(6) DISP("Major"),sql> MINOR CHAR(4) DISP("Minor"));

field MAJOR already exists. can’t ADD.field MINOR already exists. can’t ADD.field -- MAJOR exists.do you want to replace this column (y/n) ? yfield -- MINOR exists.do you want to replace this column (y/n) ? y 2 fields added.

3-24 Using UniData SQL

Page 61: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Modifying TablesUse the command ALTER TABLE MODIFY to make changes to an existing table. This command modifies only those properties you specify; other properties of the attribute remain the same.

Syntax:ALTER TABLE table_name MODIFY (attribute_definition[, attribute_definition] ...)

In the MODIFY statement, the attribute_definition has the same format as in the CREATE TABLE statement, except that you can omit the data type from the definition. The attributes you specify in the MODIFY clause must already exist in the dictionary, otherwise UniData SQL displays an error message.

See “Creating a New Table” on page 3-3 in this chapter for instructions on coding attribute_definition.

Using the MODIFY KeywordThe ALTER TABLE statement in the next example uses the MODIFY keyword to make the following changes to the INVENTORY table:

Add format description 15T to the PROD_NAME attribute.Change the display length of the FEATURES attribute to 35.Change the display name for FEATURES to “Description of Product.”

sql> ALTER TABLE INVENTORY MODIFY (PROD_NAME FORMAT("15T"),sql> FEATURES CHAR(35) DISP("Description of Product")); 2 attribute(s) modified.

To examine the result of the modification, use the LISTDICT statement.

Modifying Association NamesRemember the following when naming associations:

3-25

Page 62: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

If you modify the association name of an attribute, UniData SQL makes corresponding changes to the PH attribute.If you add an association name to the attribute definition that had not existed before in any attribute, UniData SQL creates a phrase attribute for that name and puts the related attribute name into the phrase of the PH attribute.If you add an existing association name to an existing attribute definition, UniData SQL adds the attribute name to the phrase of the PH attribute.If you delete the association name of an attribute, UniData SQL deletes the name of that attribute from the phrase of the PH attribute.If the deleted attribute is the only one that bears the association name, UniData SQL automatically deletes the PH attribute from the dictionary.

Modifying an AssociationThe following examples illustrate how to use an ALTER TABLE statement with a MODIFY clause to make the following changes to the ST_EXAM table:

Change the association name of the SEMESTER attribute and COURSE_NBR attribute to “ST_INFO_2” (UniData SQL creates a new PH attribute, ST_INFO_2 in the dictionary).

3-26 Using UniData SQL

Page 63: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Delete SEMESTER and COURSE_NBR from PH attribute CGA.sql> ALTER TABLE ST_EXAM MODIFY(SEMESTER ASSOC("ST_INFO_2"),sql> COURSE_NBR ASSOC("ST_INFO_2")); 4 fields modified.sql> LISTDICT ST_EXAM;@ID TYP LOC CONV NAME FORMAT SM ASSOC------------ ---- ------------ ---- ---------- ------ -- ----------@ID D 0 ST_EXAM 10L SLNAME D 1 Last Name 15T SFNAME D 2 First Name 15.T SMAJOR D 3 Major 6L SMINOR D 4 Mino 4L SADVISOR D 5 Tutor Name 12L SSEMESTER D 6 Term 4L MS ST_INFO_2COURSE_NBR D 7 Crs# 5L MS ST_INFO_2COURSE_GRD D 8 Grd 3L MS CGABIRTHDATE D 9 D4,M Birth Day 10L S DYA3CGA PH COURSE_GRDST_INFO_2 PH COURSE_NBR SE MESTER12 records listed

3-27

Page 64: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The following example shows how the association of COURSE_NBR is deleted and how the association for SEMESTER and COURSE_NBR are restored to CGA. This example shows that the PH attribute ST_INFO_2 has disappeared — UniData SQL deletes the dictionary attribute.

sql> ALTER TABLE ST_EXAM MODIFY(SEMESTER ASSOC("CGA"),sql> COURSE_NBR ASSOC("CGA"));

3 fields modified. 1 fields deleted.

sql> listdict ST_EXAM;

OLD CLASSICCATEGORY: CAT

@ID TYP LOC CONV NAME FORMAT SM ASSOC------------------------------------------------------------------@ID D 0 ST_EXAM 10L SLNAME D 1 Last Name 15T SFNAME D 2 First Name 15.T SMAJOR D 3 Major 6L SMINOR D 4 Minor 4L SADVISOR D 5 Tutor Name 12L SSEMESTER D 6 Term 4L MV CGACOURSE_NBR D 7 Crs# 5L MSCOURSE_GRD D 8 Grd 3L MS CGABIRTHDATE D 9 D4,M Birth Day 10L S DYA3CGA PH SEMESTER COUR SE_GRD COURS E_NBR11 records listed

Deleting AttributesYou can delete attribute definitions from the dictionary with the DELETE keyword. You cannot use the ALTER TABLE DELETE statement to delete the @ID attribute.

Syntax:

ALTER TABLE table_ name DELETE (attribute_name [, attribute_name,] ...)

Note: UniData SQL deletes only the definition. If the table had data in it, the data corresponding to the deleted attribute remains unchanged; however, it becomes inaccessible by any UniData SQL statement. But if you add an attribute at the same location, the data becomes accessible again.

3-28 Using UniData SQL

Page 65: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Example

In some instances, when you delete certain attributes UniData SQL may also delete some phrase attributes. The next example illustrates this point.

Define the Table

First, define a table called EXAMPLE and display the table dictionary:

sql> CREATE TABLE EXAMPLEsql> (A NUMBER SM("MV") ASSOC("P1"),sql> B NUMBER SM("MV") ASSOC("P1"),sql> C NUMBER) MODULO 1;Create file D_EXAMPLE, modulo/1,blocksize/1024Hash type = 0Create file EXAMPLE, modulo/1,blocksize/1024Hash type = 0Added "@ID", the default record for UniData to DICT EXAMPLE. 3 fields added. Create file EXAMPLE, modulo/1,blocksize/1024Create file EXAMPLE, modulo/1,blocksize/1024

sql> LISTDICT EXAMPLE;Page 1@ID TYP LOC CONV NAME FORMAT SM ASSOC---------- --- ------------- ---- --------------- ------ -- -------@ID D 0 EXAMPLE 10L SA D 1 10R MV P1B D 2 10R MV P1C D 3 10R SP1 PH B A5 records listed

3-29

Page 66: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Delete the Attributes

Next, when you delete attributes A and B from the table, you can see that the dictionary contains only the UniData SQL-created @ID attribute and the C attribute. This is because when you deleted A and B, UniData SQL deleted PH attribute P1.

sql> ALTER TABLE EXAMPLE DELETE (A,B); 3 fields deleted.

sql> LISTDICT EXAMPLE;Page 1@ID TYP LOC CONV NAME FORMAT SM ASSOC--------- --- ------------- ---- --------------- ------ -- --------@ID D 0 EXAMPLE 10L SC D 3 10R S2 records listed

Resizing TablesWhen you use static tables, as your database gets larger and larger, UniData SQL fills the space originally assigned to the table. To resize the table, you can use the ALTER TABLE MODULO statement. In the next example, UniData SQL increases the memory allocated to the ST_EXAM table:

sql> ALTER TABLE ST_EXAM MODULO 3;ST_EXAM RESIZED from 1 to 3

Note: Resize tables only when necessary. See Administering UniData for an explanation of how to size the modulo.

3-30 Using UniData SQL

Page 67: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Removing TablesWhen you no longer need a table, you can use a DROP TABLE statement to remove it from the database.

Warning: You cannot recover a dropped table. Once UniData SQL drops a table, the data in it is lost forever. Before you use this statement, make sure you will not lose data you intend to retain.

In the following example, ST_EXAM is dropped:

sql> DROP TABLE ST_EXAM;Do you really want to delete file ST_EXAM?(y/n):yDeleting file D_ST_EXAM.Deleting file ST_EXAM.

Remember to return the UniData SQL demo database to its original state by dropping the tables you created as examples in this chapter:

sql> DROP TABLE CUST2;sqL> DROP TABLE EXAM;sql> DROP TABLE EXAMPLE;sql> DROP TABLE NEW_CUST;sql> DROP TABLE NEW_EXAM;sql> DROP TABLE PERSON;

3-31

Page 68: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Indexing TablesUniData SQL supports indexing to optimize the query process and join operations. UniData SQL provides statements to create and drop indexes. This section contains the information necessary for you to take advantage of this feature.

What Is Indexing?An index for a table works in much the same way as a card catalog in a library. When you look for a book by a particular author, you look in the author card catalog. The information on the author’s card indicates where to find the book. The most important feature of a catalog is that it keeps the authors’ names in alphabetic order, so you can locate a particular name quickly.

When you create an index on an attribute of a data table, UniData SQL does the following:

Extracts all the values of the attribute from every record in the data table.Sorts the values.Saves the values in the index.

UniData SQL maintains a link between each key value and the record that has this value.

When you search a data table for certain records that meet conditions based on that attribute, UniData uses the index to locate only the requested records instead of turning over every record in the data table. UniData uses the index to bypass the records that do not satisfy the condition and to access only the requested records. UniData SQL reads the system hard disk less often, so the search takes considerably less time.

Creating and Dropping IndexesWhen you execute a CREATE INDEX statement, use the table_name of a data table to create an index with index_name on a single key.

3-32 Using UniData SQL

Page 69: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Syntax:

CREATE INDEX index_name ON table_name (attribute_name);

The key attribute, designated by attribute_name, could be any V- or I-type singl-evalued or multivalued attribute in a record of a table. The key attribute can also be a phrase that contains only one attribute. You can create indexes on different attri-butes in one data table. However, you cannot create more than one index on one attribute location.

When you create an index for the first time on a data table, UniData SQL prompts you to enter a length for the alternate key, as shown in the following example. UniData uses this number to allocate records for the indexes, but does not impose a limit on the length of your key values. Your answer should be the maximum length of the values in all the attributes that you want UniData SQL to treat as index keys.

Alternate key length (default 20)

The number you enter at the prompt helps reduce the system overhead so the index is more efficient. At the same time, this key length does not prevent the index from handling a longer value, as long as the key length is within 1020 plus the number you entered. If you press ENTER without entering a number, UniData SQL uses the default key length of 20.

Creating an Index

The following example shows how to create an index on the NAME attribute of the CUSTOMER table. The index is assigned a key length of 12.

sql> CREATE INDEX NAME_NDX ON CUSTOMER(NAME);Alternate key length (default 20): 1212"NAME_NDX" created

Building "NAME_NDX" ...29 record(s) processed.

Note: UniData SQL handles additional maintenance including actually building the index table and keeping the index consistent with the data table when it is updated.

3-33

Page 70: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Dropping a Table Index

When you drop an index, you must indicate the table_name, because there may be other indexes with the same name in the database since UniData SQL allows indexes of the same name in different data tables. When you execute a drop index statement, UniData SQL deletes the index from the table system.

Syntax:

DROP INDEX index_name FROM table_name

Example of Dropping a Table Index

The next example removes the NAME index from the CUSTOMER table:

sql> DROP INDEX NAME_NDX FROM CUSTOMER;

Indexing and the WHERE Clause

When you perform a UniData SQL query or subquery with a WHERE clause, UniData SQL uses an index if the predicate is one that can take advantage of the index and if the operator in the predicate refers to an indexed attribute.

The following table lists predicates that take advantage of indexes when they are present.

Predicate Description

> Greater than.

< Less than.

>= Greater than or equal to.

<= Less than or equal to.

= Equal to.

Operators That Use Indexes

3-34 Using UniData SQL

Page 71: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Examples of the WHERE Clause with an Index

The following example shows how to create the NAME_NDX index on the CUSTOMER table before issuing a query:

sql> CREATE INDEX NAME_NDX ON CUSTOMER(NAME);Alternate key length (default 20): 1212"NAME_NDX" created

Building "NAME_NDX" ...29 record(s) processed.

In the following query, UniData SQL uses the index created on the NAME attribute of CUSTOMER to find the tapes rented by Harry Smith:

sql> SELECT NAME, TAPES_RENTEDsql> FROM CUSTOMERsql> WHERE NAME = "Smith, Harry";

Indexing and Composite Conditions

UniData SQL can handle composite conditions made up of atomic conditions and logical AND and OR operators. If a WHERE clause contains multiple conditions connected by an AND or OR operator, UniData SQL uses an index to process each condition where it can.

For example, a WHERE clause might contain two conditions connected by an AND or OR operator. UniData SQL can use one index to process the first condition and another index to process the second condition.

Join operations frequently contain additional conditions that refer to one table of the join. Atomic conditions in a join operation that refer to only one table are called “restriction conditions.” In the next query, the three conditions joined by AND refer to two tables, CUSTOMER and TAPES.

IN Specifies attribute values within a set of values.

BETWEEN Specifies attribute values within a range.

LIKE Applies conditions that involve a pattern (except when the pattern begins with a wild card).

Predicate Description

Operators That Use Indexes (continued)

3-35

Page 72: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

You already created the NAME_NDX index on the CUSTOMER table. The following example shows how to create the TAPE_NAME_NDX index on the NAME attribute of the TAPES table before issuing a query:

sql> CREATE INDEX TAPE_NAME_NDX ON TAPES(NAME);Alternate key length (default 20): "TAPE_NAME_NDX" createdOne "*" represents 1000 records Building "TAPE_NAME_NDX" ... 21 record(s) processed.

In this query, the first two conditions are restriction conditions containing the equal to operator, so UniData SQL can use both the NAME_NDX and TAPE_NAME_NDX indexes to process the conditions. This query illustrates the use of AND with restriction conditions in a join:

sql> SELECT CUSTOMER.NAME, TAPES.NAME, RENTAL_PRICEsql> FROM CUSTOMER, TAPES sql> WHERE CUSTOMER.NAME = 'Smith, Harry' sql> AND TAPES.NAME = 'Blue Velvet' sql> AND TAPES_RENTED = TAPES.@ID;

When you index a table, UniData SQL selects data from your database more efficiently. However, indexing does reduce system performance during updating of the database. This is because UniData SQL must update the indexes when it updates the underlying table.

Remember that using an index involves accessing the hard disk. When accessing a large number of records, you will save time by employing the index; on the other hand, using an index, and thus accessing the hard disk to retrieve a relatively small number of records may not improve system performance.

Restoring the Database

Remember to return the UniData SQL demo database to its original state by dropping the indexes you created for use in this chapter:

sql> DROP INDEX NAME_NDX FROM CUSTOMER;sql> DROP INDEX TAPE_NAME_NDX FROM TAPES;

3-36 Using UniData SQL

Page 73: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

4Chapter

The Command Stack

Introduction to the Command Stack . . . . . . . . . . . . . 4-3Using the Command Stack. . . . . . . . . . . . . . . . 4-4 Command Stack Operators . . . . . . . . . . . . . . 4-4 Appending to an Existing Statement . . . . . . . . . . . 4-5 Changing Statements in the Stack . . . . . . . . . . . . 4-6 Deleting Statements in the Stack . . . . . . . . . . . . 4-7 Inserting a Statement Line into the Stack . . . . . . . . . . 4-8 Listing Statements in the Stack . . . . . . . . . . . . . 4-9 Recalling a Statement in the Stack . . . . . . . . . . . . 4-9 Storing Statements for Later Use . . . . . . . . . . . . 4-10

Page 74: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

This chapter introduces you to UniData SQL’s command stack. The command stack provides flexibility and convenience in entering, modifying, and executing UniData SQL statements. By the time you complete this chapter, you should be able to do the following:

Use command stack operators.Append to an existing statement.Change existing statements.Delete statements in the stack.Insert a statement into the stack.List statements in the stack.Recall a statement.Save statements for later use and delete saved statements.

4-2 Using UniData SQL

Page 75: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Introduction to the Command StackThe command stack helps you as you work with UniData SQL. It temporarily saves 20 or more UniData SQL statements you enter and enables you to recall, edit, and reexecute them. For a complete list of all the operators you can use in the command stack, see “Using the Command Stack” on page 4-4.

Some of the situations where use of the command stack can help are:

In UniData SQL, you enter the same series of queries over and over again. This repetitive action could introduce mistakes, especially when you need to retype a complex query. Rather than spending time rekeying a complex query, you can use the command stack to make changes as needed and reexecute your query.In some cases, you might find it necessary to test-run a query. If the query is successful, you can use the command stack to save it for later use.Perhaps you need to run a sequence of similar queries that differ only in a few areas. In this instance, you can use the command stack as a template for replicating the queries.

Note: The most recent statement entered or executed is always on the top of the stack and assigned the number 1. Each subsequent statement in the stack is assigned an ascending number according to the order you entered it.

4-3

Page 76: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Using the Command StackUniData SQL stack commands follow these conventions:

A period (.) prefix distinguishes stack commands (which operate on the stack) from normal UniData SQL statements (which operate on the database or tables.) The number preceding each statement line serves as an index to the line and can be used in most stack statements. The asterisk (*) as the first character in a line in the command stack indicates the beginning of the UniData SQL statement.

Note: The UniData SQL command stack works similarly to the command stack in the UniData environment.

Command Stack OperatorsThe following table lists the operators you can use in the command stack to modify and execute statements. The pound sign (#) represents the line number (if you omit #, UniData SQL defaults to line number 1.) You can enter these operators in either uppercase or lowercase.

Operator Description

.A# Appends text to the end of a statement at the specified line number.

.C# Changes one string to another string at the specified line number.

.D# Deletes a statement from the stack at the specified line number.

.I# Inserts text in a statement in the stack at the specified line number.

.L Lists the contents of the stack.

.R# Recalls statements from one line to another line, or recalls saved statements.

Command Stack Operators

4-4 Using UniData SQL

Page 77: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Appending to an Existing StatementUse the .A operator to append characters to the end of a statement line in the stack. After you append text to a statement, UniData SQL redisplays the statement with the appended characters.

Syntax

.A[#] string

# is the line number in the stack and string is the text to be appended. UniData SQL does not add a space between the existing statement and the character string you are appending unless you add a space to the beginning of the new character string.

Tip: If you omit the stack line number, UniData SQL automatically appends to the first entry in the stack.

.S# Saves stack lines in the VOC as a name.

.X# Executes a statement at the specified line number.

.? Displays online help, which provides a listing of the above functions.

Operator Description

Command Stack Operators (continued)

4-5

Page 78: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The following example uses the .A operator to show how to add TAPES_RENTED to the statement and place it after NAME and CITY. After appending the characters, the example uses the .L operator to list the stack for the result.

sql> SELECT NAME,CITYsql> FROM CUSTOMER WHERE CITY='Denver';Page 1Customer Name City--------------- ----------Frobisher, DenverKamalSteven Spender Denver...sql> .A2 ,TAPES_RENTED SELECT NAME,CITY,TAPES_RENTEDsql> .L2 2* SELECT NAME,CITY,TAPES_RENTED 1 FROM CUSTOMER WHERE CITY='Denver';

Changing Statements in the StackUse the .C operator to modify the contents of the stack.

Syntax

.C[#] separator oldstatement separator newstatement [separator G]

# is the number of the line you want to change, oldstatement is the string you are changing, and newstatement is the new string. separator is any character you want to use to separate the .C operator, oldstatement, newstatement, and option. The option G (global) selects all occurrences of the old string in the stack and changes it to the new string.

Tip: Specify the line you want to change by entering the stack line number. If you omit the stack line number, UniData SQL automatically changes the first entry in the stack.

In the following example, a misspelling error was made in the FROM clause. Notice that there is an “E” in the middle of “CUSTEOMER”:

sql> SELECT NAME,CITY FROM CUSTEOMERsql> WHERE CITY='Denver';

4-6 Using UniData SQL

Page 79: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The following example shows how to use the .C operator to correct the misspelling. The “2” after .C designates the stack entry line you are correcting, and the forward slash is used as a separator. The example then uses the .L operator to list the stack for the result.

sql> .C2/CUSTE/CUSTSELECT NAME,CITY FROM CUSTOMERsql> .L2 2* SELECT NAME,CITY FROM CUSTOMER 1 WHERE CITY=’Denver’;

Deleting Statements in the StackUse the .D operator to delete entries in the stack.

Syntax

.D{# | sentence | paragraph}

# is the line number you want to delete from the stack, sentence is the sentence name you want to delete from the VOC and paragraph is the paragraph name you want to delete from the VOC.

Note: For further information about saving statements to the VOC table, see “Storing Statements for Later Use” on page 4-10 in this chapter.

If you enter only .D at the UniData SQL prompt, the first stack item is deleted, and every command in the stack will move up one position.

The next example uses the .D and .A operators to make the following modifications to the stack:

Enter .D without a line number to delete the last entry in the stack.Enter .A to append a semicolon (;) to the end of the current last entry to make it the last line of the SELECT statement.

4-7

Page 80: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

After making the modifications, the example uses the .L operator to list the stack for the result:

sql> SELECT NAME,CITY,TAPES RENTED FROM CUSTOMERsql> UNNEST TAPES_RENTEDsql> .D sql> .A ; SELECT NAME,CITY,TAPES RENTED FROM CUSTOMER;sql> .L1 1* SELECT NAME,CITY,TAPES_RENTED FROM CUSTOMER;

Inserting a Statement Line into the StackUse the .I operator to insert a new statement into the stack.

Syntax

.I[#] newstatement

# is the line number in the stack where you want to insert a new line, and newstatement is the statement you want to insert.

Tip: If you omit the stack number, UniData SQL automatically inserts information into the first entry in the stack.

The next example shows how to insert an UNNEST clause at line 2. After inserting the line, the example uses the .L operator to list the stack for the result.

sql> SELECT NAME,CITY,TAPES_RENTEDsql> FROM CUSTOMERsql> WHERE CITY='Denver';Page 1Customer Name City Tapes--------------- ---------- ----------Frobisher, DenverKamalSteven Spender Denver V2123..sql> .I2 UNNEST TAPES_RENTED UNNEST TAPES_RENTEDsql> .L4 4* SELECT NAME,CITY,TAPES_RENTED 3 FROM CUSTOMER 2 UNNEST TAPES_RENTED 1 WHERE CITY='Denver';

4-8 Using UniData SQL

Page 81: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Listing Statements in the StackUse the .L operator to list the contents of the stack.

Syntax

.L[#]or.L {sentence | paragraph}

# is the line number you want to list, sentence is the sentence you want to list from the VOC, and paragraph is the paragraph name you want to list from the VOC.

For further information about saving statements to the VOC table, see “Storing State-ments for Later Use” on page 4-10.

Tip: If you enter .L without options, UniData SQL displays your last 20 statements.

The next example shows how to use the .L operator and display the results:

sql> SELECT NAME,CITYsql> FROM CUSTOMER sql> WHERE CITY='Denver';Page 1Customer Name City--------------- ----------Frobisher, DenverKamalSteven Spender Denver..sql> .L3 3* SELECT NAME,CITY 2 FROM CUSTOMER 1 WHERE CITY='Denver';

Recalling a Statement in the StackUse the .R operator to recall the position of a statement in the stack to the first position without executing the command.

4-9

Page 82: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Syntax

.R[#]or.R {sentence | paragraph}

# is the line number you want to recall, sentence is the sentence you want to recall from the VOC and paragraph is the paragraph name you want to recall from the VOC.

The next example shows how to recall the fifth line to the bottom of the stack (line 1). First, the example lists the stack, then uses the .R operator to recall line five, then lists the command stack again.

sql> .L5 5 UNNEST TAPES_RENTED 4 WHERE CITY='Denver'; 3*SELECT NAME,CITY 2 FROM CUSTOMER 1 WHERE CITY='Denver';sql> .R5UNNEST TAPES_RENTEDsql> .L5 5 WHERE CITY='Denver'; 4*SELECT NAME,CITY 3 FROM CUSTOMER 2 WHERE CITY='Denver'; 1*UNNEST TAPES_RENTED

Storing Statements for Later UseUse the .S operator to store all or part of the stack in your VOC table.

Syntax

.S name N1 N2

name is the name of the VOC record in which you want to store the stack statements. N1 is the line number of the first of the statements you want to store and N2 is the line number of the last of the statements you want to store.

The following example uses .S to store the contents of the stack as “qcity”. Notice that the .S stack statement has the following two sets of parameters:

4-10 Using UniData SQL

Page 83: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The first parameter is the stored statement name that cannot be omitted. This becomes a record name in the VOC table. If the name is already in the VOC table, UniData SQL asks if you want to overwrite that entry. If you answer “y” (yes), UniData SQL replaces the old contents in the VOC table with new statements; otherwise, the name remains the same and you must enter a name for the statements you want to save.The second parameter indicates the statement start and end entry numbers in the stack. If you omit the number, then only entry one is saved. If you include only one number, only that entry is saved. Enter the two entry numbers in a sequence where the larger number appears first.

sql> .S qcity 4 2save qcity to VOC.

The following example shows how to delete a saved statement. First, the example uses the .D operator to delete the saved statement “qcity” from the VOC table. Then the example uses the .R operator to attempt to recall the statement.

sql> .D qcitysql> .R qcity

qcity is not a VOC item

Executing StatementsUse the .X operator to execute statements in the stack.

Syntax

.X[#]

# is the line number of the statement you want to execute.

Tip: Use a number with the .X operator to designate the statement you want to execute. If you enter .X without a line number, UniData SQL executes the most recently entered statement which starts at the line marked with an asterisk (*).

4-11

Page 84: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The following example reexecutes a statement by first listing the command stack, then reexecuting a statement:

sql> SELECT NAME,CITY FROM CUSTOMERsql> WHERE CITY='Denver';Page 1Customer Name City--------------- ----------Frobisher, DenverKamalSteven Spender Denver..sql> .L2 2*SELECT NAME,CITY FROM CUSTOMER 1 WHERE CITY='Denver';sql> .X2

Page 1Customer Name City--------------- ----------Frobisher,Kamal DenverSteven Spender Denver..Doodle, Polly W. DenverLaRue, Karma DenverSmith, Leif Denver6 records listed

4-12 Using UniData SQL

Page 85: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

5

Chapter

Manipulating Data

Inserting Data into a Table . . . . . . . . . . . . . . . . 5-3 The INSERT Command . . . . . . . . . . . . . . . 5-3 Inserting a Single Record . . . . . . . . . . . . . . . 5-4 Inserting Data into Specified Attributes . . . . . . . . . . 5-5 Inserting Empty Strings and the Null Value . . . . . . . . . 5-5 Inserting a Record with Multiple Values . . . . . . . . . . 5-7 Copying Multiple Records from Other Tables . . . . . . . . 5-8Updating Data in a Table . . . . . . . . . . . . . . . . 5-10 The UPDATE Command . . . . . . . . . . . . . . . 5-10 Updating Specific Attributes. . . . . . . . . . . . . . 5-12 Updating Multiple Records . . . . . . . . . . . . . . 5-13 Updating Multivalued Attributes . . . . . . . . . . . . 5-13 Adding Values and Subvalues . . . . . . . . . . . . . 5-13Deleting Data from a Table . . . . . . . . . . . . . . . 5-17 The DELETE Command . . . . . . . . . . . . . . . 5-17 Deleting a Set of Records. . . . . . . . . . . . . . . 5-19 Deleting All Records in a Table . . . . . . . . . . . . . 5-20 Deleting Data in Multivalued Attributes . . . . . . . . . . 5-20Restoring the Database . . . . . . . . . . . . . . . . . 5-23

Page 86: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

This chapter discusses a set of important UniData SQL statements that manipulate the data in your database.

By the time you complete this chapter, you should be able to do the following:

Insert data into a table.Update data in a table.Delete data from a table.

5-2 Using UniData SQL

Page 87: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Inserting Data into a TableYou can insert data into tables in the following ways:

Insert a single record.Copy a set of records from another table.

This section provides examples of the following:

Inserting a single record.Inserting data into specified attributes.Inserting a record with values.Copying a set of records from other tables.

The INSERT CommandThe INSERT command adds rows to an existing table. Rows can be inserted into an empty table, or one that already contains data. You cannot insert duplicate @IDs into the @ID attribute.

The INSERT statement has two forms:

An INSERT statement with a VALUES clause inserts one row into a table.An INSERT statement with a SELECT clause inserts a set of rows from one or more tables into another table.

Syntax

INSERT INTO table_spec [(attribute_name [, attribute_name...])] VALUES (const_value [,const_value...])INSERT INTO table_spec [(attribute_name [, attribute_name...])] query_spec

Note: You cannot select data and reinsert it into the same table. For this reason, table_spec in the INSERT clause cannot be the same as table_spec in the FROM clause in the SELECT statement.

5-3

Page 88: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

If conflicting aliases exist for a location of the target table, you must specify attribute_name. Conflicting aliases have different formats, conversion codes, and so on.

To insert numeric or string literals, use the first form of the syntax, enclosing string values in quotation marks. To select data from another table and insert it into a table, use the second form of the syntax. query_spec is described under SELECT.

If no attribute_names are specified, the query_spec or VALUES list must contain one value for each data location in the dictionary for that table. The data values are inserted in order of location.

Inserting a Single RecordAn INSERT statement with a VALUES clause inserts one row into a table. The following rules also apply:

If attribute_name(s) are specified, the number and data type of attribute_name(s) and const_value(s) must match.The sequence and data type of const_values must match those of the target attributes. If an attribute is character or date data type, the value to be inserted must be enclosed in quotation marks.If you include attribute_name(s), @ID or its alias must be included in the list of attribute_name(s).Do not include virtual attributes in the VALUES clause because this data is derived from other attributes and is not stored in a base table.You cannot use INSERT or UPDATE commands to add the null value, along with other values, into a multivalued or multi-subvalued attribute. This is because UniData SQL cannot recognize the keyword NULL embedded in a quoted string such as "D|NULL|I". You must first create the record, then use the UPDATE command to change existing values to null, or to append null values.With null value handling turned off, the keyword NULL inserts an empty string.The null value is not valid for @ID. Regardless of whether null value handling is on or off, you can insert a missing value by omitting the value of an attribute in a value list.

5-4 Using UniData SQL

Page 89: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The following example shows you how to insert a single record into a table. This example uses the INSERT statement and the VALUES clause to add a new course record into the COURSES table.

sql> INSERT INTO COURSES sql> VALUES ("CS700","Advanced Database",5,"Otis");COMMIT complete. 1 record(s) created.

Inserting Data into Specified AttributesYou can insert values for specified attributes by including an attribute list after table_spec in the INSERT clause and entering a corresponding number of values in the VALUES clause.

The following example creates a new record, inserting values into specified attri-butes. UniData SQL inserts empty strings into the attributes for which no value is provided.

In this example, a new student, James Bond, enrolls in the university. His social security number is 412-34-5678, and his major is Computer Science. All other infor-mation is missing at the moment. Values listed in the second line correspond to the attributes in the first line.

sql> INSERT INTO STUDENT (@ID,LNAME,FNAME,MAJOR) sql> VALUES ("412345678","Bond","James","CS");

COMMIT complete. 1 record(s) created.

The @ID attribute must be included in the attribute list, and you must assign a non-null value to the @ID attribute in the VALUES clause.

Inserting Empty Strings and the Null ValueWith null value handling on, the null value is considered to be unknown and is repre-sented by the ASCII value selected for your language group. For further information, see Chapter 6, “The SELECT Statement.”

5-5

Page 90: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Regardless of whether null value handling is on or off, you cannot use the INSERT or UPDATE commands to add the null value (with null value handling on) or an empty string (with null value handling off), along with other values, into a multi-valued or multi-subvalued attribute. This is because UniData SQL cannot recognize the keyword NULL embedded in a quoted string such as "D|NULL|I". To insert the null value (with null value handling on) or an empty string (with null value handling off) into a multivalued or multi-subvalued attribute that also contains other values, you must first create the record, then use the UPDATE command to change existing values to null, or to append null values.

With null value handling turned off, the keyword NULL inserts an empty string.

Regardless of whether null value handling is on or off, you can always insert an empty string by inserting “”, or by failing to include a value for an attribute listed in a VALUES clause.

The following example inserts the null value and an empty string into the COURSES table:

sql> INSERT INTO COURSESsql> VALUES ("CS750","UniData Model",NULL,'');1 record(s) created.

The following example displays the null value (unknown data) and an empty string (missing data) in the record just created. First, the SET command assigns the letter “N” to print instead of the (nonprinting) null character. Then, the SELECT statement displays the character that represents the null value for the attribute CREDITS and an empty string for attribute TEACHER.

sql> SET NULL "N";sql> SHOW NULL;Null text is Nsql> SELECT * FROM COURSES WHERE @ID = "CS750";Page 1COURSES Course Name Credi Teacher---------- ------------------------- ----- ----------CS750 UniData Model N1 records listed

Inserting a Record with Multiple ValuesInsert values by separating them with value marks: “}”. Associated multivalued attri-butes must have the same number of values. When unnesting, UniData SQL adds empty strings to attributes containing fewer values so that all associated attributes have the same number.

5-6 Using UniData SQL

Page 91: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

For further information on value and subvalue marks, see Chapter 1, “Introduction to UniData SQL.”

The following example inserts values and subvalues into the STUDENT table:

sql> INSERT INTO STUDENT VALUES ("123459999","Jenral","Hions",sql> "CS","PY","Otis","SP86}FA86",sql> "PY100|CS101}PY200|CS201|CS300","A|B}B|A|C");

COMMIT complete.

1 record(s) created.

Here is the record just inserted into the STUDENT table:

sql> SELECT * FROM STUDENT WHERE @ID="123459999";Page 1STUDENT Last Name First Name Majo Mino Advisor Term Crs # GD ----------- --------- ---------- ---- ---- ------- ---- ----- -- 123-45-9999 Jenral Hions CS PY Otis SP86 PY100 A CS101 B FA86 PY200 B CS201 A CS300 C

1 records listed

Note: When unnesting, UniData SQL considers associated multivalued attributes to always have the same number of values in a record. Null values are appended to shorter ones to match the number of values in a longer one.

Inserting Missing Values in Multivalued and Multi-Subvalued Attributes

To assign empty strings (representing missing values) to an entire multivalued or multi-subvalued attribute, use the same method as you would to insert a value into a singlevalued attribute. For further information on value and subvalue marks, see “Inserting Data into Specified Attributes” on page 5-5.

There may be times when you do not want to set an entire multivalued or multi-subvalued attribute to be empty. In this case, in the VALUES clause, use the “}” value mark to separate values, and “|” value mark to separate subvalues.

5-7

Page 92: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Tip: You cannot insert the null value along with other values into a multivalued or multi-subvalued attribute; you must first create the record, then use the UPDATE command to add null values. You can also create subtables that contain only the multivalued or multi-subvalued attributes, and insert values to those subtables, thereby updating the table.

In this example, student John Kline attended school, but some information is not yet available regarding the courses, grades, and terms he completed. He completed the SP87 term, taking three courses: PY100, CS150, and MA200. His grades for PY100 and MA200 were A and B, but his grade for CS150 is missing. Also, he attended at least one semester before the spring of 1987, but we have no information on that term yet.

sql> INSERT INTO STUDENT VALUESsql> (777123155,"Kline","John","PY","MA","Jones",sql> "}SP87","}PY100|CS150|MA200","}A||B");COMMIT complete. 1 record(s) created.

The following example displays the record just entered:

sql> SELECT * FROM STUDENT WHERE @ID LIKE "777%"Page 1 STUDENT Last Name First Name Majo Mino Advisor Term Crs # GD------------ --------------- ---------- ---- ---- -------- ---- ----- --- 777-12-3155 Kline John PY MA Jones SP87 PY100 A CS150 MA200 B1 records listed

Copying Multiple Records from Other TablesUniData SQL enables you to insert a set of records from one or more tables into another table with the SELECT clause. The following rules apply:

The values to be inserted are determined by the SELECT clause.If attribute_name(s) are specified, the number and data types must be the same as in the SELECT clause.You cannot insert into the table from which you are selecting attributes in the SELECT clause.

5-8 Using UniData SQL

Page 93: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The SELECT clause can contain any valid query_spec as described in Chapter 6, “The SELECT Statement.” It can include joins, group functions, and expressions, as long as the number of INSERT list values is the same as SELECT list values, and they are of the same type.

The following example copies a set of records from the CUSTOMER table into the CUST2 table:

sql> INSERT INTO CUST2 SELECT @ID,NAME,CITY,STATE,PHONEsql> FROM CUSTOMER WHERE CITY = "Denver";COMMIT completed.6 records created.

5-9

Page 94: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Updating Data in a TableThis section provides examples of the following:

Updating specific attributes.Updating multiple records.Updating multivalued attributes.Adding values and subvalues.

The UPDATE CommandUse the UPDATE statement to modify the contents of a table. You cannot update the @ID attribute.

Warning: If you do not specify either an ID_list or a WHERE clause in an UPDATE statement, all rows in the table are modified.

Syntax

UPDATE table_spec [ID_list] {SET | ADD VALUE | ADD SUBVALUE} attribute_name = expression [,attribute_name = expression ...] [WHERE search_condition]

5-10 Using UniData SQL

Page 95: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Parameters

The following table describes each parameter of the syntax.

UPDATE Parameters

Parameter Description

table_spec Name of the table, view, or subtable to be updated.

ID_list Limits search_condition to only those records whose ID is listed in ID_list. ID_list can be applied to a base table only, not to a view or subtable.

SET Replaces the values in one or more attributes of records satisfying WHERE search_condition. You cannot include delimiters to set values or subvalues.

ADD VALUE ADD SUBVALUE

Appends values to the end of an existing multivalued or multi-subvalued attribute specified by attribute_name for the rows satisfying the WHERE clause. More information is provided on this subject following this table.

attribute_name Specifies an attribute to update. Must be an individual attribute name; cannot be a phrase; can be qualified by preceding the attribute name with the table name/label and a period, as follows.table_name.attribute_nametable_label.attribute_name

expression Any combination of attribute names, constants, arithmetic operators, and UniData SQL functions that together return a value that deter-mines the value to store in the attribute.You can set an attribute to the null value like this: attribute_name = NULL.

WHERE search_condition

Updates attribute values that meet the criteria specified in search_condition. WHERE evaluates values and multi- subvalues as if they have been unnested. search_condition takes the form:attribute_name/expression rel_op attribute_name/expressionFor example: WHERE fld1 BETWEEN 100 AND 500.If no WHERE clause or ID_list is included, all rows of the table are updated.Within a WHERE clause, the sum total of the individual conditions and the Boolean operators cannot exceed 127.

5-11

Page 96: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Updating Specific AttributesUse the UPDATE command and the SET keyword to assign one value to a singl-evalued, multivalued, or multi-subvalued attribute. The following example raises Otis’s salary by $2,000.

sql> UPDATE STAFF SET SAL=SAL+2000sql> WHERE LNAME = "Otis";COMMIT complete.

1 record(s) updated.

Updating Multiple RecordsUse the UPDATE command and the SET keyword to modify a set of records based on the WHERE clause. The WHERE clause can contain multiple conditions, or even subqueries, as shown in the following example. A set of updated records might be one, two, or 1000 records, or none, depending on the search condition.

This example uses UPDATE to raise the salary by $3,000 for those staff members who are not professors and are advisors to at least one student:

sql> UPDATE STAFF SET SAL = SAL + 3000sql> WHERE LNAME IN (SELECT ADVISOR FROM STUDENT)sql> AND TITLE != "Prof";COMMIT complete.

2 record(s) updated.

Updating Multivalued AttributesUse the UPDATE command and the SET keyword to modify more than one value in a multivalued attribute.

The following example uses the UPDATE statement to correct a mistake in Smith’s student record. It changes a course number from PY100 to PY200.

sql> UPDATE STUDENT SET COURSE_NBR = "PY200" WHEREsql> LNAME = "Smith" AND SEMESTER = "FA93"sql> AND COURSE_NBR = "PY100";1 record(s) updated.

Note: This example modified only one value in the COURSE_NBR attribute for Smith’s record. If the condition specified in a WHERE clause is satisfied by multiple values in the multivalued attribute, all those values are modified.

5-12 Using UniData SQL

Page 97: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Adding Values and SubvaluesUse the ADD VALUE or ADD SUBVALUE clause to add values or subvalues to an attribute. These clauses insert the value or subvalue into a record as follows:

ADD VALUE appends the value to the end of the specified multivalued attribute.ADD SUBVALUE appends the subvalue to the end of the specified multi-subvalued attribute.

Appending Values and Subvalues with ADD VALUE

Use ADD VALUE to add values to a multivalued or multi-subvalued attribute. Identify the attribute to receive the new values by specifying conditions in the WHERE clause.

In the following example, Muller has completed his SP97 term, taking four courses: CS306, PY207, PY310, and CS326. His grades for CS306 and PY310 are A and B, but the other two grades are not yet reported. This example adds courses CS306, PY207, PY310, and CS326 for SP97. It includes grade A for CS306 and grade B for PY310. Courses PY207 and CS327 are assigned empty strings (by default).

sql> UPDATE STUDENT ADD VALUE SEMESTER = "SP97",sql> COURSE_NBR = "CS306|PY207|PY310|CS326",sql> COURSE_GRD = "A||B"sql> WHERE LNAME = "Muller";1 record(s) updated. sql> SELECT * FROM STUDENT WHERE LNAME = "Muller";Page 1STUDENT Last Name First Name Majo Mino Advisor Term Crs # GD---------- --------------- ---------- ---- ---- -------- ---- ----- ---978766676 Muller Gerhardt FA PY Carnes FA93 FA120 A FA230 C HY101 C SP94 FA121 A FA231 B HY102 I SP97 CS306 A PY207 PY310 B CS3261 records listed

5-13

Page 98: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Adding Subvalues with ADD SUBVALUE

As demonstrated in the preceding section, you can use ADD VALUE to add values and subvalues. Specify the conditions that select attributes to be updated in the WHERE clause. UniData SQL maintains the relationship of the existing values by appending the new ones.

This example adds three new courses to the spring 1994 semester record for jojo Smith:

sql> UPDATE STUDENT ADD SUBVALUEsql> COURSE_NBR = "FA101|FA102|MA101",sql> COURSE_GRD = "D|C|I"sql> WHERE LNAME = "Smith" AND FNAME = "jojo";1 record(s) updated. sql> SELECT * FROM STUDENT WHERE FNAME = "jojo";Page 1STUDENT Last Name First Name Majo Mino Advisor Term Crs # GD---------- --------------- ---------- ---- ---- -------- ---- ----- ---291222021 Smith jojo CS FA Eades SP94 FA100 B FA101 D FA102 C MA101 I1 records listed

Adding Null Values

Regardless of whether null value handling is on or off, you cannot use the INSERT or UPDATE commands to add the null value (with null value handling on) or an empty string (with null value handling off), along with other values, into a multi-valued or multi-subvalued attribute. This is because UniData SQL cannot recognize the keyword NULL embedded in a quoted string such as "D|NULL|I" (see the preceding example).

To insert the null value into a multivalued or multi-subvalued attribute that also contains other values, you must first create the record, then use the UPDATE command to change existing values to null, or to append null values.

5-14 Using UniData SQL

Page 99: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The following example changes the grade of I for course MA101 to the null value (the null value is set to display as “N”):

sql> UPDATE STUDENT SET COURSE_GRD = NULLsql> WHERE FNAME = "jojo" AND COURSE_NBR = "MA101";1 record(s) updated.

sql> SELECT * FROM STUDENT WHERE FNAME = "jojo";Page 1STUDENT Last Name First Name Majo Mino Advisor Term Crs # GD---------- --------------- ---------- ---- ---- -------- ---- ----- ---291222021 Smith jojo CS FA Eades SP94 FA100 B FA101 D FA102 C MA101 N1 records listed

You can also use the NULL keyword to append the null value to a multivalued attribute, as shown in the following example. SET PRINT NULL “N” has been executed so that UniData SQL prints “N” to represent the null value.

sql> UPDATE STUDENT ADD SUBVALUE sql> COURSE_NBR = NULLsql> WHERE LNAME = "Smith" AND FNAME = "jojo";1 record(s) updated. sql> SELECT * FROM STUDENT WHERE FNAME = "jojo";Page 1STUDENT Last Name First Name Majo Mino Advisor Term Crs # GD---------- --------------- ---------- ---- ---- -------- ---- ----- ---291222021 Smith jojo CS FA Eades SP94 FA100 B FA101 D FA102 C MA101 N N1 records listed

5-15

Page 100: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Deleting Data from a TableThis section provides examples of the following:

Deleting a recordDeleting a set of recordsDeleting all recordsDeleting data in multivalued attributes

The DELETE CommandThe DELETE command eliminates records from a table, subtable, or view.

Syntax

DELETE FROM table_spec [table_label] [ID_list] [WHERE search_condition]

Parameters

The following table describes each parameter of the syntax.

Parameter Description

FROM table_spec Specifies the table, subtable, or view from which records are to be deleted.

DELETE Parameters

5-16 Using UniData SQL

Page 101: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

ExampleThe next example shows how to delete the CS700 record from the COURSES table:

sql> DELETE FROM COURSES WHERE @ID="CS100";COMMIT complete.

1 record(s) deleted or updated.

table_label Specifies an alias for a table from which records are to be deleted.

ID_list Limits search_condition to only those records whose ID or key is listed in ID_list. ID_list can be applied to a base table only, not to a view or subtable.If you do not specify the ID_list and search_condition , all records in the table are deleted.

WHERE search_condition

Selects records to delete. If search_condition is applied to:A singlevalued attribute; deletes the entire record.A multivalued attribute; deletes all values that meet the criteria, together with all its associated subvalues. However, even if all values in the multivalued attribute are deleted, values in associated singlevalued attributes remain.A multi-subvalued attribute; deletes all subvalues that meet the criteria. If a conditional test is performed to select values of associated multivalued and multi-subvalued attributes, only the values in the multi-subvalued attribute are deleted. Within a WHERE clause, the sum total of the individual conditions and the Boolean operators cannot exceed 127.If you do not specify the ID_list and search_condition , all records in the table are deleted.

Parameter Description

DELETE Parameters (continued)

5-17

Page 102: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Deleting a Set of RecordsUse a search condition in the WHERE clause to specify a set of records to delete. The result set might be one, two, or 1,000 records, depending on the search condition. For a description of search conditions, see Chapter 6, “The SELECT Statement.”

Since you cannot recover data once you delete it, IBM recommends that you use one of the following methods for saving your data in another place before actually issuing the DELETE statement:

Copy your data into a temporary table using a SELECT statement with the INTO keyword. This method enables the system to automatically create a temporary table that stores your data. However, when you exit UniData SQL, the system automatically deletes this temporary table along with your stored data.Copy your data into another table using the INSERT statement with a SELECT clause. This method enables you to store your data in a UniData SQL table that already exists.

The following examples show the process you should use to delete records from a table.

1. First, store the data you want to delete in another table so you can access it at a later time, if necessary:

sql> SELECT * FROM CUSTOMER WHERE CITY="Chicago" orsql> NUM_RENTALS < 3 INTO TEMP_CUST;

2. Next, delete the customer data in the CUSTOMER table for customers who live in Chicago or rent fewer than three tapes:

sql> DELETE FROM CUSTOMER WHERE CITY = "Chicago" or sql> NUM_RENTALS < 3;COMMIT complete.

8 record(s) deleted or updated.

5-18 Using UniData SQL

Page 103: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

3. Finally, select data from the CUSTOMER table to see how the customer data changed:

sql> SELECT NAME,CITY,NUM_RENTALS FROM CUSTOMER;Page 1Customer Name City RENTALS--------------- ---------- --------Jones, Bob Arvada 7Frobisher, Denver 33KamalSteven Spender Denver 3Jamieson, Dale Seattle 8Chase, Carl Kenosha 11Wagner, Pat Denver 4Wagner, Esther Kenosha 5Doodle, Polly Denver 3W....

Note: The keyword INTO creates a temporary table. You must retrieve data from the temporary table in the same session.

Deleting All Records in a TableIf you do not specify a WHERE clause or a list of @IDs (ID-list) in the DELETE statement, UniData SQL deletes all the records in the specified table.

Warning: It is inadvisable to delete the records in a table unless you are sure you will not need that data again. For information on temporarily storing the data you want to delete before executing the DELETE command, see “Deleting a Set of Records” on page 5-18.

The following example deletes all records in the CUSTOMER table:

sql> DELETE FROM CUSTOMER;COMMIT complete.

21 record(s) deleted or updated.

Deleting Data in Multivalued AttributesYou can delete specified data in a multivalued attribute without deleting the whole record that contains the multivalued attribute. When the system performs conditional checking on multivalued and multi-subvalued attributes using the WHERE clause, only the values that satisfy the conditions are deleted.

5-19

Page 104: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

In the following examples, a student named Jenral has several incorrect entries in his record. First, he has not taken course CS201 in semester FA86. In addition, he did not take any classes in semester SP86. These examples show the process for correcting Jenral’s student record.

1. First, display the record for Jenral:sql> SELECT LNAME,SEMESTER,COURSE_NBR,COURSE_GRDsql> FROM STUDENTsql> WHERE LNAME="Jenral";

Page 1Last Name Term Crs # GD--------------- ---- ----- ---Jenral SP86 PY100 A CS101 B FA86 PY200 B CS201 A CS300 C1 records listed

2. Next, issue the DELETE statement to remove CS201 in FA86 from Jenral’s entry in the STUDENT table. Notice that you only delete one line (the line containing CS201) from the original record:

sql> DELETE FROM STUDENT WHERE LNAME = "Jenral" and sql> COURSE_NBR = "CS201";COMMIT complete.

1 record(s) deleted or updated.

3. Now, display the record for Jenral again. Notice that CS201 no longer appears:

sql> SELECT LNAME,SEMESTER,COURSE_NBR,COURSE_GRD FROM STUDENT sql> WHERE LNAME="Jenral";Page 1Last Name Term Crs # GD--------------- ---- ----- ---Jenral SP86 PY100 A CS101 B FA86 PY200 B CS300 C1 records listed

4. Next, delete all Jenral’s information for the SP86 semester. Remember, if you specify a condition satisfied by a value in a multivalued attribute, then the multivalue and all its associated subvalues are deleted.

sql> DELETE FROM STUDENT WHERE LNAME = "Jenral"sql> AND SEMESTER = "SP86";COMMIT complete.

1 record(s) deleted or updated.

5-20 Using UniData SQL

Page 105: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

5. Finally, display the record for Jenral again, as this example illustrates. Notice that all Jenral’s information for the SP86 semester has been deleted:

sql> SELECT LNAME,SEMESTER,COURSE_NBR,COURSE_GRD FROM STUDENTsql> WHERE LNAME="Jenral";Page 1Last Name Term Crs # GD--------------- ---- ----- ---Jenral FA86 PY200 B CS300 C1 records listed

Note: If conditional checking is performed on multi-subvalued attributes, and the association contains both multivalued and multi-subvalued attributes, only values in the multi-subvalued attribute are deleted. However, if all the values in a multi-subvalued attribute satisfy the condition, the corresponding values of the associated multivalued attributes are also deleted.

5-21

Page 106: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Restoring the DatabaseBefore leaving this chapter, restore the database to its original status by deleting the records you inserted and returning the contents of the records you modified to their original state.

The following example initiates the restoration:

sql> UPDATE STAFF SET SAL=SAL-2000sql> WHERE LNAME = "Otis";COMMIT complete.

1 record(s) updated.

The following example completes the restoration of the STAFF database:

sql> UPDATE STAFF SET SAL = SAL-3000sql> WHERE LNAME IN (SELECT ADVISORsql> FROM STUDENT) AND TITLE !="Prof";COMMIT complete.2 record(s) updated.

The next example restores the COURSES database:

sql> DELETE FROM COURSES WHERE @ID = "CS750";COMMIT complete.

1 record(s) deleted or updated.

The next example restores the STUDENT database:

sql> DELETE FROM STUDENT WHERE @ID = "412345678"sql> OR @ID = "123459999" OR @ID = "777123155";COMMIT complete.

3 record(s) deleted or updated.

The final example restores the CUSTOMER database. You must do this in the same SQL session in which you created TEMP_CUST.

sql> INSERT INTO CUSTOMERsql> SELECT * FROM TEMP_CUST;COMMIT complete.

7 record(s) created.

5-22 Using UniData SQL

Page 107: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

6Chapter

The SELECT Statement

Retrieving Data with SELECT . . . . . . . . . . . . . . 6-5 Separation Characters . . . . . . . . . . . . . . . . 6-7Writing Simple Queries. . . . . . . . . . . . . . . . . 6-8 Selecting Rows from the Result Table . . . . . . . . . . . 6-8 Selecting Specific Attributes. . . . . . . . . . . . . . 6-8 Selecting All Attributes . . . . . . . . . . . . . . . 6-9 Selecting or Excluding Duplicate Values . . . . . . . . . . 6-11 Selecting Multivalued Attributes . . . . . . . . . . . . 6-12 Selecting Multi-Subvalued Attributes . . . . . . . . . . . 6-13 Selecting Virtual Attributes . . . . . . . . . . . . . . 6-14 Selecting Records by Specifying Record IDs . . . . . . . . 6-15Selecting Tables with FROM . . . . . . . . . . . . . . . 6-17 Qualifying Attribute Names with Table Labels . . . . . . . . 6-17 Joining Tables . . . . . . . . . . . . . . . . . . 6-18 Types of Joins . . . . . . . . . . . . . . . . . . 6-19 How to Join Tables. . . . . . . . . . . . . . . . . 6-21 Inner Joins . . . . . . . . . . . . . . . . . . . 6-24 Outer Joins . . . . . . . . . . . . . . . . . . . 6-27Unnesting Query Results with UNNEST . . . . . . . . . . . 6-32 How to Unnest . . . . . . . . . . . . . . . . . . 6-32 Unnesting Multivalued Attributes . . . . . . . . . . . . 6-33 Unnesting Multi-Subvalued Attributes . . . . . . . . . . 6-36 Unnesting Multivalued and Multi-Subvalued Attributes . . . . . 6-37Selecting Records with WHERE . . . . . . . . . . . . . . 6-41 Using Greater Than in a WHERE Clause . . . . . . . . . . 6-42 Combining Selection Criteria with AND . . . . . . . . . . 6-42 Combining Selection Criteria with OR . . . . . . . . . . 6-44

Page 108: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

6-2 Usi

Combining the AND and OR Operators . . . . . . . . . . 6-44 Selecting Values That Do Not Meet Conditions . . . . . . . . 6-45 Applying Conditions to Every Value . . . . . . . . . . . 6-48 Selecting Records That Match Patterns . . . . . . . . . . 6-49 Searching for Patterns with the LIKE Operator . . . . . . . . 6-50 Using Range Specifiers . . . . . . . . . . . . . . . 6-52 Using Wild Cards in Patterns. . . . . . . . . . . . . . 6-53 Dictionary Conversions and the LIKE Operator . . . . . . . . 6-53 LIKE Clauses and Strings. . . . . . . . . . . . . . . 6-54 Incorrect Pattern Specification . . . . . . . . . . . . . 6-55 The IN Operator. . . . . . . . . . . . . . . . . . 6-55 Selecting Records within a Range . . . . . . . . . . . . 6-57Sorting Query Results . . . . . . . . . . . . . . . . . 6-59 Sorting in Ascending Order . . . . . . . . . . . . . . 6-59 Sorting in Descending Order . . . . . . . . . . . . . . 6-60 Sorting by Multiple Attributes . . . . . . . . . . . . . 6-60 Combining Ascending and Descending Operators . . . . . . . 6-62 Sorting Based on Multivalued Attributes . . . . . . . . . . 6-62 Unnesting and Sorting Based on Multivalued Attributes . . . . . 6-63 Unnesting an Association and Sorting . . . . . . . . . . . 6-64 Sorting and Unnesting . . . . . . . . . . . . . . . . 6-64Subqueries . . . . . . . . . . . . . . . . . . . . . 6-66 Combining Multiple Queries into a Single Query . . . . . . . 6-66 Using ANY, ALL, and IN with Subqueries . . . . . . . . . 6-67 Writing Compound Queries . . . . . . . . . . . . . . 6-69 Passing Data from Query to Subquery . . . . . . . . . . . 6-72Group Functions . . . . . . . . . . . . . . . . . . . 6-73 Selecting Summary Information from One Group . . . . . . . 6-73 Multiple Group Functions. . . . . . . . . . . . . . . 6-77 Correct and Incorrect Group Function Use . . . . . . . . . 6-77 Using DISTINCT and COUNT with Attributes . . . . . . . . 6-78 Writing Column Headings . . . . . . . . . . . . . . 6-78 Selecting Summary Information from Multiple Groups . . . . . 6-79 Including Multiple Attribute Names in a GROUP BY Clause . . . 6-80 Specifying a Search Condition for Groups . . . . . . . . . 6-80 Group Functions with Multivalued Attributes . . . . . . . . 6-83

ng UniData SQL

Page 109: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Expressions and Functions . . . . . . . . . . . . . . . . 6-85 Arithmetic Expressions . . . . . . . . . . . . . . . . 6-85 Arithmetic Functions. . . . . . . . . . . . . . . . . 6-88 Arithmetic Expressions and Functions in Group Functions . . . . . 6-94 Character String Functions . . . . . . . . . . . . . . . 6-95 Date Functions. . . . . . . . . . . . . . . . . . . 6-102

Using UniData SQL 6-3

Page 110: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

This chapter discusses various ways to use the UniData SQL SELECT statement. By the time you complete this chapter, you should be able to complete the following tasks:

Select data with and without conditions.Unnest multivalues.Sort query results.Join tables.Write subqueries.Write group functions.Write expressions and functions.

6-4 Using UniData SQL

Page 111: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Retrieving Data with SELECTThe SELECT command retrieves data from the database. You can select data and format output with clauses in the query_spec portion of the statement; you can combine two or more statements with the UNION clause and subqueries, sort results with the ORDER BY clause, and direct output to temporary and disk files and the system printer with the INTO TO, and LPTR clauses.

The SELECT statement and query_spec are also clauses in some other command statements, including CREATE SUBTABLE, CREATE VIEW, and INSERT.

The keywords SELECT and FROM are required; all other keywords are optional. All keywords must be used in the order in which they are listed in the syntax. The required clauses provide the following information:

The SELECT clause tells UniData SQL what information to retrieve. The FROM clause tells UniData SQL where to find the information to retrieve.

You must observe the following constraints when writing SELECT statements:

In a SELECT statement, you cannot select more than 1000 attributes and expressions.The SELECT statement or clause cannot contain more than 255 virtual attributes.

6-5

Page 112: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

SyntaxQuery Specification (query_spec):

SELECT [ ALL | DISTINCT ] { * | { attribute_spec | expression} [ attribute_label ] [ , {attribute_spec | expression} [ attribute_label ] ...] }FROM table_spec [ table_label ] [ ID_list ] [ [ INNER | { LEFT | RIGHT | FULL } [ OUTER ] ] JOIN table_spec [ table_label ] [ ID_list ] { ON search_condition | USING ( attribute_name [ , attribute_name ...] ) } ...] [ , table_spec [ table_label ] [ ID_list] [ [ INNER | { LEFT | RIGHT | FULL } [ OUTER ] ] JOIN table_spec [ table_label ] [ ID_list ] { ON search_condition | USING ( attribute_name [ , attribute_name ...] ) } ...] ...][ UNNEST [ NL1 | NL2 | NL_ALL ] { association_name | attribute_name} [ , {association_name | attribute_name} ...] ][ WHERE search_condition] [ GROUP BY { attribute_name | expression} [ , { attribute_name | expression } ...] [ HAVING condition ] ]

Select Statement (select_stmt):

query_spec [ UNION query_spec ...][ ORDER BY { attribute_spec | ordinal_position | expression } [ ASC | DESC ] [ EXP ] [ , {attribute_spec | ordinal position} [ ASC | DESC ] [ EXP ] ...] ][ TO filename | INTO temp_table | LPTR ] [TOXML [ELEMENTS] [WITHSCHEMA] [WITHDTD] [XMLMAPPING mapping_file]] [XMLDATA extraction_mapping_file];

See the UniData SQL Commands Reference for an explanation of the parameters of the above syntax.

6-6 Using UniData SQL

Page 113: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Separation CharactersSeparate attribute names and table names within a UniData SQL statement with commas. You can enter a SELECT statement on a single line, as long as it does not exceed 272 characters, or you can enter it on multiple lines. UniData SQL processes the statement when it encounters a semicolon (;).

Tip: IBM recommends that you not enter more characters per line than your screen displays.

6-7

Page 114: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Writing Simple QueriesThis section demonstrates how to write simple SELECT statements that do not qualify the selection with conditional clauses. These statements retrieve data from all rows in the table, view, or subtable named in the SELECT statement.

You can select the following using simple queries:

Specific attributesAll attributesDistinct valuesSinglevalued, multivalued, and/or multi-subvalued attributesVirtual attributesRecord IDs

Selecting Rows from the Result TableThe SELECT clause produces a result table. Additional clauses, such as WHERE, JOIN, and HAVING, may further qualify the selection, thereby restricting the rows displayed from the result table. Finally, you can sort the rows in the result table with ORDER BY, or combine multiple queries with UNION.

Selecting Specific AttributesIn Chapter 3, “Creating and Modifying Tables,” you learned that a table can consist of many attributes. You can retrieve data from all of the attributes in a table or from selected attributes.

The following example illustrates how to retrieve data from tables with the Video Classics database. In this example, UniData SQL displays the column headings “Customer Name,” “Phone,” and “Total Re” (Total Rented). The headings differ from the attribute names in the SELECT statement. The headings are the display names that are specified in the dictionary for each attribute.

6-8 Using UniData SQL

Page 115: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

This example shows the customer names, customer phone numbers, and the numbers of tapes rented from the CUSTOMER table:

sql> SELECT NAME,PHONE,NUM_RENTALS FROM CUSTOMER;Page 2Customer Name Phone Total Re--------------- ------------- --------...Fellini, J. 14HobokenJones, Freddie (312)555-1212 4Valenzuela, (414)555-1212 13CarmenLaRue, Karma 2Darrell Corden (415)444-0102 2Smith, Leif (303)778-0880 3Jones, Mable (414)333-9999 19Best, George (555)555-5555 15Barrie, Dick (414)999-8765 12Boorman, Rick (312)888-8888 12Partner, Bonnie (303)449-5641 19Byles, Marcy (913)555-6565 229 records listed

Selecting All AttributesYou can use either of the following methods to select all the attributes from a table:

Enter all the attribute names in a table, view, or subtable after SELECT.Enter an asterisk (*) after SELECT.

6-9

Page 116: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Selecting Attribute Names

The following example uses the first method to display the data from the COURSES table where the attributes are @ID, Name, Credits, and Teacher:

sql> SELECT @ID,NAME,CREDITS,TEACHERsql> FROM COURSES;Page 1COURSES Course Name Credi Teacher---------- ------------------------- ----- ----------FA120 Finger Painting 5 FriedPY140 Abnornal Psychology 5 MastersPE100 Golf - I 3 FisherCS105 Database Design 3 GibsonMA101 Math Principals 3 OtisFA231 Photography Practicum 3 Fried...

Note: You can prefix an attribute name with a table reference, and can use an asterisk after the table reference to designate all D-type attributes from a specific table.

Selecting All Attributes with an Asterisk

The asterisk selects all D-type attributes; it does not retrieve virtual fields, and you cannot include attribute_name or expression. If the same attribute name is contained in more than one table, you can qualify the attribute name by preceding it with the table name/label and a period, as follows:

table_name.*table_label.*

6-10 Using UniData SQL

Page 117: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The following example uses the asterisk to display all the attributes from the COURSES table. Notice that the results of this example and the previous example are identical.

sql> SELECT * FROM COURSES;Page 1COURSES Course Name Credi Teacher---------- ------------------------- ----- ----------FA120 Finger Painting 5 FriedPY140 Abnornal Psychology 5 MastersPE100 Golf - I 3 FisherCS105 Database Design 3 GibsonMA101 Math Principals 3 OtisFA231 Photography Practicum 3 FriedPE220 Racquetball 3 FisherMA221 Calculus - II 5 OtisEG110 Engineering Principles 5 Carnes...

Note: An asterisk only selects data attributes and not virtual or phrase attributes.

Selecting or Excluding Duplicate ValuesThe ALL keyword selects every record that meets the selection criteria, including duplicates; this is the default.

Suppose that you want to list the cities in which your customers live. You might initiate a query similar to the following example. UniData SQL lists each city as many times as that city appears in the CUSTOMER table.

sql> SELECT CITY FROM CUSTOMER;Page 1City----------ArvadaDenverDenverSeattleKenoshaDenverKenoshaDenverNew YorkHawthorne...29 records listed

6-11

Page 118: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Excluding Duplicate Records

The DISTINCT keyword returns only unique records; duplicates are filtered out.

Use the DISTINCT operator to tell the system that you want to list only once each city name in which your customers live.

The next example uses DISTINCT to list the 17 cities. The result is a list that does not contain duplications.

sql> SELECT DISTINCT CITY FROM CUSTOMER;Page 1 City --------------- ArvadaBoulderChicagoDenverDodge CityEl PasoGoldenHawthorneKenoshaLakewoodLos AngelesMilwaukeeNew YorkOvertonRutherfordSan JoseSeattle17 records listed

Selecting Multivalued AttributesThe previous examples select singlevalued attributes, but UniData SQL enables you to use a query on multivalued attributes in the same way you do on singlevalued attributes.

The following example illustrates how to select multivalued attributes. This example lists the customer name, the tapes rented by that customer, and the dates the customer checked out tapes from the CUSTOMER table.

6-12 Using UniData SQL

Page 119: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Notice that the displayed format in the following example differs from the format of other examples in that some of the NAME attribute lines are blank. This is because TAPES_RENTED and DATE_OUT are both multivalued attributes; therefore, each customer can rent more than one tape, and they can rent them on different days.

Note: To repeat singlevalued attributes for each multivalue, you must unnest the multivalued attribute.

The following SELECT statement demonstrates selection and display of multivalued attributes:

sql> SELECT NAME,TAPES_RENTED,DATE_OUT FROM CUSTOMER;Page 1Customer Name Tapes Date Out--------------- ---------- --------Jones, Bob V4341 04/24/94Frobisher,KamalSteven SpenderJamieson, Dale V6670 04/24/94Chase, Carl V8481 04/20/94 V1254 04/20/94 V4951 04/21/94Wagner, PatWagner, EstherDoodle, PollyW.Fischer, Carrie V110 04/23/94...Byles, Marcy29 records listed

Selecting Multi-Subvalued AttributesThe following example demonstrates how UniData SQL selects multi-subvalued attributes. UniData SQL displays multiple semesters (multivalues) and multiple courses within a semester (multi-subvalues). As you look at this example, compare the display format of the multi-subvalued attributes COURSE_NBR and COURSE_GRD with the multivalued attribute SEMESTER.

6-13

Page 120: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

This example shows the last names of the students, the semesters in which they were enrolled, the courses taken each semester, and grades earned.

sql> SELECT LNAME,SEMESTER,COURSE_NBR,COURSE_GRDsql> FROM STUDENT;Page 1Last Name Term Crs # GD--------------- ---- ----- ---Smith FA93 CS130 A CS100 B PY100 B SP94 CS131 B CS101 B PE220 ASmith SP94 FA100 BMartin SP94 PY100 C PE100 COffenbach FA93 CS104 D MA101 C FA100 C...Muller FA93 FA120 A FA230 C HY101 C SP94 FA121 A FA231 B HY102 I6 records listed

Selecting Virtual AttributesChapter 3, “Creating and Modifying Tables,” introduced virtual attributes. A virtual attribute is a dictionary record definition that executes a formula to derive its value each time the attribute is retrieved.

6-14 Using UniData SQL

Page 121: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

In this example, the virtual attribute TAPE_NAME uses the tape number from the TAPES_RENTED attribute to find a tape name in the TAPES table. The example displays the customer names, tape numbers, and names of the tapes rented.

sql> SELECT NAME,TAPES_RENTED,TAPE_NAME FROM CUSTOMER;Page 1Customer Name Tapes Video Tape Name--------------- ---------- --------------------Jones, Bob V4341 ZFrobisher,KamalSteven SpenderJamieson, Dale V6670 2001Chase, Carl V8481 'Round Midnight V1254 Flash Gordon V4951 American GraffitiWagner, PatWagner, EstherDoodle, PollyW....Page 3Customer Name Tapes Video Tape Name--------------- ---------- -------------------- B2297 Love StoryByles, Marcy29 records listed

Selecting Records by Specifying Record IDsIf you want to retrieve data from specific records in a table, you can specify a record ID list. When you use a record ID list, UniData searches for data in the specified records rather than searching the entire table to find the data you need. This method provides the fastest access to data stored in UniData tables.

The following example shows you one way to select records with IDs 1 and 11 from the CUSTOMER table:

sql> SELECT @ID,NAME,TAPES_RENTEDsql> FROM CUSTOMER "1" "11";Page 1 Cust Customer Name Tapes---------- --------------- ---------- 1 Smith, Harry V2001 V5004 V8181 11 Best, George B22972 records listed

6-15

Page 122: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The following alternative syntax is equally efficient:

sql> SELECT NAME,TAPES_RENTED FROM CUSTOMERsql> WHERE @ID IN ("1", "11");

or

sql> SELECT NAME,TAPES_RENTED FROM CUSTOMERsql> WHERE @ID = "1" or @ID = "11";

6-16 Using UniData SQL

Page 123: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Selecting Tables with FROMThe FROM clause of the SELECT statement determines the tables accessed. You can select up to eight tables in a single FROM clause.

SyntaxFROM table_spec [ table_label ] [ ID_list ] [ [ INNER | { LEFT | RIGHT | FULL } [ OUTER ] ] JOIN table_spec [ table_label ] [ ID_list ] { ON search_condition | USING ( attribute_name [ , attribute_name ...] ) } ...] [ , table_spec [ table_label ] [ ID_list] [ [ INNER | { LEFT | RIGHT | FULL } [ OUTER ] ] JOIN table_spec [ table_label ] [ ID_list ] { ON search_condition | USING ( attribute_name [ , attribute_name ...] ) } ...] ...]

Tip: You can select attributes from more than one table by including multiple tables in the WHERE clause, or by including one or more JOIN clauses.

Qualifying Attribute Names with Table LabelsWhen you include attributes of the same name from different tables, you need to link each attribute with its table. Other times, you may want to clarify a complex statement that selects two attributes from the same table that contains the same type of information. In these cases, you can qualify the attribute names with a table label, consisting of the table name and a period. You can even abbreviate table labels.

Abbreviating Table Labels – Adding qualifying table labels can make state-ments long and cumbersome. You can assign shorter labels by defining them in the FROM clause, as in this line from the example later in this section:FROM STAFF X, STAFF YYou can then use the abbreviated label as you would any table label in other clauses:SELECT X.LNAME Supervisor, X.DEPT, Y.LNAME Employee, Y.DEPT

6-17

Page 124: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Using Table Labels for Reused Attributes – This example statement joins a table to itself and uses table labels to make the statement more readable. The statement displays information from both the NAME and DEPT attributes for both supervisors and employees. To qualify use of the attribute, we have assigned two abbreviated table labels: X and Y. When we use one of these attributes, we label it with X if it applies to the supervisor, or Y if it applies to the employee.

sql> SELECT X.LNAME Supervisor, X.DEPT, Y.LNAME Employee, Y.DEPTsql> FROM STAFF X, STAFF Ysql> WHERE X.LNAME = Y.SUPERVISOR;Page 1Supervis Dept Employee Dept-------- ---- -------- ----Fried BUS James PSYFried BUS Carnes ENGFried BUS Eades FAFried BUS Fisher BUSFried BUS Gibson SPAJames PSY Masters PSYJames PSY Aaron PSYEades FA Otis FA8 records listed

Note: Alternate column headings would also help clarify the output. See COLUMN in the UniData SQL Commands Reference for instructions on assigning column headings.

Joining TablesA join uses data from one table to obtain data from another. You can join a table to itself, or you can join two tables. Joins are based on one of the following:

TRANS function – A virtual attribute includes a TRANS function that extracts data from another table.JOIN clause – Two related attributes in two (or more) tables contain the same type of data (such as a code). The JOIN clause selects records based on a comparison of values in the related attributes. WHERE clause – Alternate syntax that performs the same functions as the INNER JOIN keyword. Two related attributes in two tables contain the same type of data (such as a code), and a third attribute defines the code. The join is accomplished by a WHERE clause, which selects records based on a comparison of values in the related attributes.

6-18 Using UniData SQL

Page 125: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Tip: Indexes are not used in queries that involve a join of two or more sql tables or views. However, if you are joining views of the same base table on record ID only, the statement is translated into a non-join query on the underlying table. Thus, if an attribute included in the WHERE clause is indexed, that index is used to improve performance.

Types of JoinsYou can create the following types of joins using the preceding methods:

Inner join – Performs an inner join of the tables included in the FROM clause. Retrieves only rows that meet the join condition. Therefore, rows in the result set have matching values in the attributes on which the join is based.Outer join – Retrieves all rows that meet the join criteria, but it also retrieves additional unmatched rows based on whether it is a left or right outer join. These additional rows come from the left (the table preceding the JOIN keyword), right (the table following the JOIN keyword), or both tables. The keywords refer to the following:

A left outer join retrieves all rows from the left table (the table preceding the JOIN keyword), including those for which no matching value exists in the joined table. In addition, it includes rows for which values in the attributes match (these are the same rows included in the inner join). Finally, it places null values in all columns of the result table that come from the right table for all unmatched rows.A right outer join retrieves all rows from the right table (the table following the JOIN keyword), including those for which no matching value exists in the joined table. In addition, it includes rows for which values in the attributes match (these are the same rows included in the inner join). Finally, it places null values in all columns of the result table that come from the left table for all unmatched rows.A full outer join retrieves all rows from both tables listed in the JOIN clause, combining the results from the left and right outer joins. Therefore, all rows from both tables are included, and those for which the attributes match are combined. Finally, it places null values in all columns of the result table for all unmatched rows.

6-19

Page 126: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Points to Remember about Joins

UniData SQL differs from ANSI-standard outer joins in the following ways: Only equi-joins are supported (see Appendix B, “More Table Joins,” for some examples involving three tables while meeting this requirement).

Have you ever produced results in which every row is joined with every other row? You produce a Cartesian product when you fail to include a search condition to restrict the rows retrieved. A Cartesian product is rarely meaningful.

Tip: The examples in this section were generated from sql scripts. To do this, at the operating system level, use a text editor to enter the sql statements in a file. Then initiate an SQL session and execute the script on the same line from the operating system prompt, as follows:% sql script_filename.

How to Join TablesJoins are based on attributes in the joined tables being related through one of the following methods:

TRANS function in a virtual attribute.Attributes that contain the same type of data.

Joining Tables through Virtual Attributes

You can link tables by including the TRANS function in a virtual attribute. TRANS uses the data from an attribute in one table to retrieve related data in another table, such as when you match the code in one file to its description in another. Any time you include a virtual attribute with a TRANS function, you are creating an equi-join.

The TRANS function and virtual attributes are unique features of the UniData imple-mentation of SQL. For details on the TRANS function, see Using UniData.

Here is the virtual attribute COMPANY in the ORDERS table. COMPANY uses the CLIENT_NO attribute from the ORDERS table as a key to retrieve records from the CLIENTS table. Then the COMPANY attribute from the corresponding record is displayed.

COMPANY V TRANS('CLIENT Company 15T S S',CLIENT_NO,

'COMPANY’,'X' )

6-20 Using UniData SQL

Page 127: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The following example lists the two virtual attributes client name (NAME) and company (COMPANY), for orders totaling less than $100. Both of these attributes are located in the CLIENTS table but are obtained for ORDERS through TRANS functions.

SELECT NAME, PRODUCT_NO, COMPANY FROM ORDERSUNNEST PRODUCT_NOWHERE EPRICE < 100;Page 1Name Product Nu Company------------------------- ---------- ---------------Glen Asakawa 10005 Pearl SecurityAlicia Rodriguez 10030 Macro Print Inc,Sharon Guo 30000 Spence DesignSharon Guo 11020 Spence DesignIan Samuel 51020 Wilson Instruments...92 records listed

Joining Tables through Related Attributes

Remember that a join of two tables is created when you use attribute values in one table to select rows in another table — based on a comparison of the values of two related attributes. The most common comparison type selects rows when those attribute values are equal — an equi-join.

Outer joins must be equi-joins, based on an equal condition. Inner joins can be equi-joins, or can be based on any relational operator.

Operator Description

= Equal to.

!= <> Not equal to.

> Greater than.

< Less than.

>= Greater than or equal to.

Relational Operators

6-21

Page 128: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Joins Based on an Equal Condition

An equi-join retrieves rows when data values for the related attributes (those included in the JOIN or WHERE clause) are equal.

The following sample SELECT statement produces an inner, equi-join based on values in the attribute TAPES_RENTED from the CUSTOMER table being equal to values in @ID in the TAPES table.

The video store manager creates this SELECT when she needs a list of the tapes rented by each customer. The following two statements produce this list. The join condition in each statement is shown in bold type.

select a.@ID, a.NAME, a.TAPES_RENTED, a.TAPE_COST, b.@ID, b.RENTAL_PRICEfrom CUSTOMER a join TAPES b on a.TAPES_RENTED = b.@IDunnest a.TAPES_RENTED;select a.@ID, a.NAME, a.TAPES_RENTED, a.TAPE_COST, b.@ID, b.RENTAL_PRICEfrom CUSTOMER a, TAPES bunnest a.TAPES_RENTEDwhere a.TAPES_RENTED = b.@ID;

<= Less than or equal to .

!> Not greater than.

!< Not less than.

Operator Description

Relational Operators (continued)

6-22 Using UniData SQL

Page 129: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Joins Based on a Not Equal Condition

Inner joins can select rows based on the joined attributes’ relationship being other than equal. The following two sample SELECT statements produce an inner join based on a comparison of the RENTAL_PRICE for tapes with a name starting with the word “Blue,” with the RENTAL_PRICE of other tapes. The join condition in each statement is shown in bold type.

SELECT X.NAME,X.RENTAL_PRICE,Y.NAME,Y.RENTAL_PRICEFROM TAPES X,TAPES YWHERE X.RENTAL_PRICE >Y.RENTAL_PRICEAND Y.NAME LIKE "Blue...";select X.NAME, X.RENTAL_PRICE, Y.NAME, Y.RENTAL_PRICEfrom TAPES X INNER JOIN TAPES Y on X.RENTAL_PRICE > Y.RENTAL_PRICEunnest X.RENTAL_PRICEwhere Y.NAME like “Blue...”

Joins Not Qualified by a Condition

If you fail to include a search condition, UniData SQL produces a Cartesian product: every row in the first table is matched with every row in the second table.

Inner JoinsInner joins retrieve only rows that meet the search condition. Therefore, rows in the result set have matching values in the related attributes (the attributes on which the join is based).

Inner Joins Based on an Equal ConditionSuppose the tape rental store manager wants to list all active tapes and customers — that is all tapes that have been rented and all customers who have rented tapes. This requires that the manager write an equi-join that is also an inner join.

6-23

Page 130: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The following two SELECT statements satisfy this requirement and produce the same output. Notice that customers who have rented more than one tape are listed more than once, and that tapes that have been rented by more than one customer are listed more than once. Missing from this output are customers who have not rented tapes, as well as tapes that have not been rented.

select a.@ID, a.NAME, a.TAPES_RENTED, a.TAPE_COST, b.@ID, b.NAMEfrom CUSTOMER a INNER JOIN TAPES b ON a.TAPES_RENTED = b.@IDunnest a.TAPES_RENTED;select a.@ID, a.NAME, a.TAPES_RENTED, a.TAPE_COST, b.@ID, b.NAMEfrom CUSTOMER a, TAPES bunnest a.TAPES_RENTEDwhere a.TAPES_RENTED = b.@IDPage 1CUSTOMER Customer Name Tapes Rental C TAPES Tape Name---------- --------------- ---------- -------- ---------- --------------------9 Chase, Carl V8481 $6.75 V8481 'Round Midnight100 Jones, Samuel V8481 $6.75 V8481 'Round Midnight11 Best, George B2297 $2.50 B2297 Love Story2 Partner, Bonnie B2297 $2.50 B2297 Love Story8 Jones, Mable V4499 $4.54 V4499 Psycho1 Smith, Harry V8181 $5.50 V8181 Catch 225 Barrie, Dick V996 $4.54 V996 Citizen Kane2 Partner, Bonnie B914 $1.06 B914 Tammy15 James, Bob V2001 $3.75 V2001 Blue Velvet1 Smith, Harry V2001 $3.75 V2001 Blue Velvet1 Smith, Harry V5004 $4.40 V5004 Journey Abroad10 Faber, Harry V5151 $3.54 V5151 To Kill A Mockingbird12 Jamieson, Dale V6670 $6.75 V6670 20014 Bowie, David V9961 $5.05 V9961 The Stalker3 Fischer, Carrie V110 $2.52 V110 Girl Friday100 Jones, Samuel V1254 $3.15 V1254 Flash Gordon9 Chase, Carl V1254 $3.15 V1254 Flash Gordon6 Jones, Bob V4341 $4.54 V4341 Z9 Chase, Carl V4951 $2.50 V4951 American GraffitiPage 2CUSTOMER Customer Name Tapes Rental C TAPES Tape Name---------- --------------- ---------- -------- ---------- --------------------7 Jones, Freddie V9431 $4.50 V9431 Help8 Jones, Mable V1249 $3.54 V1249 Gone With The Wind21 records listed

Inner Joins Based on a Not Equal ConditionInner joins can select rows based on the joined attributes’ relationship being other than equal. Inner joins can be equi-joins, or can be based on one of the other relational operators: =, != <>, >, <, >=, <=, !>, !<

Here are some examples:

6-24 Using UniData SQL

Page 131: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Using Greater Than with Equal To

This example also joins a table to itself. The results list staff members who make more than Fisher:

sql> SELECT X.LNAME,X.SAL,Y.LNAME,Y.SALsql> FROM STAFF X,STAFF Ysql> WHERE Y.SAL >X.SAL AND X.LNAME = "Fisher";Page 1Last Nam Salary Last Nam Salary-------- ------- -------- -------Fisher 31,200 James 32,500Fisher 31,200 Masters 35,800Fisher 31,200 Eades 42,000Fisher 31,200 Fried 98,0004 records listed

Sorting Join Results

The following two statements create inner joins and sort the results. This first statement sorts results by tape name:

select a.@ID, a.NAME, a.TAPES_RENTED, a.TAPE_COST, b.@ID, b.NAMEfrom CUSTOMER a INNER JOIN TAPES b ON a.TAPES_RENTED = b.@IDunnest a.TAPES_RENTEDorder by b.NAME;Page 1CUSTOMER Customer Name Tapes Rental C TAPES Tape Name---------- --------------- ---------- -------- ---------- --------------------100 Jones, Samuel V8481 $6.75 V8481 'Round Midnight9 Chase, Carl V8481 $6.75 V8481 'Round Midnight12 Jamieson, Dale V6670 $6.75 V6670 20019 Chase, Carl V4951 $2.50 V4951 American Graffiti15 James, Bob V2001 $3.75 V2001 Blue Velvet1 Smith, Harry V2001 $3.75 V2001 Blue Velvet...21 records listedAnd this statement sorts by customer name:select a.@ID, a.NAME, a.TAPES_RENTED, a.TAPE_COST, b.@ID, b.NAMEfrom CUSTOMER a INNER JOIN TAPES b ON a.TAPES_RENTED = b.@IDunnest a.TAPES_RENTEDorder by a.NAME;Page 1CUSTOMER Customer Name Tapes Rental C TAPES Tape Name---------- --------------- ---------- -------- ---------- --------------------5 Barrie, Dick V996 $4.54 V996 Citizen Kane11 Best, George B2297 $2.50 B2297 Love Story4 Bowie, David V9961 $5.05 V9961 The Stalker9 Chase, Carl V1254 $3.15 V1254 Flash Gordon9 Chase, Carl V4951 $2.50 V4951 American Graffiti9 Chase, Carl V8481 $6.75 V8481 'Round Midnight...21 records listed

6-25

Page 132: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Outer JoinsYou can create the following types of outer joins:

Outer Join – Retrieves all rows that meet the search criteria, but it also retrieves additional unmatched rows based on whether it is a left or right outer join. These additional rows come from the left (the table preceding the JOIN keyword), right (the table following the JOIN keyword), or both tables. A left outer join retrieves all rows from the left table (the table preceding the JOIN keyword), including those for which no matching value exists in the joined table. In addition, it includes rows for which values in the attributes match (these are the same rows included in the inner join). Finally, it places null values in all columns of the result table that come from the right table for all unmatched rows.A right outer join retrieves all rows from the right table (the table following the JOIN keyword), including those for which no matching value exists in the joined table. In addition, it includes rows for which values in the attri-butes match (these are the same rows included in the inner join.) Finally, it places null values in all columns of the result table that come from the left table for all unmatched rows.A full outer join retrieves all rows from both tables listed in the JOIN clause, combining the results from the left and right outer joins. Therefore, all rows from both tables are included, and those for which the attributes match are combined. Finally, it places null values in all columns of the result table for all unmatched rows.

The following sections provide examples of simple outer joins. For more examples, see Appendix B, “More Table Joins.”

Note: The examples in this section were generated from sql scripts. To create a script, at the operating system level, use a text editor to enter the sql statements in a file. Then execute the script as follows: % sql script_filename

6-26 Using UniData SQL

Page 133: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Left Outer Joins

A left outer join, by definition, retrieves all rows from the left table (the table preceding the JOIN keyword), including those for which no matching value exists in the joined table. In addition, it includes rows for which values in the related attributes match (these are the same rows included in the inner join).

Suppose we want to list all customers who have registered to rent movies, including those who have never rented a movie. To include all of them, we must execute a left outer join.

Note: This example uses abbreviated table labels to identify the table each attribute comes from. Table labels, abbreviated table labels, and qualifying attributes are explained earlier in this chapter.

select a.@ID, a.NAME, a.TAPES_RENTED, a.TAPE_COST, b.@ID, b.RENTAL_PRICEfrom CUSTOMER a LEFT JOIN TAPES b ON a.TAPES_RENTED = b.@IDunnest a.TAPES_RENTED;Page 1 CUSTOMER Customer Name Tapes Rental C TAPES Retail C---------- --------------- ---------- -------- ---------- -------- 200 Smith, Leif 201 Wagner, Pat 202 Grundy, Robin 203 Boorman, Rick 204 Frobisher, Kamal 205 Fellini, J. Hoboken 206 LaRue, Karma 207 Doodle, Polly W. 208 Dillon, Matt 209 Byles, Marcy 25 Valenzuela, Carmen 210 Wagner, Esther 2 11 Best, George B2297 $2.50 B2297 2.50 2 Partner, Bonnie B2297 $2.50 B2297 2.50 2 Partner, Bonnie B914 $1.06 B914 1.06 3 Fischer, Carrie V110 $2.52 V110 2.52...Page 3 CUSTOMER Customer Name Tapes Rental C TAPES Retail C---------- --------------- ---------- -------- ---------- -------- 14 Darrell Corden V9834 5 Barrie, Dick V996 $4.54 V996 4.54 4 Bowie, David V9961 $5.05 V9961 5.0538 records listed

6-27

Page 134: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

As you would expect, rows retrieved from the CUSTOMER table only do not include data for the related attributes in the TAPES table. These are the new customers who have not yet rented a tape.

Right Outer Join

A right outer join, by definition, retrieves all rows from the right table (the table following the JOIN keyword), including those for which no matching value exists in the related attribute. In addition, it includes rows from the result table with matching values in the related attributes (these are the same rows included in the inner join).

Suppose the tape rental store manager wants to list some information about every tape, and, for those tapes that have been rented, the manager wants to know which customers have rented them. To list this information, the manager includes the RIGHT OUTER JOIN keywords, and tests for an equal condition in the JOIN clause.

6-28 Using UniData SQL

Page 135: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Note: This example uses abbreviated table labels to identify the table each attribute comes from. Table labels, abbreviated table labels, and qualifying attributes are explained earlier in this chapter.

select a.NAME, a.TAPES_RENTED, a.TAPE_COST, b.@ID, b.NAMEfrom CUSTOMER a right join TAPES b ON a.TAPES_RENTED = b.@IDunnest a.TAPES_RENTED;Page 1Customer Name Tapes Rental C TAPES Tape Name--------------- ---------- -------- ---------- --------------------Best, George B2297 $2.50 B2297 Love StoryPartner, Bonnie B2297 $2.50 B2297 Love StoryPartner, Bonnie B914 $1.06 B914 Tammy V1077 SleuthFischer, Carrie V110 $2.52 V110 Girl Friday V1231 ScaramoucheJones, Mable V1249 $3.54 V1249 Gone With The WindChase, Carl V1254 $3.15 V1254 Flash GordonJones, Samuel V1254 $3.15 V1254 Flash GordonJames, Bob V2001 $3.75 V2001 Blue VelvetSmith, Harry V2001 $3.75 V2001 Blue VelvetJones, Bob V4341 $4.54 V4341 ZJones, Mable V4499 $4.54 V4499 Psycho V4637 If...Chase, Carl V4951 $2.50 V4951 American GraffitiSmith, Harry V5004 $4.40 V5004 Journey AbroadFaber, Harry V5151 $3.54 V5151 To Kill A MockingbirdJamieson, Dale V6670 $6.75 V6670 2001 V7456 A Clockwork OrangePage 2Customer Name Tapes Rental C TAPES Tape Name--------------- ---------- -------- ---------- --------------------Smith, Harry V8181 $5.50 V8181 Catch 22Chase, Carl V8481 $6.75 V8481 ‘Round MidnightJones, Samuel V8481 $6.75 V8481 ‘Round MidnightJones, Freddie V9431 $4.50 V9431 HelpBarrie, Dick V996 $4.54 V996 Citizen KaneBowie, David V9961 $5.05 V9961 The Stalker25 records listed

Note that some rows are missing data from the left (CUSTOMER) table. The tapes listed on these rows: Sleuth, Scaramouche, If..., and A Clockwork Orange, have not been rented.

Full Outer JoinA full outer join retrieves all rows from both tables listed in the JOIN clause.

At the end of the year, the tape rental shop manager cleans out the database. She wants to list all tapes and all customers, cross-referencing customers with the tapes they have rented. To list this information, the manager includes the FULL OUTER JOIN keywords, and tests for an equal condition. This retrieves all rows from both tables, including the following:

6-29

Page 136: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Those that contain matching values in the related attributes (those included in the inner join).Those that contain only data from the right table.Those that contain only data from the left table.

select a.@ID, a.NAME, a.TAPES_RENTED, a.TAPE_COST, b.@ID, b.NAMEfrom CUSTOMER a FULL JOIN TAPES b ON a.TAPES_RENTED = b.@IDunnest a.TAPES_RENTED;Page 1CUSTOMER Customer Name Tapes Rental C TAPES Tape Name---------- --------------- ---------- -------- ---------- --------------------14 Darrell Corden190 Belafonte, Harry200 Smith, Leif201 Wagner, Pat202 Grundy, Robin203 Boorman, Rick204 Frobisher, Kamal...Page 2CUSTOMER Customer Name Tapes Rental C TAPES Tape Name---------- --------------- ---------- -------- ---------- --------------------11 Best, George B2297 $2.50 B2297 Love Story2 Partner, Bonnie B2297 $2.50 B2297 Love Story... V4637 If...9 Chase, Carl V4951 $2.50 V4951 American Graffiti1 Smith, Harry V5004 $4.40 V5004 Journey Abroad10 Faber, Harry V5151 $3.54 V5151 To Kill A Mockingbird12 Jamieson, Dale V6670 $6.75 V6670 2001 V7456 A Clockwork OrangePage 3CUSTOMER Customer Name Tapes Rental C TAPES Tape Name---------- --------------- ---------- -------- ---------- --------------------1 Smith, Harry V8181 $5.50 V8181 Catch 22100 Jones, Samuel V8481 $6.75 V8481 'Round Midnight9 Chase, Carl V8481 $6.75 V8481 'Round Midnight7 Jones, Freddie V9431 $4.50 V9431 Help5 Barrie, Dick V996 $4.54 V996 Citizen Kane4 Bowie, David V9961 $5.05 V9961 The Stalker40 records listed

6-30 Using UniData SQL

Page 137: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Unnesting Query Results with UNNESTWithin the SELECT statement, UNNEST repeats single values for each multivalue, multivalues for each multi-subvalue, or both. You may want to unnest tables for the following reasons:

You need to view your multivalued attributes in first normal form (repeating single value for each multivalue).You want to use aggregate functions such as SUM with multivalued attributes.You are sorting (using ORDER BY) results based on multivalued attributes.

Warning: Some legacy systems used the M specifier in the value-type attribute of table dictionaries to indicate a multivalued attribute. When unnesting, UniData SQL interprets this M as MS, unnesting the associated multi-subvalues (repeating multi-values), but not unnesting the multivalues.

Note: The UNNEST clause can process 10,240 values in a multivalued or multi-subvalued attribute, or in all associations for the unnested record.

Syntax[UNNEST [NL1 | NL2 | NL_ALL] {association_name | [attribute_name [ ,attribute_name]]}

How to UnnestYou can unnest multivalued attributes, multi-subvalued attributes, or both by including in the SELECT statement the UNNEST keyword and the options NL1, NL2, and NL_ALL, or no option, combined with the names of multivalued and/or multi-subvalued attributes or an association name. This section explains:

Unnesting Multivalued AttributesUnnesting Multi-Subvalued AttributesUnnesting Multivalues and Multi-Subvalued Attributes

See the UniData SQL Commands Reference for examples of UNNEST with options NL1, NL2, and NL_ALL.

6-31

Page 138: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Unnesting Multivalued AttributesUnnesting multivalues results in single values being repeated. If any multi-subvalued attributes are included in the SELECT statement but not the UNNEST clause, they remain nested. You can use any of the following forms of the UNNEST clause to unnest just multivalued attributes:

UNNEST mv_attributeUNNEST NL1 associationUNNEST NL1 mv_attributeUNNEST NL1 ms_attributeUNNEST NL1 mv_attribute, ms_attribUNNEST NL_ALL mv_attribute

6-32 Using UniData SQL

Page 139: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

This example uses the UNNEST keyword with no options to unnest multivalued attributes only, leaving multi-subvalued attributes nested. Unnesting the multivalued attribute SEMESTER results in the singlevalued attributes @ID and NAME being unnested.

sql> SELECT @ID,LNAME,SEMESTER,COURSE_NBRsql> FROM STUDENTsql> UNNEST SEMESTER;Page 1 STUDENT Last Name Term Crs #------------ --------------- ---- ----- 521-81-4564 Smith FA93 CS130 CS100 PY100 521-81-4564 Smith SP94 CS131 CS101 PE220 291-22-2021 Smith SP94 FA100 424-32-5656 Martin SP94 PY100 PE100 414-44-6545 Offenbach FA93 CS104 MA101 FA100 414-44-6545 Offenbach SP94 CS105 MA102 PY100 221-34-5665 Miller FA93 EG110 MA220 PY100 221-34-5665 Miller SP94 EG140 EG240Page 2 STUDENT Last Name Term Crs #------------ --------------- ---- ----- MA221 978-76-6676 Muller FA93 FA120 FA230 HY101 978-76-6676 Muller SP94 FA121 FA231 HY10210 records listed

6-33

Page 140: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

This example also uses the UNNEST operator with no option to unnest a multivalued attribute only. Semesters attended (multivalued attributes) are displayed in 1NF format (unnested); this causes singlevalued attributes to be repeated (names and majors).

sql> SELECT LNAME,MAJOR,SEMESTERsql> FROM STUDENTsql> UNNEST SEMESTER;Page 1Last Name Majo Term--------------- ---- ----Smith CH FA93Smith CH SP94Smith CS SP94Martin PY SP94Offenbach CS FA93Offenbach CS SP94Miller EG FA93Miller EG SP94Muller FA FA93Muller FA SP9410 records listed

This example contrasts the previous display with a nested display. The UNNEST keyword is omitted, resulting in the same attribute values being returned, but in NF2 format. Thus, the same data values are displayed in 8 rows rather than 13.

sql> SELECT LNAME,MAJOR,SEMESTER FROM STUDENT;Page 1Last Name Majo Term--------------- ---- ----Smith CH FA93 SP94Smith CS SP94Martin PY SP94Offenbach CS FA93 SP94Miller EG FA93 SP94Muller FA FA93 SP946 records listed

Unnesting Multi-Subvalued AttributesUnnesting a multi-subvalued attribute repeats the associated multivalued attribute, but does not repeat singlevalued attributes. You can use any of the following forms of the UNNEST clause to unnest multi-subvalued attributes only:

6-34 Using UniData SQL

Page 141: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

UNNEST ms_attributeUNNEST NL2 association_nameUNNEST NL2 ms_attributeUNNEST NL2 mv_attribute, ms_attribute

Note: The syntax UNNEST NL2 mv_attribute is invalid.

This example unnests the multi-subvalued attributes (COURSE_NBR and COURSE_GRD), repeating the associated multivalued attribute (SEMESTER). This multivalued attribute is not unnested, so singlevalued attributes (@ID, LNAME) are not repeated.

sql> SELECT @ID,LNAME,SEMESTER,COURSE_NBR,COURSE_GRDsql> FROM STUDENTsql> UNNEST COURSE_NBR;Page 1 STUDENT Last Name Term Crs # GD------------ --------------- ---- ----- --- 521-81-4564 Smith FA93 CS130 A FA93 CS100 B FA93 PY100 B SP94 CS131 B SP94 CS101 B SP94 PE220 A 291-22-2021 Smith SP94 FA100 B 424-32-5656 Martin SP94 PY100 C SP94 PE100 C 414-44-6545 Offenbach FA93 CS104 D FA93 MA101 C FA93 FA100 C SP94 CS105 B SP94 MA102 C SP94 PY100 C 221-34-5665 Miller FA93 EG110 C FA93 MA220 B FA93 PY100 B SP94 EG140 B SP94 EG240 978-76-6676 Muller FA93 FA120 A FA93 FA230 C FA93 HY101 C SP94 FA121 A SP94 FA231 B SP94 HY102 I6 records listed

6-35

Page 142: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Unnesting Multivalued and Multi-Subvalued AttributesUnnesting all multivalues and multi-subvalues results in 1NF format. You can use any of the following forms of the UNNEST clause to unnest both multivalued and multi-subvalued attributes:

UNNEST association_nameUNNEST mv_attribute, ms_attributeUNNEST NL_ALL ms_attributeUNNEST NL_ALL association_name UNNEST NL_ALL mv_attribute, ms_attribute

In the next example, all multivalues and multi-subvalues are unnested, repeating all singlevalued and multivalued attributes for each multi-subvalued attribute value — even though only one of the multi-subvalued attributes is listed in the UNNEST clause.

6-36 Using UniData SQL

Page 143: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

COURSE_NBR and COURSE_GRD are associated, so UniData SQL unnests both. Course number is associated with one grade for each semester for each student.

sql> SELECT LNAME,SEMESTER,COURSE_NBR,COURSE_GRD sql> FROM STUDENT UNNEST SEMESTER,COURSE_NBR;Page 1Page 1Last Name Term Crs # GD--------------- ---- ----- ---Smith FA93 CS130 ASmith FA93 CS100 BSmith FA93 PY100 BSmith SP94 CS131 BSmith SP94 CS101 BSmith SP94 PE220 AOffenbach FA93 CS104 DOffenbach FA93 MA101 COffenbach FA93 FA100 COffenbach SP94 CS105 BOffenbach SP94 MA102 COffenbach SP94 PY100 CMiller FA93 EG110 CMiller FA93 MA220 BMiller FA93 PY100 B...Muller FA93 FA120 AMuller FA93 FA230 CMuller FA93 HY101 CMuller SP94 FA121 AMuller SP94 FA231 BMuller SP94 HY102 I29 records listed

When you include an association (in this case, CGA) in an UNNEST clause, and include no option, all multivalued and multi-subvalued attributes in the association are unnested, so all singlevalued and multivalued attributes are repeated for each multi-subvalued attribute.

6-37

Page 144: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

This example includes an association in an UNNEST clause to unnest the semester (multivalued attribute), course number, and course grade (multi-subvalued attributes) for each student (singlevalued attribute).

sql> SELECT @ID,LNAME,SEMESTER,COURSE_NBR,COURSE_GRDsql> FROM STUDENTsql> UNNEST CGA;Page 1 STUDENT Last Name Term Crs # GD------------ --------------- ---- ----- --- 521-81-4564 Smith FA93 CS130 A 521-81-4564 Smith FA93 CS100 B 521-81-4564 Smith FA93 PY100 B 521-81-4564 Smith SP94 CS131 B 521-81-4564 Smith SP94 CS101 B 521-81-4564 Smith SP94 PE220 A 291-22-2021 Smith SP94 FA100 B 424-32-5656 Martin SP94 PY100 C 424-32-5656 Martin SP94 PE100 C 414-44-6545 Offenbach FA93 CS104 D 414-44-6545 Offenbach FA93 MA101 C 414-44-6545 Offenbach FA93 FA100 C 414-44-6545 Offenbach SP94 CS105 B 414-44-6545 Offenbach SP94 MA102 C 414-44-6545 Offenbach SP94 PY100 C 221-34-5665 Miller FA93 EG110 C 221-34-5665 Miller FA93 MA220 B 221-34-5665 Miller FA93 PY100 B 221-34-5665 Miller SP94 EG140 B 221-34-5665 Miller SP94 EG240 B... 978-76-6676 Muller FA93 FA230 C 978-76-6676 Muller FA93 HY101 C 978-76-6676 Muller SP94 FA121 A 978-76-6676 Muller SP94 FA231 B 978-76-6676 Muller SP94 HY102 I27 records listed

6-38 Using UniData SQL

Page 145: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The next example also unnests an association. If you execute this statement without the unnest clause, Smith and Muller are listed one time each, and the footer reads “2 records listed”.

sql> SELECT LNAME,COURSE_NBR,COURSE_GRD sql> FROM STUDENT sql> UNNEST CGA sql> WHERE COURSE_GRD = "A";Page 1Last Name Crs # GD--------------- ----- ---Smith CS130 ASmith PE220 AMuller FA120 AMuller FA121 A4 records listed

6-39

Page 146: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Selecting Records with WHEREWithin the SELECT statement, the WHERE clause defines the criteria that selects records. WHERE appears in SELECT after the UNNEST clause, as follows:

SELECT ...FROM ...[UNNEST ...[WHERE search_condition] [GROUP BY ...

search_condition takes the form:

attribute_name/expression rel_op attribute_name/expression

expression can be a constant (a character string enclosed within quotation marks), a number, an attribute name, or an expression.Within a WHERE clause, the total number of predicates and Boolean operators cannot exceed 127.

You can make the following types of selections using keywords and comparison operators.

Type of WHERE Clause Keywords/Operators Notes/Examples

Comparison =, >, >=, < <=, !=, <>, !<, !>

WHERE PRICE * QTY = SUBTOTAL

! means NOT.

Range BETWEEN WHERE PRICE BETWEEN 100 AND 200

List IN WHERE COUNTRY IN ("AUSTRIALIA")

Character comparisons

LIKE WHERE COUNTRY LIKE "A%"

Types of WHERE Clauses

6-40 Using UniData SQL

Page 147: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Using Greater Than in a WHERE ClauseThe next example uses the greater than operator to show which customers have rented more than 15 tapes:

sql> SELECT NAME,NUM_RENTALS FROM CUSTOMERsql> WHERE NUM_RENTALS >15;Page 1Customer Name Total Re--------------- --------Frobisher, 33KamalBowie, David 17Belafonte, 22HarryGrundy, Robin 23Smith, Harry 22Jones, Mable 19Partner, Bonnie 197 records listed

Combining Selection Criteria with ANDThe following example shows how to connect multiple conditions using the AND operator. When you use AND, all stipulated conditions must be true for UniData SQL to select a given row.

Selecting unknown values (null value handling on) or missing values (null value handling off)

IS NULL, IS NOT NULL WHERE COUNTRY IS NULL

Combinations AND, OR WHERE COUNTRY IS NULL OR COUNTRY = "AUSTRALIA"

Join INNER LEFT RIGHT FULL OUTER JOIN

See “Joining Tables” in this chapter.

Subquery not created by keywords See “Subqueries” in this chapter.

Type of WHERE Clause Keywords/Operators Notes/Examples

Types of WHERE Clauses (continued)

6-41

Page 148: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

This example uses the AND operator to show which customers live in Denver and have rented more than 20 tapes.

sql> SELECT NAME,CITY,NUM_RENTALS FROM CUSTOMERsql> WHERE CITY = "Denver" AND NUM_RENTALS >20;Page 1Customer Name City Total Re--------------- ---------- --------Frobisher, Denver 33Kamal1 records listed

Combining Multiple Selection Criteria

The next example demonstrates that any number of conditions can be connected by the AND operator.

This example shows which customers live in Chicago, have rented fewer than five tapes, and currently hold at least one tape.

sql> SELECT NAME,CITY,NUM_RENTALS,NBR_TAPES FROM CUSTOMER sql> WHERE CITY = "Chicago" AND NUM_RENTALS <5 AND NBR_TAPES >=1;Page 1Customer Name City Total Re Nbr T--------------- ---------- -------- -----Jones, Freddie Chicago 4 11 records listed

6-42 Using UniData SQL

Page 149: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Combining Selection Criteria with ORThe next example uses the OR operator to select rows that satisfy at least one of several conditions. This example shows the customers who live in Denver, Boulder, or Chicago.

sql> SELECT NAME,CITY FROM CUSTOMER sql> WHERE CITY ="Denver" OR CITY = "Boulder" OR CITY ="Chicago";Page 1Customer Name City--------------- ----------Frobisher, DenverKamalSteven Spender DenverWagner, Pat DenverDoodle, Polly DenverW.Belafonte, BoulderHarrySmith, Harry BoulderFellini, J. ChicagoHobokenJones, Freddie ChicagoLaRue, Karma DenverSmith, Leif DenverBoorman, Rick Chicago11 records listed

Combining the AND and OR OperatorsUniData SQL enables you to combine AND and OR to structure composite search conditions that simulate the way people ask questions.

Notice the logical structure of the query in the next example. This example uses the WHERE clause to specify the following conditions:

The tapes must feature Janet Leigh.

6-43

Page 150: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The tapes must be in the “H” or “B” movie categories.sql> SELECT NAME,ACTORS,CATEGORIES sql> FROM TAPES sql> WHERE ACTORS = "Janet Leigh" sql> AND (CATEGORIES = "H" OR CATEGORIES = "B");Page 1Tape Name Actors Type of Vide-------------------- ------------ ------------Psycho Janet Leigh H D

1 records listed

Grouping Conditions with Parentheses

Use parentheses to group the conditions that the clause must meet. Parentheses tell UniData SQL how to prioritize the conditions. Notice that if you enter the same statement as in the previous example, but do not use the parentheses, you get a different result.

In the next example, UniData SQL selects the rows that satisfy both of the first two conditions, or the third condition. In the absence of parentheses, UniData SQL evaluates multiple conditions in the following order:

1. Looks from left to right for any occurrences of AND.2. Evaluates all conditions paired by AND.3. Looks from left to right for any occurrences of OR.4. Evaluates conditions paired by OR.sql> SELECT NAME,ACTORS,CATEGORIES FROM TAPESsql> WHERE ACTORS = "Janet Leigh" sql> AND CATEGORIES = "H" OR CATEGORIES = "B";Page 1Tape Name Actors Type of Vide-------------------- ------------ ------------Journey Abroad Cary Grant BPsycho Janet Leigh H2 records listed

Selecting Values That Do Not Meet ConditionsSometimes you need to select data that does not meet certain conditions. There are two ways to accomplish this task:The NOT EQUAL TO operator.

6-44 Using UniData SQL

Page 151: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The NOT operator.

Using the NOT EQUAL TO Operator

The next example uses the NOT EQUAL TO operator (!= or < >) to display the customers who do not live in Denver or Chicago:

sql> SELECT NAME,CITY FROM CUSTOMERsql> WHERE CITY != "Denver" AND CITY != "Chicago";Page 1Customer Name City--------------- ----------Jones, Bob ArvadaJamieson, Dale SeattleChase, Carl KenoshaWagner, Esther KenoshaFischer, Carrie New YorkJames, Bob HawthorneDillon, Matt Dodge City...Page 2Customer Name City--------------- ----------Partner, Bonnie LakewoodByles, Marcy Los Angeles 20 records listed

Using the NOT Operator

The following shows you how to formulate the previous example using parentheses and the NOT operator to get the same result:

Precede the group with the NOT operator.Put parentheses around the group.

6-45

Page 152: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Change AND to OR.sql> SELECT NAME,CITY FROM CUSTOMERsql> WHERE NOT (CITY = "Denver" OR CITY = "Chicago");Page 1Customer Name City--------------- ----------Jones, Bob ArvadaJamieson, Dale SeattleChase, Carl KenoshaWagner, Esther KenoshaFischer, Carrie New YorkJames, Bob HawthorneDillon, Matt Dodge City...Page 2Customer Name City--------------- ----------Partner, Bonnie LakewoodByles, Marcy Los Angele s20 records listed

Priority of the NOT Operator

NOT has a higher priority than AND and OR. UniData SQL evaluates multiple conditions involving NOT in the following order:

1. It evaluates conditions preceded by NOT and negates the result.2. It evaluates the remaining conditions.

The next example shows the staff members who use the title Professor or Associate Professor, earn a salary greater than $25,000, and do not belong to the Business department or Computer Science department:

sql> SELECT LNAME,TITLE,SAL,DEPTsql> FROM STAFFsql> WHERE (TITLE = "Prof" OR TITLE = "AscProf")sql> AND SAL > 25000sql> AND NOT (DEPT = "BUS" OR DEPT = "CS");Page 1Last Nam Title Salary Dept-------- ------- ------- ----Eades Prof 42,000 FAJames AscProf 32,500 PSYCarnes Prof 29,900 ENGOtis AscProf 25,800 FAGibson Prof 26,800 SPA5 records listed

6-46 Using UniData SQL

Page 153: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Applying Conditions to Every ValueBefore you apply conditions to multivalued attributes, you should determine if every value in the multivalued attribute must meet the condition before selecting the record.

Using the EVERY Operator

Use the EVERY operator to apply the condition to every value.

The next example uses the EVERY operator to show the students whose grades are all below A:

sql> SELECT LNAME,COURSE_GRD FROM STUDENT sql> WHERE EVERY COURSE_GRD != "A";Page 1Last Name GD--------------- ---Smith BMartin C COffenbach D C C B C CMiller C B B B B B4 records listed

Omitting the EVERY OperatorNotice that if you enter the same statement as in the previous example, but omit EVERY, you obtain a different result. This query yields six students instead of the four in the previous query. Without the EVERY operator, the query lists all students who have at least one course grade not equal to A. These students can also have course grades equal to A. However, since the query excludes course grades equal to A, UniData SQL does not display the A grades.

6-47

Page 154: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

This certainly differs from the meaning of the last query, which listed students who had no A grades. More examples using the EVERY operator appear later in this chapter.

sql> SELECT LNAME,COURSE_GRD FROM STUDENT sql> WHERE COURSE_GRD != "A";Page 1Last Name GD--------------- ---Smith B B B BSmith BMartin C COffenbach D C C B C CMiller C B B B B BMuller CPage 2Last Name GD--------------- --- C B I6 records listed

Selecting Records That Match PatternsUsing the LIKE operator, you can select records based on patterns and strings. Instead of specifying a complete string that every row must match, you can specify a pattern that partially matches a designated attribute. Remember to specify all patterns in quotation marks.

6-48 Using UniData SQL

Page 155: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Pattern Specifications

The following table describes the UniData SQL pattern specifications to designate variables or unknown contents of a string or pattern.

UniData SQL Pattern Specifications

Specification Description

% The percent sign (%) matches any number of characters.

_ The underscore character (_) matches one character of any kind.

... Three dots matches any number of characters.

xN A number x followed by the letter N and surrounded by quotation marks matches any numeric string that is of x length. For example, 3N matches strings like “234” or “578”, but not strings like “bs3nn32” or “34+2”.

xA A number followed by the letter A and surrounded by quotation marks matches any alphabetic string that is of x length. Thus, “5A” matches “Jones” but not “BX47Y”.

xX A number followed by the letter X surrounded by quotation marks matches any string that is of x length, regardless of their combination. X stands for any character, including a space.

0A, ON, OX A zero (0A,0N,0X) matches any number of alphabetic characters, numbers, or other characters.

Note: You can replace the number specifier, x in xN, xA and xX, with a range specifier. In the format of m-n, the range specifier tells UniData SQL to match patterns with m to n specified characters. For example, 3-5N matches strings such as “234”, “3567”, “91990”....

Searching for Patterns with the LIKE OperatorThe next example uses the LIKE operator to apply conditions that involve a pattern. This statement enables you to select any name that begins with the character string “B”. If you use a lowercase letter “b”, the pattern does not match anything in the NAME column, because none of the entries under NAME begins with the lowercase letter “b”.

6-49

Page 156: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The next SELECT statement displays the customers whose names begin with the letter “B”:

sql> SELECT NAME FROM CUSTOMER sql> WHERE NAME LIKE "B%";Page 1 Customer Name ------------------------ Bowie, David Belafonte, H. Best, George Barrie, Dick Boorman, Rick Byles, Marcy 6 records listed

Using LIKE to Search for Strings with Variable Contents

You can search for explicit strings, (such as “string”, “Julie”, “video distribution”, and so forth). You can also search for strings or patterns that have variable or unknown contents, as long as you use either an ellipsis (...) or a percent sign (%) after a part of the word. For example, when you search for a name like “Bel...” in the CUSTOMER table, UniData SQL retrieves the name Harry Belafonte.

sql> SELECT NAME FROM CUSTOMER sql> WHERE NAME LIKE "Bel...";Page 1Customer Name ---------------- Belafonte, Harry 1 records listed

Using Range SpecifiersThe next example uses the pattern x-xX (lowercase x is a number of characters) to find all the tapes that have from a one-character to a five-character name:

sql> SELECT @ID,NAME FROM TAPES WHERE NAMEsql> LIKE "1-5X";Page 1TAPES Tape Name---------- --------------------V6670 2001V9431 HelpV4637 If...B914 TammyV4341 Z5 records listed

6-50 Using UniData SQL

Page 157: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Using NOT with Pattern Matching

The next example illustrates that you can use the NOT operator with the LIKE operator. You can precede any operators that specify a search condition with NOT in order to negate the result.

This example uses pattern matching to list all tapes with names that do not start with V:

sql> SELECT @ID,NAME FROM TAPESsql> WHERE @ID NOT LIKE "V...";Page 1TAPES Tape Name---------- --------------------B914 TammyB2297 Love Story2 records listed

Combining Patterns

The next example uses the LIKE operator in the statement, and surrounds the string “er” by a pair of ellipsis. The SELECT statement tells UniData to display the names in the CUSTOMER table that contain the letters “er” anywhere in the name. The ellipsis indicates that the string can occur any place within the name string.

sql> SELECT NAME FROM CUSTOMER sql> WHERE NAME LIKE "...er...";Page 1 Customer Name ------------------------ Frobisher,KamalSteven SpenderWagner, PatWagner, EstherFischer, CarrieFaber, HarryPartner, Bonnie7 records listed

Using Wild Cards in PatternsPattern matching characters have specified meaning between quotation marks. If you want to use these characters with their literal meaning, you must surround them by an additional pair of quotation marks.

6-51

Page 158: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The next example shows the tapes in which the tape name contains the literal string “...”:

sql> SELECT @ID,NAME FROM TAPES sql> WHERE NAME LIKE "...'...'...";Page 1TAPES Tape Name---------- --------------------v4637 If...1 records listed

Dictionary Conversions and the LIKE OperatorThe dictionary entry for each attribute contains a conversion that specifies how the data in that attribute displays. In UniData SQL, the LIKE operator works on the data after it is converted.

In the following example, the pattern 2N,3N selects salaries. You could also have used 6X to get the result shown in the example.

sql> SELECT LNAME,SAL FROM STAFF sql> WHERE SAL LIKE "2N,3N";Page 1Last Nam Salary-------- -------Eades 42,000Masters 35,800Aaron 19,900Fisher 31,200James 32,500Carnes 29,900Otis 25,800Gibson 26,800Fried 98,0009 records listed

For further information on conversion functions, see the UniData SQL Commands Reference.

6-52 Using UniData SQL

Page 159: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

LIKE Clauses and StringsThe following LIKE clauses all return the same result:

sql> SELECT NAME FROM CUSTOMER WHERE NAME LIKE "%ones,____"; sql> SELECT NAME FROM CUSTOMER WHERE NAME LIKE "...ones,1X3A"; sql> SELECT NAME FROM CUSTOMER WHERE NAME LIKE "...ones5X";Customer Name -------------------------- Jones, Bob 1 record listed

Each of these queries looks for records in the following order:

Any number of any characters.The literal string “ones”.One of the character strings in the following table.

What LIKE Clauses Look for in Queries

String Looks For

"%ones,____" , followed by four characters

"...ones,1X3A" , 1 character and 3 alphabetic characters

"...ones5X" 5 characters

Note: A comma is neither numeric nor alphanumeric, however, it does match X.

Incorrect Pattern SpecificationThe following statement does not return any records because it tells UniData SQL to look for a literal 5X in the string:

sql> SELECT NAME FROM CUSTOMERsql> WHERE NAME LIKE "...ones'5X'";Page 1 Customer Name ------------- No record listed

6-53

Page 160: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The IN OperatorUse the IN operator to select records that have some attribute values within a set of provided values. A value list enclosed by parentheses represents the value of the set.

The next example uses the IN operator to display the staff members who work in the BUS, FA, PSY, or ENG departments:

sql> SELECT LNAME,DEPT FROM STAFF sql> WHERE DEPT IN ("BUS","FA","PSY","ENG");Page 1Last Nam Dept-------- ----Eades FAMasters PSYAaron PSYFisher BUSJames PSYCarnes ENGOtis FAFried BUS8 records listed

Note: The IN operator is a convenient shorthand representation for conditions connected by the OR operators.

Using NOT with IN

The next example uses the NOT operator with the IN operator to specify rows that have a value not in the list.

The SELECT statement retrieves the names of the tapes that do not belong to any of the A, B, C, or D categories.

sql> SELECT NAME,CATEGORIES FROM TAPES sql> WHERE EVERY CATEGORIES NOT IN ("A","B","C","D");Page 1Tape Name Type of Vide-------------------- ------------Scaramouche MGone With The Wind R Tammy RLove Story R TJFlash Gordon S K7 records listed

6-54 Using UniData SQL

Page 161: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Using EVERY and NOT IN

The next example lists customer names, the tapes they have rented, and the tape categories for those customers who have rented tapes of categories other than A through D. This example also sorts the results by customer names.

sql> SELECT C.NAME,T.NAME,CATEGORIESsql> FROM CUSTOMER C,TAPES Tsql> WHERE TAPES_RENTED = T.@IDsql> AND EVERY CATEGORIES NOT IN ("A","B","C","D")sql> ORDER BY C.NAME;Page 1Customer Name Tape Name Type of Vide--------------- -------------------- ------------Best, George Love Story R TJChase, Carl Flash Gordon S KJones, Mable Gone With The Wind RJones, Samuel Flash Gordon S KPartner, Bonnie Love Story R TJPartner, Bonnie Tammy R6 records listed

Selecting Records within a RangeUse the BETWEEN operator to select rows that have attribute values within a certain range. BETWEEN X and Y means greater than or equal to X and less than or equal to Y.

The next example uses the BETWEEN operator to show the tapes that were rented between “04/19/87 and “04/22/87” and who rented them:

sql> SELECT NAME,TAPES_RENTED,DATE_OUTsql> FROM CUSTOMERsql> WHERE DATE_OUT BETWEEN "04/19/94" AND "04/22/94";Page 1Customer Name Tapes Date Out--------------- ---------- --------Chase, Carl V8481 04/20/94 V1254 04/20/94 V4951 04/21/94Faber, Harry V5151 04/19/942 records listed

6-55

Page 162: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Using NOT with BETWEEN

The next example uses the NOT operator with the BETWEEN operator to display the staff members who have salaries less than $30,000 and more than $50,000:

sql> SELECT LNAME,SAL FROM STAFF sql> WHERE SAL NOT BETWEEN 30000 AND 50000;Page 1 Last Nam Salary-------- -------Aaron 19,900Carnes 29,900Otis 25,800Gibson 26,800Fried 98,0005 records listed

6-56 Using UniData SQL

Page 163: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Sorting Query ResultsUse the ORDER BY clause to sort SELECT statement results.

This section provides examples that show you ways to use the ORDER BY clause to arrange query results in UniData SQL:

In ascending order.In descending order.Based on multiple attributes.Combining order operators.Based on multivalued attributes.Combining with UNNEST on multivalued attributes.Based on an association.Using the EXP keyword.

Sorting in Ascending OrderTo arrange a query result in a certain order, you can use the ORDER BY clause. You can order data in ascending or descending order with the ASC (default) and DESC keywords, respectively.

The next example shows you how to select the rows in the STAFF table which list the names in ascending order, which is the default:

sql> SELECT LNAME FROM STAFF ORDER BY LNAME;Page 1Last Nam--------AaronCarnesEadesFisherFriedGibsonJamesMastersOtis9 records listed

6-57

Page 164: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Sorting in Descending OrderYou can request results to display in descending order. To accomplish this, place the DESC operator immediately after the attribute name, as illustrated in the next example:

sql> SELECT NAME,NBR_TAPES FROM CUSTOMERsql> ORDER BY NBR_TAPES DESC;Page 1Customer Name Nbr T--------------- -----Chase, Carl 3Smith, Harry 3Jones, Mable 2Jones, Samuel 2Partner, Bonnie 2Barrie, Dick 1Best, George 1Bowie, David 1Faber, Harry 1Fischer, Carrie 1James, Bob 1...Grundy, Robin 0LaRue, Karma 0 Smith, Leif 0Steven Spender 0Valenzuela, 0CarmenWagner, Esther 0Wagner, Pat 029 records listed

Sorting by Multiple AttributesUniData SQL enables you to determine the order of query results based on several attributes, as follows:

First, UniData SQL begins to order the selected rows according to the first attribute in an ORDER BY list. Second, within each group of equal valued first attribute rows, UniData SQL orders records according to the second attribute in the ORDER BY list, and so on.

6-58 Using UniData SQL

Page 165: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The next example shows how to create a list of staff names ordered alphabetically by department:

sql> SELECT LNAME,DEPT FROM STAFFsql> ORDER BY DEPT,LNAME;Page 1Last Nam Dept-------- ----Fisher BUSFried BUSCarnes ENGEades FAOtis FAAaron PSYJames PSYMasters PSYGibson SPA9 records listed

Note: If you do not specify an attribute name in an ORDER BY clause, then the ordering of that attribute’s values is undetermined.

6-59

Page 166: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Combining Ascending and Descending OperatorsThe next example demonstrates how to combine ascending and descending order operators within a single query:

sql> SELECT CITY,NAME FROM CUSTOMER sql> ORDER BY CITY DESC,NAME;Page 1City Customer Name---------- ---------------Seattle Jamieson, DaleSan Jose Darrell CordenRutherford Jones, SamuelOverton Bowie, DavidNew York Fischer, CarrieMilwaukee Faber, HarryMilwaukee Jones, MableLos Angele Byles, MarcysLakewood Partner, BonnieKenosha Barrie, Dick...Denver LaRue, Karma Denver Smith, Leif Denver Steven SpenderDenver Wagner, PatChicago Boorman, RickChicago Fellini, J. Hoboken Chicago Jones, Freddie Boulder Belafonte, HarryBoulder Smith, Harry Arvada Jones, Bob29 records listed

Sorting Based on Multivalued AttributesThe next example shows the interaction between multivalued attributes and the ORDER BY clause. This example illustrates how UniData SQL selects rows in the STUDENT table. UniData SQL lists the students in ascending order by semester.

6-60 Using UniData SQL

Page 167: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Notice that the result is not in perfect ascending order by semester because semester is a multivalued attribute. If you do not UNNEST a multivalued attribute, UniData SQL treats it as a whole value, no matter how many multivalues are actually in it.

sql> SELECT @ID,LNAME,SEMESTERsql> FROM STUDENTsql> ORDER BY SEMESTER;Page 1 STUDENT Last Name Term------------ --------------- ---- 221-34-5665 Miller FA93 SP94 414-44-6545 Offenbach FA93 SP94 521-81-4564 Smith FA93 SP94 978-76-6676 Muller FA93 SP94 291-22-2021 Smith SP94 424-32-5656 Martin SP946 records listed

Unnesting and Sorting Based on Multivalued AttributesThe next example shows how to achieve the correct order with the help of the UNNEST operator. When ordering the result based on multivalued attributes, always remember to completely unnest the result to achieve a perfect order.

sql> SELECT @ID,LNAME,SEMESTERsql> FROM STUDENTsql> UNNEST SEMESTERsql> ORDER BY SEMESTER;Page 1 STUDENT Last Name Term------------ --------------- ---- 221-34-5665 Miller FA93 414-44-6545 Offenbach FA93 521-81-4564 Smith FA93 978-76-6676 Muller FA93 221-34-5665 Miller SP94 291-22-2021 Smith SP94 414-44-6545 Offenbach SP94 424-32-5656 Martin SP94 521-81-4564 Smith SP94 978-76-6676 Muller SP9410 records listed

6-61

Page 168: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Unnesting an Association and SortingThe next example shows how UNNEST affects the ordering of multivalued and multi-subvalued attributes when you use ASSOCIATION names in the UNNEST statement:

sql> SELECT @ID,LNAME,SEMESTER,COURSE_NBR,COURSE_GRDsql> FROM STUDENTsql> UNNEST CGAsql> ORDER BY COURSE_GRD;Page 1 STUDENT Last Name Term Crs # GD------------ --------------- ---- ----- --- 521-81-4564 Smith FA93 CS130 A 521-81-4564 Smith SP94 PE220 A 978-76-6676 Muller FA93 FA120 A 978-76-6676 Muller SP94 FA121 A 221-34-5665 Miller FA93 MA220 B 221-34-5665 Miller FA93 PY100 B 221-34-5665 Miller SP94 EG140 B 221-34-5665 Miller SP94 EG240 B 221-34-5665 Miller SP94 MA221 B 291-22-2021 Smith SP94 FA100 B 414-44-6545 Offenbach SP94 CS105 B 521-81-4564 Smith FA93 CS100 B...414-44-6545 Offenbach SP94 MA102 CPage 2 STUDENT Last Name Term Crs # GD------------ --------------- ---- ----- --- 414-44-6545 Offenbach SP94 PY100 C 424-32-5656 Martin SP94 PE100 C 424-32-5656 Martin SP94 PY100 C 978-76-6676 Muller FA93 FA230 C 978-76-6676 Muller FA93 HY101 C 414-44-6545 Offenbach FA93 CS104 D 978-76-6676 Muller SP94 HY102 I27 records listed

Sorting and UnnestingAnother way to order query results with multivalued attributes is to use the EXP keyword in the ORDER BY clause. When you use EXP, UniData SQL unnests all multivalues.

6-62 Using UniData SQL

Page 169: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

For example, listing student grades from A to I using EXP yields the same result as in the previous example:

sql> SELECT @ID,LNAME,SEMESTER,COURSE_NBR,COURSE_GRDsql> FROM STUDENTsql> ORDER BY COURSE_GRD EXP;Page 1 STUDENT Last Name Term Crs # GD------------ --------------- ---- ----- --- 521-81-4564 Smith FA93 CS130 A 521-81-4564 Smith SP94 PE220 A 978-76-6676 Muller FA93 FA120 A 978-76-6676 Muller SP94 FA121 A 221-34-5665 Miller FA93 MA220 B 221-34-5665 Miller FA93 PY100 B 221-34-5665 Miller SP94 EG140 B 221-34-5665 Miller SP94 EG240 B 221-34-5665 Miller SP94 MA221 B 291-22-2021 Smith SP94 FA100 B 414-44-6545 Offenbach SP94 CS105 B 521-81-4564 Smith FA93 CS100 B...414-44-6545 Offenbach SP94 MA102 CPage 2 STUDENT Last Name Term Crs # GD------------ --------------- ---- ----- --- 414-44-6545 Offenbach SP94 PY100 C 424-32-5656 Martin SP94 PE100 C 424-32-5656 Martin SP94 PY100 C 978-76-6676 Muller FA93 FA230 C 978-76-6676 Muller FA93 HY101 C 414-44-6545 Offenbach FA93 CS104 D 978-76-6676 Muller SP94 HY102 I27 records listed

6-63

Page 170: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

SubqueriesSubqueries enable you to perform multiple queries within a single statement. With subqueries, you can do the following:

Relate information in more than one table.Build dynamic search conditions — conditions that change based on the data currently stored in a table.Nest subqueries within subqueries.Write more complex SELECT, INSERT, DELETE, or UPDATE statements.

This section provides the following examples using subqueries:

Combining multiple queries into a single statement.Qualifying comparisons with ANY, ALL and IN.Writing compound subqueries.Passing data from the main query to a subquery.

Combining Multiple Queries into a Single QueryThe following example shows two ways to achieve a desired result:

Perform two separate queries.Combine the two queries into a single query.

The following two examples show how to perform two separate queries. The goal of these examples is to find the department where professor Otis works and all the employees from that department.

The first example finds the department where professor Otis works:

sql> SELECT LNAME,DEPT FROM STAFF WHERE LNAME ="Otis";Page 1Last Nam Dept-------- ----Otis FA1 records listed

6-64 Using UniData SQL

Page 171: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The second example lists all the employees of the FA department where professor Otis works:

sql> SELECT LNAME,DEPT FROM STAFF WHERE DEPT = "FA";Page 1Last Nam Dept-------- ----Eades FAOtis FA2 records listed

The following example combines the preceding two queries into a single query to produce the same result set. This example lists all employees in the same department as professor Otis.

sql> SELECT LNAME,DEPT FROM STAFFsql> WHERE DEPT = (SELECT DEPTsql> FROM STAFF WHERE LNAME = "Otis");Page 1Last Nam Dept-------- ----Eades FAOtis FA2 records listed

Note: You must enclose subqueries in parentheses.

Using ANY, ALL, and IN with SubqueriesPart of the power of subqueries is their ability to return a set of values. Use the ANY or ALL operators to indicate whether you intend to match any or all of the values the subquery returns. In addition, you can use the IN operator to mean the same thing as =ANY, and use the NOT IN operator to mean the same the same thing as !=ALL.

6-65

Page 172: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Using the ANY Operator

The next example uses the ANY operator to show who outside the “PSY” department has a higher salary than any of the “PSY” department staff:

sql> SELECT LNAME,TITLE,SAL,DEPTsql> FROM STAFFsql> WHERE SAL >ANY (SELECT SAL sql> FROM STAFF WHERE DEPT = "PSY")sql> AND DEPT != "PSY";Page 1Last Nam Title Salary Dept-------- ------- ------- ----Eades Prof 42,000 FAFisher Prof 31,200 BUSCarnes Prof 29,900 ENGOtis AscProf 25,800 FAGibson Prof 26,800 SPAFried Dean 98,000 BUS6 records listed

Tip: If you do not specify which operator to use, UniData SQL uses ANY.

Using the ALL Operator

The next example shows how to query with the ALL operator. This example shows who outside the “PSY” department has a higher salary than everyone in the “PSY” department.

sql> SELECT LNAME,TITLE,SAL,DEPT sql> FROM STAFFsql> WHERE SAL >ALL (SELECT SALsql> FROM STAFF WHERE DEPT = "PSY")sql> AND DEPT !="PSY";Page 1Last Nam Title Salary Dept-------- ------- ------- ----Eades Prof 42,000 FAFried Dean 98,000 BUS2 records listed

6-66 Using UniData SQL

Page 173: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Using the IN Operator

The next example uses the IN operator. The example shows which students, whose major is not “PY,” take “PY” courses.

sql> SELECT LNAME,MAJOR,COURSE_NBRsql> FROM STUDENTsql> WHERE MAJOR != "PY"sql> AND COURSE_NBR IN (SELECT COURSE_NBRsql> FROM STUDENT WHERE MAJOR = "PY");Page 1Last Name Majo Crs #--------------- ---- -----Smith CH PY100Offenbach CS PY100Miller EG PY1003 records listed

Writing Compound QueriesUniData SQL enables you to combine simple UniData SQL statements to construct complex statements. The WHERE clause of a query can contain a combination of standard search conditions, join conditions and multiple subqueries.

Using the EVERY Operator

The next example illustrates a relatively complicated set of conditions that Harry Smith, a customer in the video store, must meet. Harry is a friend of two other customers, Carl Chase and Mr. Jones, and for the most part he relies on their taste.

The list of movies Harry wants to see includes:

The tapes rented by Carl, except comedies; Harry does not like Carl’s choice of comedies.The tapes rented by Jones, except romances; Harry does not like Jones’ romances.Horror films in stock. They are his true, secret passion.

The tape list has two parts:

The first part includes those tapes where the IDs match any of the values the subquery returns.The second part includes those tapes with category “H”.

6-67

Page 174: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The subquery also has two parts:

The first part represents the tastes of Smith’s friends and the exceptions.The second part specifies a join condition, because the customer name and tape category belong to different tables and should be related by tape IDs.

In this example, the EVERY operator in the subquery is necessary, because CATEGORIES is a multivalued attribute. Without EVERY, UniData SQL selects those tapes with “C” or “R” and other categories.

sql> SELECT @ID,NAME,CATEGORIES FROM TAPESsql> WHERE @ID IN (SELECT T.@ID FROM CUSTOMER C,sql> TAPES T WHERE ((C.NAME = "Chase, Carl" ANDsql> EVERY CATEGORIES != "C") OR (C.NAME LIKEsql> "...Jones..." AND EVERY CATEGORIES != "R"))sql> AND T.@ID = TAPES_RENTED)sql> OR CATEGORIES = "H";Page 1TAPES Tape Name Type of Vide---------- -------------------- ------------V9431 Help K C MV4499 Psycho H DV8481 'Round Midnight M DV1254 Flash Gordon S KV2001 Blue Velvet HV4341 Z P DV996 Citizen Kane HV5151 To Kill A H Mockingbird8 records listed

6-68 Using UniData SQL

Page 175: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The following is another example of using a compound subquery. This example lists students who receive an “A” in any five credit hour courses. The subquery selects the COURSES table and returns a list of course numbers that have five credits. The main query then compares each value in the COURSE_ GRD and COURSE_NBR attri-butes and, if the grade is “A” and the course number is in the list, UniData SQL selects the row.

sql> SELECT LNAME,COURSE_NBR,COURSE_GRD,CREDITSsql> FROM STUDENT,COURSESsql> WHERE (COURSE_GRD = "A"sql> AND COURSE_NBR IN (SELECT @ID FROM COURSESsql> WHERE CREDITS = 5))sql> AND COURSE_NBR = COURSES.@ID;Page 1Last Name Crs # GD Credi--------------- ----- --- -----Muller FA120 A 5Smith CS130 A 52 records listed

The next example shows three levels of subqueries. In this example, you must use the EVERY operator because TAPES_RENTED is a multivalued attribute. This example shows the customers who did not rent any tapes in the Horror and Drama categories.

sql> SELECT CST.NAME,TAPES_RENTED,T.CATEGORIES,C.NAMEsql> FROM CUSTOMER CST,TAPES T,CATEGORIES Csql> WHERE EVERY TAPES_RENTED NOT IN (SELECT @ID FROM TAPESsql> WHERE CATEGORIES IN (SELECT @ID FROM CATEGORIESsql> WHERE NAME = "Horror" OR NAME = "Drama"))sql> AND TAPES_RENTED = T.@ID AND CATEGORIES = C.@IDsql> ORDER BY CST.NAME;Page 1Customer Name Tapes Type of Vide Category Type--------------- ---------- ------------ --------------------Best, George B2297 R RomanceBest, George B2297 TJ Tear JerkerBowie, David V9961 A Avant GardeBowie, David V9961 S Science FictionFischer, Carrie V110 C ComedyFischer, Carrie V110 O Old ClassicJones, Freddie V9431 C ComedyJones, Freddie V9431 K Childrens MovieJones, Freddie V9431 M MusicalPartner, Bonnie B2297 R RomancePartner, Bonnie B2297 TJ Tear JerkerPartner, Bonnie B914 R Romance12 records listed

6-69

Page 176: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Passing Data from Query to SubqueryYou can structure your queries so that information from the topmost level query is passed to a subquery. This is called a correlated subquery. This is useful when performing repeated analyses of information.

The following example uses the STAFF table to determine which staff members are paid the least in their department:

sql> SELECT DEPT,LNAME,SAL,TITLE FROM STAFF Xsql> WHERE SAL <=ALL(SELECT SAL FROM sql> STAFF WHERE X.DEPT=DEPT);Page 1Dept Last Nam Salary Title---- -------- ------- -------PSY Aaron 19,900 Counsel orBUS Fisher 31,200 ProfENG Carnes 29,900 ProfFA Otis 25,800 AscProfSPA Gibson 26,800 Prof5 records listed

Note: In correlated queries when a label or alias from the main query appears in the conditional clause of the nested query, UniData SQL correlates, or synchronizes, the two queries.

6-70 Using UniData SQL

Page 177: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Group FunctionsIn addition to selecting data from individual rows in a table, UniData SQL enables you to extract summary information from some groups of rows.

Remember the following when executing group functions:

You should unnest: (1) multivalued and multi-subvalued attributes used in a group function and (2) an attribute that is included in a GROUP BY clause.The null value is ignored by group functions except COUNT(*).

You can perform the following group functions on a specific attribute.

Group Functions

Function Description

AVG Computes the average value.

SUM Computes the total value.

MIN Returns the minimum value.

MAX Returns the maximum value.

COUNT Counts the number of values.

COUNT(*) Counts the number of rows.

NUMBER Counts the number of records in a table.

STD Computes standard deviation.

VARIANCE Computes the sqare of the standard deviation.

Selecting Summary Information from One GroupThis section shows you how to use group functions to compute summary information from just one group.

6-71

Page 178: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Using the AVG Operator

In the next example, the query requests the price and income from the tapes that generate above average revenue. To process the query, UniData SQL performs the following steps:

1. Retrieves a tape in the main query and uses the categories from that tape in the subquery.

2. Averages the income for all the tapes that belong to any category from the first tape.

3. Passes this average back to the main query and compares the incomes. If the income from the tape is greater than the average, UniData SQL returns the income from that tape, otherwise it bypasses it.

Note: The second label Y is not required. You can use it to clarify the query.

sql> SELECT NAME,RENTAL_PRICE,INCOME,CATEGORIESsql> FROM TAPES Xsql> UNNEST CATEGORIESsql> WHERE INCOME > (SELECT AVG(INCOME)sql> FROM TAPES Ysql> WHERE X.CATEGORIES = Y.CATEGORIES);Page 1Tape Name Retail C Tape Rev Type of Vide-------------------- -------- -------- ------------2001 6.75 985.50 S2001 6.75 985.50 DCitizen Kane 4.54 104.42 O’Round Midnight 6.75 452.25 M’Round Midnight 6.75 452.25 DAmerican Graffiti 2.50 242.50 KSleuth 4.50 279.00 DZ 4.54 104.42 PPsycho 4.54 154.36 HCatch 22 5.50 786.50 CCatch 22 5.50 786.50 AGone With The Wind 3.54 311.52 R12 records listed

6-72 Using UniData SQL

Page 179: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Using SUM

In the next example, UniData SQL uses all of the rows in the CUSTOMER table to compute the SUM, since no search condition is stated. UniData SQL returns only one sum value. This example shows the total number of tapes held by all the customers.

sql> SELECT SUM(NBR_TAPES)sql> FROM CUSTOMER;Page 1SUM(N----- 21 29 record(s) calculated

Using MIN

The following example uses the MIN group function to show the minimum number of tapes rented by one customer:

SELECT MIN(NUM_RENTALS)FROM CUSTOMER;Page 1MIN(Tota-------- 1.0000 29 record(s) calculated

Using MAX

The next example uses the MAX group function to show the maximum number of tapes rented by one customer:

sql> SELECT MAX(NUM_RENTALS)sql> FROM CUSTOMER;Page 1MAX(Tota-------- 33.0000 30 record(s) calculated

6-73

Page 180: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Using COUNT

The next example uses the COUNT group function to count the number of values of a specific attribute in the query. The example shows how many staff members have a salary greater than $30,000.

sql> SELECT COUNT(LNAME)sql> FROM STAFFsql> WHERE SAL >30000;Page 1CNT(Last-------- 5 5 record(s) calculated

Using COUNT(*)

If you need to know only the number of rows that satisfy the criteria and you do not care if the specific attribute is indicated, you can use COUNT(*) instead of COUNT(attribute_name).

Tip: Use COUNT(*) to count rows that may contain the null value. COUNT(attribute_name) excludes from the count rows that contain the null value in attribute_name.

This example is similar to the previous one, but it uses COUNT (*) instead of COUNT:

sql> SELECT COUNT(*) FROM STAFFsql> WHERE SAL >30000;Page 1COUNT(*)-------- 5 5 record(s) calculated

6-74 Using UniData SQL

Page 181: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Multiple Group FunctionsThe next example shows how you can use more than one group function in one SELECT clause. This example shows the maximum, minimum, average, and total salaries in the PSY department:

sql> SELECT MAX(SAL),MIN(SAL),AVG(SAL),SUM(SAL)sql> FROM STAFFsql> WHERE DEPT = "PSY";Page 1MAX(Sal MIN(Sal AVG(Sal SUM(Sal------- ------- ------- ------- 35,800 19,900 29,400 88,2003 record(s) calculated

Correct and Incorrect Group Function UseThe select list in a SELECT statement containing group functions cannot contain attribute names not listed in the GROUP BY clause. Since an attribute name is an attribute of each row, and a group function is an attribute of each group of rows, they result in a different number of values.

For example, if you want to find the name and department of the staff member who receives the highest pay, do not use the following query:

sql> SELECT LNAME,DEPT,MAX(SAL) FROM STAFF;

Instead of using the query in the previous example, you should use the query in next example:

sql> SELECT LNAME,DEPT,SAL FROM STAFFsql> WHERE SAL = (SELECT MAX(SAL)sql> FROM STAFF);Page 1Last Nam Dept Salary-------- ---- -------Fried BUS 98,0001 records listed

6-75

Page 182: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Using DISTINCT and COUNT with AttributesThe next example uses DISTINCT to show the different majors the students have chosen:

sql> SELECT DISTINCT MAJOR FROM STUDENT;Page 1Majo----CHCSEGFAPY5 records listed

The next example uses COUNT and DISTINCT to show the number of different majors chosen by students:

sql> SELECT COUNT (DISTINCT MAJOR) FROM STUDENT;Page 1CNT(DT M-------- 5 8 record(s) calculated

Writing Column HeadingsIn previous example, the headings displayed in the query result are “Majo” and “CNT(DT M”. Because these headings may not be meaningful, you can use attribute labels to specify headings.

Attribute labels are character strings surrounded by quotation marks that follow the attribute name or group function you want to label. When you stipulate an attribute label, UniData SQL displays the label as the column heading in the output. For instance, the next example designates the label “Sum Rent” in the query to show the total rental income represented in the CUSTOMER table:

sql> SELECT SUM(NUM_RENTALS) "Sum Rent"sql> FROM CUSTOMER;Page 1Sum Rent--------300.0000

29 record(s) calculated

6-76 Using UniData SQL

Page 183: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Selecting Summary Information from Multiple GroupsThe group function is a powerful tool for solving business problems, especially when used on grouped data. In UniData SQL, use group functions to extract summary information from multiple groups. For example, suppose you want to compute the number of tapes in each category. Use the UniData SQL GROUP BY operator to conveniently retrieve the data, rather than issuing a dozen similar queries for each category.

Using COUNT with GROUP BY

The next query uses the attribute name CATEGORIES in the SELECT clause with a group function.

The example lists the number of tapes by categories. First, UniData SQL divides the tapes into groups based on their categories. Then, UniData SQL applies COUNT to each group to get the final result.

sql> SELECT CATEGORIES,COUNT(*) "Total" FROM TAPESsql> GROUP BY CATEGORIES;Page 1Type of Vide Total------------ --------A 3B 1C 4D 10H 4K 3M 3O 2P 2R 3S 4TJ 1 ======== 40 12 records listed

The GROUP BY clause always follows the WHERE clause. If there is no WHERE clause in the query, GROUP BY follows the FROM clause.

6-77

Page 184: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Including Multiple Attribute Names in a GROUP BY ClauseThe next example illustrates how you can group data based on more than one attribute. The example illustrates the following:

It divides all staff members by department and by title within the department.It computes average salary of each group.It orders the result by the department name.

sql> SELECT DEPT,TITLE,AVG(SAL) "Avg.Sal"sql> FROM STAFFsql> GROUP BY DEPT,TITLEsql> ORDER BY DEPT;Page 1Dept Title Avg.Sal---- ------- -------BUS Dean 98,000BUS Prof 31,200ENG Prof 29,900FA AssProf 25,800FA Prof 42,000PSY AscProf 32,500PSY Assprof 35,800PSY Counsel 19,900 orSPA Prof 26,800 ======= 37,989 9 records listed

Specifying a Search Condition for GroupsUniData SQL enables you to specify search conditions for group functions with the HAVING clause. The HAVING clause works on data that UniData SQL has grouped in a GROUP BY clause. UniData SQL passes only those groups that satisfy HAVING conditions to a final result.

6-78 Using UniData SQL

Page 185: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Using the HAVING Clause

The HAVING clause always follows the GROUP BY clause, as shown in the next example. This example shows which categories include more than one tape:

sql> SELECT CATEGORIES,COUNT(*)sql> FROM TAPESsql> GROUP BY CATEGORIESsql> HAVING COUNT(*) >1;Page 1Type of Vide COUNT(*)------------ --------A 3C 4D 10H 4K 3M 3O 2P 2R 3S 4 ======== 38 10 records listed

Using a Subquery in a HAVING Clause

UniData SQL enables you to use a subquery within a HAVING clause to compare an attribute of a group with a computed attribute of another group.

6-79

Page 186: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The next example uses a subquery in a HAVING clause to show which category of tapes has an average rental price greater than the average rental price of all the tapes:

sql> SELECT CATEGORIES,AVG(RENTAL_PRICE) sql> FROM TAPESsql> GROUP BY CATEGORIESsql> HAVING AVG(RENTAL_PRICE) >sql> (SELECT AVG(RENTAL_PRICE) FROM TAPES);Page 1Type of Vide AVG(Reta------------ --------A 4.77B 4.40C 3.76D 4.60H 4.09M 5.01P 4.04S 4.75 ======== 4.46 8 records listed

Combining WHERE and HAVING

The next example illustrates how to use the WHERE clause and the HAVING clause together. This example shows which departments have at least one professor. The UniData SQL statement does the following:

Uses the WHERE clause to select qualified rows.Uses the GROUP BY clause to form the groups.Uses the HAVING clause to qualify the groups.

6-80 Using UniData SQL

Page 187: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The following example lists the departments and the number of professors in each. Departments that have no professors assigned to them are excluded from the list.

sql> SELECT DEPT,COUNT(*)sql> FROM STAFFsql> WHERE TITLE = "Prof"sql> GROUP BY DEPTsql> HAVING COUNT(*) >= 1;Page 1Dept COUNT(*)---- --------BUS 1ENG 1FA 1SPA 1 ======== 4 4 records listed

Group Functions with Multivalued AttributesWhen you use group functions on a multivalued attribute, you must use an UNNEST clause to produce the correct result. The following two examples show how COUNT works with and without UNNEST.

Using COUNT without UNNEST

The next example uses COUNT without UNNEST in an attempt to determine how many courses are being taken by students. This statement yields the number of students who are taking a course, not the number of courses being taken. The result is incorrect because the multivalued attribute COURSE_NBR is not unnested.

sql> SELECT COUNT(COURSE_NBR) FROM STUDENT;Page 1CNT(Crs-------- 8 8 record(s) calculated

6-81

Page 188: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Using COUNT with UNNEST

The next example uses the same query as in the previous example with UNNEST to obtain the expected result:

sql> SELECT COUNT(COURSE_NBR) FROM STUDENT sql> UNNEST CGA;Page 1CNT(Crs-------- 36

32 record(s) calculated

6-82 Using UniData SQL

Page 189: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Expressions and FunctionsTo enhance your ability to access information in your database, UniData SQL enables you to use various expressions and functions in query statements. There are three kinds of expressions and functions:

ArithmeticCharacterDate

Note: Up to this point, you have used attribute names, attribute labels, and group functions in SELECT clauses. The following examples demonstrate how to use expressions within SELECT statements and group functions.

The examples provided in this section are:

Arithmetic expressions.Arithmetic functions.Arithmetic expressions with multivalued attributes and REUSE.Arithmetic expressions and functions in group functions.Character string functions.Date functions.

Arithmetic ExpressionsAn arithmetic expression is made up of an attribute name or constant values connected by any of the following arithmetic operators.

Arithmetic Operators

Operator Function

+ Addition

- Subtraction

* Multiplication

/ Division

6-83

Page 190: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Note: When you use an expression in a SELECT clause, UniData SQL displays the expression as an attribute heading, unless you specify an attribute label or column heading. Also, UniData SQL displays the expression attribute with a column width equal to the length of the expression, even if you specify a new column heading.

The Addition Operator

The next example uses the addition operator (+) to show the result of adding a service charge to all accounts at the video store:

sql> SELECT NAME,NUM_RENTALS,CUR_BALANCE + 5 sql> FROM CUSTOMERsql> WHERE NUM_RENTALS < 5;Page 1Customer Name Total Re CUR_BALANCE+5--------------- -------- -------------James, Bob 1 8.7500Faber, Harry 2 8.5400Jones, Freddie 4 9.50003 records listed

6-84 Using UniData SQL

Page 191: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The Division Operator

The next example uses the division operator (/) to show those customers who have a current balance greater than zero. The example orders the result based on the current balance of the customer divided by the number of tapes they have rented:

sql> SELECT NAME,NUM_RENTALS,CUR_BALANCE,sql> CUR_BALANCE/NUM_RENTALSsql> FROM CUSTOMERsql> WHERE CUR_BALANCE>0 AND NUM_RENTALS != 0sql> ORDER BY 4 DESC;

Page 1Customer Name Total Re Currentl CUR_BALANCE/NUM_RENTALS--------------- -------- -------- -----------------------James, Bob 1 3.75 3.7500Jones, Samuel 5 9.90 1.9800Faber, Harry 2 3.54 1.7700Chase, Carl 11 12.40 1.1273Jones, Freddie 4 4.50 1.1250Jamieson, Dale 8 6.75 0.8438Jones, Bob 7 4.54 0.6486Smith, Harry 22 13.65 0.6205Jones, Mable 19 8.08 0.4253Barrie, Dick 12 4.54 0.3783Bowie, David 17 5.05 0.2971Fischer, Carrie 10 2.52 0.2520Partner, Bonnie 19 3.56 0.1874Best, George 15 2.50 0.166714 records listed

Multiple Arithmetic Operators

The next example uses multiple arithmetic operators (+ and /) to show what the salaries would be if you gave a 5 percent raise to those earning less than $20,000:

sql> SELECT LNAME,SAL +(SAL/20) "New Pay"sql> FROM STAFFsql> WHERE SAL <20000;Page 1Last Nam New Pay-------- ------------Aaron 208951 records listed

6-85

Page 192: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Arithmetic FunctionsIn addition to arithmetic expressions using standard operators, arithmetic functions can be used in UniData SQL statements.

The POWER Function

The next example uses the POWER function to square the NUM_RENTALS attribute:

sql> SELECT NAME,POWER(NUM_RENTALS,2)sql> FROM CUSTOMERsql> WHERE NAME = "Wagner, Pat";Page 1Customer Name POWER(NUM_RENTALS,2)--------------- --------------------Wagner, Pat 161 records listed

Arithmetic Function Description

ABS (nvalue) Absolute value of nvalue.

ACOS (nvalue) Trigonometric arc-cosine of nvalue. The result is expressed as the degree of the arc-cosine of the nvalue, which ranges from 0 to 180.

ASIN (nvalue) Trigonometric arc-sine of nvalue. The result is expressed as the degree of the arc-sin of the nvalue, which ranges from -90 to 90.

ATAN (nvalue) Trigonometric arc-tangent of nvalue.

COS (nvalue) Cosine of nvalue. nvalue is expressed as degree.

EXP (nvalue) Raises “e” (natural exponential) by the value of nvalue.

INT (x) Integer value of x.

LN (nvalue) Natural log of nvalue.

MOD (nvalue, m) Remainder of nvalue divided by m.

POWER(nvalue, e) Raises the numeric value to the power e.

Arithmetic Functions

6-86 Using UniData SQL

Page 193: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The ROUND Function

The next example illustrates the ROUND function with a rounding factor of two decimal points. You can embed an expression within the function.

sql> SELECT NAME,NUM_RENTALS,sql> ROUND(CUR_BALANCE + 10,2) BALANCEsql> FROM CUSTOMERsql> WHERE NUM_RENTALS <14;Page 1Customer Name Total Re Balance--------------- -------- -----------------------Jones, Bob 7 14.54Steven Spender 3 10.00Jamieson, Dale 8 16.75Chase, Carl 11 22.40Wagner, Pat 4 10.00Wagner, Esther 5 10.00Doodle, Polly 3 10.00W....Boorman, Rick 12 10.00Byles, Marcy 2 10.0020 records listed

--------------- -------- -----------------------Carmen19 records listed

ROUND(nvalue, e) Rounds the nvalue to the number of decimal places specified by e.

SIGN(nvalue) Returns +1 if the nvalue is greater than zero, 0 if the nvalue is equal to zero, -1 if the nvalue is less than zero.

SIN (nvalue) Sine of nvalue. nvalue is expressed as degree.

SQRT (nvalue) Square root of nvalue; if nvalue is 0, returns 0.

TAN (nvalue) Tangent of nvalue. nvalue is expressed as degree.

TRUNC(nvalue{,d}) Truncates the nvalue to ddigits right of the decimal place. The default is 0.

Arithmetic Function Description

Arithmetic Functions (continued)

6-87

Page 194: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The TRUNC Function

In the next example, UniData SQL uses the TRUNC function to display the attribute CUR_BALANCE. Because no TRUNC parameter was used to indicate the number of decimals, UniData SQL defaults to zero decimal places. Notice that the column label appears in quotation marks since there is a space in the label name. UniData SQL does not round the balances in this case—it truncates.

sql> SELECT NAME,TRUNC(CUR_BALANCE) "Cur Bal" FROM CUSTOMERsql> WHERE CUR_BALANCE> 0.00;Page 1Customer Name Cur Bal--------------- ------------------Jones, Bob 4Jamieson, Dale 6Chase, Carl 12Fischer, Carrie 2James, Bob 3Bowie, David 5Jones, Samuel 9Smith, Harry 13Faber, Harry 3Jones, Freddie 4Jones, Mable 8Best, George 2Barrie, Dick 4Partner, Bonnie 37 records listed

To display one decimal place, use the following TRUNC function:

sql> SELECT NAME,TRUNC(CUR_BALANCE,1) "Cur Bal"sql> FROM CUSTOMERsql> WHERE CUR_BALANCE > 0.00;Page 1Customer Name Cur Bal--------------- --------------------Jones, Bob 4.5Jamieson, Dale 6.7Chase, Carl 12.4Fischer, Carrie 2.5James, Bob 3.7Bowie, David 5.0Jones, Samuel 9.9Smith, Harry 13.6Faber, Harry 3.5Jones, Freddie 4.5Jones, Mable 8.0Best, George 2.5Barrie, Dick 4.5Partner, Bonnie 3.514 records listed

6-88 Using UniData SQL

Page 195: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The SIGN Function

In the next example, SIGN returns the following values:

+1 if the value is greater than zero.0 if the value is zero.-1 if the value is less than zero.

sql> SELECT NAME,SIGN(CUR_BALANCE)sql> FROM CUSTOMER;Page 1Customer Name SIGN(CUR_BALANCE)--------------- -----------------Jones, Bob +1Frobisher, 0KamalSteven Spender 0Jamieson, Dale +1Chase, Carl +1Wagner, Pat 0Wagner, Esther 0Doodle, Polly 0W.Fischer, Carrie +1James, Bob +1Fischer, Carrie +1James, Bob +1Dillon, Matt 0Bowie, David +1Jones, Samuel +1...Partner, Bonnie +1Byles, Marcy 029 records listed

Multivalued Attributes and Arithmetic Functions

You should pay special attention to using multivalued attributes in arithmetic functions and expressions. For example, the next query yields an unexpected result because it does not include the keyword REUSE in the expression with the multi-valued attribute STD_NO.

6-89

Page 196: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Notice that in this example, UniData SQL changes only the first student number of each record. To get the expected result, UniData SQL would need to add 10 to each student number in the STAFF table.

sql> SELECT LNAME,STD_NO "Old No",STD_NO + 10 "New No"sql> FROM STAFFsql> WHERE STD_NO <> "";Page 1Last Nam Old No New No-------- ------------ ---------Eades 978-76-6676 978766686 978-76-6676 978766676Fisher 414-44-6545 414446555Otis 221-34-5665 221345675 414-44-6545 4144465453 records listed

The REUSE Function

UniData SQL provides you with the REUSE function to solve the types of problems shown in the previous two examples.

The following example uses a single value (the value 10) in an expression with a multivalued attribute (STD_NO). To add this single value to every value of the multi-valued attribute, the query uses the REUSE function.

sql> SELECT LNAME,STD_NO "Old No",STD_NO + REUSE(10) "New No"sql> FROM STAFFsql> WHERE STD_NO <> "";Page 1Last Nam Old No New No-------- ------------ ----------------Eades 978-76-6676 978766686 978-76-6676 978766686Fisher 414-44-6545 414446555Otis 221-34-5665 221345675 414-44-6545 4144465553 records listed

6-90 Using UniData SQL

Page 197: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Arithmetic Expressions and Functions in Group FunctionsYou can use arithmetic expressions and functions in group functions. For instance, the next example displays the average salary of staff members in each department if everyone receives a $1,000 raise:

sql> SELECT DEPT,AVG(SAL),AVG(SAL + 1000),sql> SUM(SAL + 1000),COUNT(*)sql> FROM STAFFsql> GROUP BY DEPT;Page 1Dept AVG(Sal AVG(SAL+ SUM(SAL+ COUNT(*)---- ------- -------- -------- --------BUS 64,600 65600.00 131200.0 2 0ENG 29,900 30900.00 30900.00 1FA 33,900 34900.00 69800.00 2PSY 29,400 30400.00 91200.00 3SPA 26,800 27800.00 27800.00 1 ======= ======== ======== ======== 37,989 38988.89 350900.0 9 05 records listed

Note: Group functions cannot be used in an expression. Thus, expressions similar to AVG(SAL)+1000 or MAX(SAL)/MIN(SAL) are not allowed.

The next example computes the average of the square of credits for courses taught by each teacher:

sql> SELECT TEACHER,AVG(POWER(CREDITS,2))sql> FROM COURSES GROUP BY TEACHER;Page 1Teacher AVG(POWER(CREDIT---------- ----------------Aaron 14.3333Carnes 13.0000Fisher 9.0000Fried 14.3333Gibson 11.3333James 25.0000Masters 17.0000Otis 14.3333 ================ 13.9583 10 records listed

6-91

Page 198: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Character String FunctionsCharacter string functions enable you to include different types of formats in your query statements. For a complete list of the character string functions, see Developing UniBasic Applications or the UniBasic Commands Reference.

String Functions

String Function Description

ASCII (char) Converts EBCDIC to ASCII.

CHAR (x) Converts number to ASCII value.

DECODE(...) Translates the values in a column to a set of constants or values in other columns.

DOWNCASE Changes all uppercase characters to (string) lowercase.

ICONV Converts string or numeric data to internal (str.expr, represen-tation format based on conversion conv.code.expr) codes. For details, see Developing UniBasic Applications. You can also use this function for numeric or data conversion.

INITCAP(string) Capitalizes the first initial of a string.

INSTR Returns the starting position of the nth (str,substr, occur(rence) of substr in the string, str s.pos, occur) beginning at the position specified by s.pos.

OCONV Converts string or numeric data from internal (str.expr, repre-sentation format to output format based conv.code.expr) on conversion codes. For details, see Developing UniBasic Appli-cations or the UniBasic Commands Reference manual.

string1 || string2 Concatenates string1 with string2.

NVL Converts the null value to another string.

The Concatenation Function

Use the concatenation function (||) to combine several columns and/or constant values into a single display column.

6-92 Using UniData SQL

Page 199: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The next example uses the concatenation function to display a list of students and their majors. The example is formatted as last name, comma, and major.

sql> SELECT LNAME||","||MAJOR "Student, Major"sql> FROM STUDENT;Page 1Student, Major-----------------Smith,CHSmith,CSMartin,PYOffenbach,CSMiller,EGMuller,FA6 records listed

The LENGTH Function

The LENGTH function enables you to count the total number of characters in a string. For instance, the next example shows how to determine the length of each tape name in the TAPES table:

sql> SELECT NAME,LENGTH(NAME) "Name Length"sql> FROM TAPES;Page 1Tape Name Name Length-------------------- ------------2001 4A Clockwork Orange 18American Graffiti 18The Stalker 11Scaramouche 11Gone With The Wind 18Girl Friday 11...Catch 22 8To Kill A 21Mockingbird 023 records listed

6-93

Page 200: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The SUBSTR Function

The following example uses the SUBSTR function to extract a substring from a string. To tell UniData SQL to extract only a single character from each attribute, the query specifies a length parameter of 1. If no character is specified, the function includes all of the characters from the starting position to the end of the string. The first parameter is the starting position and the second is the length parameter.

The next example also uses the concatenation function to display the first letter from each attribute. This example uses the STUDENT table to display the students’ last names, first names and initials:

sql> SELECT FNAME,LNAME,SUBSTR(FNAME,1,1)||sql> SUBSTR(LNAME,1,1)Initialssql> FROM STUDENT;Page 1First Name Last Name Initials---------- --------------- -------------------------------Harry Smith HSjojo Smith jSSally Martin SMKarl Offenbach KOSusan Miller SMGerhardt Muller GM6 records listed

The INSTR Function

The INSTR function returns a number corresponding to the beginning position of a specified substring within a string. You can also specify where to begin searching in the string and which occurrence of the substring to look for. If no characters in the string match the specified substring, INSTR returns a zero.

6-94 Using UniData SQL

Page 201: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The next example looks for the first occurrence of the letter ‘s’ in the last names of each of member of the STAFF, starting at the beginning of the string:

sql> SELECT LNAME,INSTR(LNAME,"s",1,1) "s Position"sql> FROM STAFF;Page 1Last Nam s Position-------- --------------------Eades 5Masters 3Aaron 0Fisher 3James 5Carnes 6Otis 4Gibson 4Fried 09 records listed

The next example looks for the first and second occurrence of the letter ‘s’ in ‘Masters’, starting from the beginning of the string:

sql> SELECT LNAME,INSTR(LNAME, "s",1,1) "First s",sql> INSTR(LNAME,"s",1,2) "Second s"sql> FROM STAFFsql> WHERE LNAME = "Masters";Page 1Last Nam First s Second s-------- -------------------- --------------------Masters 3 71 records listed

6-95

Page 202: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The UPCASE and DOWNCASE FunctionsTo display data in upper- or lowercase, use a statement like the one in the next example:

sql> SELECT UPCASE (LNAME) "UPNAME",sql> DOWNCASE(TITLE) "LOTITLE"sql> FROM STAFF;Page 1UPNAME LOTITLE------------- ---------------EADES profMASTERS ascprofAARON counselorFISHER profJAMES ascprofCARNES profOTIS ascprofGIBSON profFRIED dean9 records listed

The INITCAP Function

The INITCAP function capitalizes the first character in a string. Use INITCAP as illustrated in the next example:

sql> SELECT INITCAP(FNAME),INITCAP(LNAME)sql> FROM STUDENTsql> WHERE INITCAP(FNAME) = "Jojo";Page 1INITCAP(FNAME) INITCAP(LNAME)-------------- --------------Jojo Smith1 records listed

The LPAD and RPAD FunctionsLPAD and RPAD perform similar functions. Both functions “pad” an attribute with a specific character. LPAD pads on the left and RPAD pads on the right. For example, if a column display width of the attribute NAME in the CUSTOMER table is 20 characters, and most of the names are shorter than 20 characters, pad the extra space in the column with dashes.

6-96 Using UniData SQL

Page 203: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The next example shows how to use RPAD:

sql> SELECT RPAD(NAME,30-LENGTH(NAME),"-") "Name",sql> TAPES_RENTEDsql> FROM CUSTOMERsql> WHERE TAPES_RENTED BETWEEN "V2000" AND "V6000";Page 1Name Tapes------------------------------ ----------Jones, Bob-------------------- V4341Chase, Carl------------------- V4951James, Bob-------------------- V2001Smith, Harry------------------ V2001 V5004Faber, Harry------------------ V5151Jones, Mable------------------ V44996 records listed

The TRANSLATE Function

The TRANSLATE function converts one character to another within a string. The next two examples illustrate how to use the TRANSLATE function.

The first example converts letter grades to number grades as follows:

sql> SELECT LNAME,COURSE_NBR,sql> TRANSLATE(COURSE_GRD,"A,B,C,D,F,I","4,3,2,1,0,0")sql> FROM STUDENT;Page 1Last Name Crs # TRANSLATE(COURSE_GRD,"A,B,C,D,F--------------- ----- -------------------------------Smith CS130 4 CS100 3 PY100 3 CS131 3 CS101 3 PE220 4Smith FA100 3Martin PY100 2 PE100 2Offenbach CS104 1 MA101 2...Muller FA120 4 FA230 2 HY101 2 FA121 4 FA231 3 HY102 06 records listed

6-97

Page 204: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The DECODE Function

The DECODE function enables you to translate any attribute value found in the search attribute with a constant or with the value found in a replacement attribute.

The next example displays the full title of each person in the STAFF table with DECODE, in the following manner:

1. TITLE is the first parameter listed and is the attribute that UniData SQL searches.

2. A list of pairs follows. The first member of each pair is the value to find in the TITLE attribute. The second member of the pair is the constant that replaces it.

3. Next, a constant value called Administrative Staff, is located at the end of the parameter list. This constant value serves as the default replacement constant for any value found in the TITLE attribute that UniData SQL did not previously list as one of the search values.

sql> SELECT LNAME,DECODE(TITLE,"Prof","Professor",sql> "AssProf","Assistant Professor","AscProf","Associatesql> Professor", "Administrative Staff") "Full Title"sql> FROM STAFF;Page 1Last Nam Full Title-------- -------------------------------Eades ProfessorMasters Administrative StaffAaron Administrative StaffFisher ProfessorJames Associate ProfessorCarnes ProfessorOtis Associate ProfessorGibson ProfessorFried Administrative Staff

6-98 Using UniData SQL

Page 205: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The next example uses another attribute value as the replacement value. This example compares the salaries of the administrative staff with the salaries of the teaching staff. The example displays the title held by each of the administrative staff, but lumps all of the teaching staff in the category “Teacher.”

sql> SELECT LNAME,DECODE (TITLE,"Dean", sql> TITLE,"Counselor",TITLE,"Teacher")sql> "Title",SAL FROM STAFF;Page 1Last Nam Title Salary-------- ------------------------------- -------Eades Teacher 42,000Masters Teacher 35,800Aaron Counselor 19,900Fisher Teacher 31,200James Teacher 32,500Carnes Teacher 29,900Otis Teacher 25,800Gibson Teacher 26,800Fried Dean 98,0009 records listed

Date FunctionsUniData SQL date functions perform arithmetic on internal-format dates.

UniData SQL stores the date as a simple integer, which enables you to perform addition and subtraction on a date. The output then becomes another meaningful date. However, if you subtract two dates, the result of the expression is a number of days. UniData SQL outputs the result as a date, not the number of days. Use a virtual attribute to solve this problem.

See the UniData SQL Commands Reference for date formatting options.

The next example uses a date function to show all customers whose tapes have been overdue for more than one month:

sql> SELECT NAME,MONTHS_BETWEEN (DATE_DUE,TODAY)"MOS"sql> FROM CUSTOMER WHERE MONTHS_BETWEEN(DATE_DUE,TODAY)>1;Page 1Customer Name MOS--------------- ------------------------------Steven Spender 2 2Partner, Bonnie 3 32 records listed

6-99

Page 206: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

7Chapter

Creating and Querying Views

What Is a View? . . . . . . . . . . . . . . . . . . . 7-3 How to Use Views . . . . . . . . . . . . . . . . . 7-3 How View Queries Are Processed . . . . . . . . . . . . 7-3Creating Views . . . . . . . . . . . . . . . . . . . 7-5 Creating a View from a Single Table . . . . . . . . . . . 7-5 Creating a View from Multiple Tables. . . . . . . . . . . 7-6 Creating a View Using Expressions . . . . . . . . . . . 7-7 Creating a View on a View . . . . . . . . . . . . . . 7-8Querying Views . . . . . . . . . . . . . . . . . . . 7-9 Optimizing Processing on View Queries . . . . . . . . . . 7-9Dropping Views . . . . . . . . . . . . . . . . . . . 7-14

Page 207: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

This chapter discusses how to create and use the VIEW facility. A view is a virtual table or file based on tables actually stored in the database.

When you complete this chapter, you should be able to complete the following tasks:

Understand what a view is.Understand how views are processed.Create a view.Query a view.Drop a view.

7-2

Page 208: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

What Is a View?UniData SQL does not separately store data in views. Instead, when you create a new view, UniData SQL creates a view dictionary that interprets data in the base table. You can insert, update, and delete attribute values through views that are based on a single base table (have not been created with a join). Views created by a join and views that contain an UNNEST clause or a group function are read-only.

View attributes are defined in the SELECT clause of the CREATE VIEW statement. They can be data, or virtual attributes, or expressions. You can specify new names for the attributes in the view; however, if you do not, the view attributes are named after the attribute that creates them.

Note: You cannot execute the ALTER TABLE command against a view. You must delete and re-create the view.

How to Use ViewsOnce you create a view, you can:

Query it as you would a base table.Use it to create other views.

How View Queries Are ProcessedUniData SQL processes queries on views in two ways:

Standard Method (materialization) – UniData SQL first stores the result of the view SELECT statement in a temporary file, then applies the query to the temporary file rather than the base table.Optimized View Query Processing Method (query transformation) – UniData SQL queries the underlying base table, thus eliminating the need for an intermediate temporary file.

Decision Support System (DSS) tools do not operate directly on the UniData nested relational tables or NF2 tables; they operate on 1NF views of those tables. In these cases, it is important for UniData SQL to be able to use the optimized view query processing method.

7-3 Using UniData SQL

Page 209: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

UniData SQL automatically uses the optimized method if your view definition meets certain criteria, which results in:

Better system performance when processing queries involving views.Enhanced performance of DSS tool queries.Use of alternate indexing when processing queries involving views.

For further information on using the optimized method for processing queries on views, see “Optimizing Processing on View Queries” on page 7-9 in this chapter.

7-4

Page 210: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Creating ViewsThis section provides examples of the following:

Creating a view from a single table.Creating a view from multiple tables.Creating a view using expressions.Creating a view on top of other views.

Syntax:

CREATE VIEW view_name [(attribute_name [{,attribute_name}...])] AS SELECT statement

Creating a View from a Single TableThe following example creates a view called C_DENVER that draws data from the CUSTOMER table. In this example, the view C_DENVER has the same attributes as the base table CUSTOMER, from which UniData SQL extracted the information. Also, the attribute names are the same. In this case, you can omit the attribute name definition in the CREATE VIEW statement.

sql> CREATE VIEW C_DENVER AS sql> SELECT * FROM CUSTOMER sql> WHERE CITY ="Denver";View C_DENVER created.

Note: Only the query_spec portion of the SELECT statement can be included in the CREATE VIEW statement.

7-5 Using UniData SQL

Page 211: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The next example establishes a view called MYSTAFF that lists staff members, but does not list salaries. The SELECT statement tells UniData SQL to extract the data from the STAFF table. After the view is created, data is selected from it.

sql> CREATE VIEW MYSTAFF (NAME,TITLE,DEPT,COURSES,TUTEE,BOSS) AS sql> SELECT LNAME,TITLE,DEPT,COURSES,STD_NO,SUPERVISOR sql> FROM STAFF;View MYSTAFF created.

sql> SELECT * FROM MYSTAFF sql> WHERE DEPT ='PSY';Page 1NAME TITLE Dept COURSES TUTEE BOSS-------- -------- ---- ------- ----- --------Masters Assprof PSY JamesAaron Counsel PSY JamesJames AscProf PSY Fried3 records listed

Tip: If you want the view to have different attribute names from what the base table already contains, you must specify the view attribute names in the CREATE VIEW clause. In addition, if at least one view attribute name is different from what the base table contains, all the attribute names must be specified in the CREATE VIEW statement.

Creating a View from Multiple TablesYou can create a view that derives data from more than one table. To do this, use a join query. For further information on joining tables, see Chapter 6, “The SELECT Statement.”

7-6

Page 212: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The following example shows how to create a view called RENTALS that is derived from the CUSTOMER and TAPES tables. After the view is created, data is selected from it:

sql> CREATE VIEW RENTALS sql> (CUSTOMER,TAPE,OUT,CHARGE) AS sql> SELECT X.NAME,Y.NAME,DATE_OUT,RENTAL_PRICE sql> FROM CUSTOMER X,TAPES Y sql> WHERE TAPES_RENTED = Y.@ID;

View RENTALS created.sql> SELECT * FROM RENTALSsql> WHERE TAPE = "Catch 22";Page 1CUSTOMER TAPE OUT CHARGE--------------- -------------------- -------- --------Smith, Harry Catch 22 04/24/87 5.501 records listed

Creating a View Using ExpressionsYou can use expressions to create views by entering them in an attribute list in the SELECT clause. Expressions are attribute names and constants connected by arith-metic, string, and date and time operators and functions. When you use expressions, you must assign new attribute names to the view attributes.

The following example creates a view called NEWBUDGET from the STAFF table. Once the view is created, the example selects data from it.

sql> CREATE VIEW NEWBUDGET (NAME,CURRSAL,NEWSAL) AS sql> SELECT LNAME,SAL,(SAL+(SAL*.05)) FROM STAFF;View NEWBUDGET created.

sql> SELECT * FROM NEWBUDGET;Page 1 NAME CURRSAL NEWSAL-------- ------- ---------------Eades 42,000 44100Masters 35,800 37590Aaron 19,900 20895Fisher 31,200 32760James 32,500 34125Carnes 29,900 31395Otis 28,800 30240Gibson 26,800 28140Fried 101,000 1060509 records listed

7-7 Using UniData SQL

Page 213: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Creating a View on a ViewYou can use views to define other views.

The following example defines a view called NEWBUDGET_1 that contains staff members who make more than $44,000. UniData SQL derives the data in NEWBUDGET_1 from the view called NEWBUDGET. Once the view is created, the example selects data from it.

sql> CREATE VIEW NEWBUDGET_1 AS sql> SELECT * FROM NEWBUDGET sql> WHERE CURRSAL > 44000;View NEWBUDGET_1 created.

sql> SELECT * FROM NEWBUDGET_1;Page 1NAME CURRSAL NEWSAL-------- ------- ---------------Fried 101,000 1060501 records listed

Note: Views and base tables can be used together to define new views.

7-8

Page 214: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Querying ViewsAfter you create a view, you can query it with a SELECT statement as you do a base table.

The next example uses a SELECT statement to query the view called C_DENVER:

sql> SELECT NAME,CITY,TAPES_RENTED,DATE_OUT sql> FROM C_DENVER;Page 1Customer Name City Tapes Date Out--------------- ---------- ---------- --------Frobisher, DenverKamalSteven Spender DenverWagner, Pat DenverDoodle, Polly DenverW.LaRue, Karma DenverSmith, Leif Denver6 records listed

Optimizing Processing on View QueriesUniData SQL automatically optimizes queries that involve views. This accomplishes the following:

Eliminates the need for storing the intermediate results in a temporary file.Enables you to use alternate indexing when processing queries involving views.

Using the optimized method, UniData SQL processes data straight from the base table.

For UniData SQL to use the optimized method for processing queries involving views, the view definition must meet the following criteria:

The view must be defined on a single table.The SELECT clause in the view definition cannot involve group functions.The SELECT statement in the view definition cannot contain the DISTINCT keyword.

7-9 Using UniData SQL

Page 215: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Optimizing Queries on Views Derived from a Single Table

The following example shows how UniData SQL optimizes queries on views. The first statement creates a view from the STAFF table which contains the attributes @ID, LNAME, TITLE, and SAL. The second statement creates another view called V2 from data found in the first view.

sql> CREATE VIEW V1 AS SELECT @ID,LNAME,TITLE,SAL FROM STAFF;

View V1 created.sql> CREATE VIEW V2 AS SELECT @ID,LNAME,TITLE FROM V1;

View V2 created.

The following example queries on the V2 view which you created in the previous example. Because the SELECT clause in the view definition meets the criteria for optimization, UniData SQL automatically optimizes processing of the query.

sql> SELECT * FROM V2;Page 1STAFF Last Nam Title---------- -------- -------3 Eades Prof6 Masters Ascprof9 Aaron Counsel or1 Fisher Prof4 James AscProf7 Carnes Prof2 Otis AscProf5 Gibson Prof8 Fried Dean9 records listed

7-10

Page 216: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

View Definitions That Prevent Optimization

The next example demonstrates examples of two cases in which UniData SQL cannot optimize the processing of queries. The first statement is a join of two tables (COURSES and STAFF), and the second statement contains a group function (SUM).

sql> CREATE VIEW V3 AS SELECT LNAME,COURSES,NAME FROMsql> STAFF,COURSES WHERE COURSES = COURSES.@ID;

View V3 created.

sql> CREATE VIEW V4 (DEPT,SALARY) AS SELECT DEPT,SUM(SAL) FROMsql> STAFF GROUP BY DEPT; View V4 created.

The next example selects data from the view, however the processing of the query is not optimized because view V4 contains a group function:

sql> SELECT * FROM V4;Page 1DEPT SALARY---- -------BUS 129,200ENG 29,900FA 67,800PSY 88,200SPA 26,8005 records listed

Optimizing View Queries with Alternate Indexes

Using the optimized method, UniData SQL takes advantage of alternate indexes when processing queries from views.

The following example shows how to create an alternate index called I_NAME from the STAFF table which will be used in the next few examples:

sql> CREATE INDEX I_NAME ON STAFF(LNAME);Alternate key length (default 20): "I_NAME" created Building "I_NAME" ... 9 record(s) processed.

7-11 Using UniData SQL

Page 217: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The following example shows how to take advantage of the alternate index you created in the previous example when you process a query on the view called V1:

sql> SELECT * FROM V1 WHERE LNAME = "Fried";Page 1STAFF Last Nam Title Salary---------- -------- ------- -------8 Fried Dean 98,0001 records listed

The query from the previous example transforms into the following:

sql> SELECT @ID,LNAME,TITLE,SAL FROM STAFFsql> WHERE LNAME="Fried";Page 1STAFF Last Nam Title Salary---------- -------- ------- -------8 Fried Dean 98,0001 records listed

Optimizing View Queries and the UNNEST Clause

Even though a view definition meets the criteria for optimizing view processing, in some cases, UniData SQL does not optimize some queries involving views. For example, if a query involving a view contains an UNNEST clause, its processing cannot be optimized even if the view definition meets the required criteria.

The following example shows how to create a view called V5 that meets the criteria for optimizing view processing:

sql> CREATE VIEW V5 AS SELECT LNAME,COURSES FROM STAFF;

View V5 created.

7-12

Page 218: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The following example shows how to query the V5 view using the UNNEST clause. Notice that this query cannot be optimized. However, other queries from V5 that do not contain the UNNEST clause can be optimized.

sql> SELECT * FROM V5 UNNEST COURSES;Page 1Last Nam Courses Tu-------- ----------Eades FA230Eades FA231MastersAaronFisher FA100JamesCarnesOtis PY100GibsonFried10 records listed

Note: UniData SQL automatically optimizes joins of views that are based on the same table and joined on the record ID.

7-13 Using UniData SQL

Page 219: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Dropping ViewsWhen you no longer need a view, you can use a DROP VIEW statement to delete it.

SyntaxDROP cVIEW view_name

The following example shows how to drop the view called C_D_INFO:

sql> DROP VIEW C_DENVER;View C_DENVER dropped.

If you drop a view, all other views based on the dropped view become inaccessible:

sql> DROP VIEW MYSTAFF; sql> DROP VIEW RENTALS; sql> DROP VIEW NEWBUDGET; sql> DROP VIEW NEWBUDGET1; sql> DROP VIEW V1;sql> DROP VIEW V2;sql> DROP VIEW V3;sql> DROP VIEW V4;sql> DROP VIEW V5;

After you have dropped the views, finish cleaning up the demo database by dropping the index you created earlier in this chapter:

sql> DROP INDEX I_NAME FROM STAFF;"I_NAME" deleted

7-14

Page 220: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

8Chapter

Creating Reports

Understanding UniData SQL Reports . . . . . . . . . . . . 8-4Constructing Report Columns. . . . . . . . . . . . . . . 8-6 Using the COLUMN Command . . . . . . . . . . . . 8-6 Setting Up Column Headings . . . . . . . . . . . . . 8-10 Justifying Text in a Column Heading . . . . . . . . . . . 8-11 Controlling Column Spacing. . . . . . . . . . . . . . 8-11 Controlling Spaces between Two Columns . . . . . . . . . 8-12 Controlling Spaces Between Specific Columns . . . . . . . . 8-13Formatting Report Columns . . . . . . . . . . . . . . . 8-14 Copying a Format . . . . . . . . . . . . . . . . . 8-16 Displaying Long Values . . . . . . . . . . . . . . . 8-16Defining Report Titles . . . . . . . . . . . . . . . . . 8-19 Turning Titles On or Off . . . . . . . . . . . . . . . 8-19 Formatting Headers . . . . . . . . . . . . . . . . 8-19 Formatting Footers . . . . . . . . . . . . . . . . . 8-23 Including Attribute Values in Headers and Footers . . . . . . . 8-25Organizing Reports by Group . . . . . . . . . . . . . . . 8-28 Creating Breaks in a Report . . . . . . . . . . . . . . 8-28Performing Computations at Breaks . . . . . . . . . . . . . 8-32 Computing Subtotals . . . . . . . . . . . . . . . . 8-33 Executing Multiple Computations . . . . . . . . . . . . 8-34 Computing a Grand Total. . . . . . . . . . . . . . . 8-35 Displaying and Clearing Breaks and Computations . . . . . . 8-36Setting the Report Environment . . . . . . . . . . . . . . 8-37 Setting Report Parameters . . . . . . . . . . . . . . 8-39 Wrapping Text Vertically . . . . . . . . . . . . . . . 8-40 Displaying Report Environment Parameters . . . . . . . . . 8-41

Page 221: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

8-2 Usi

Preparing Complex Reports . . . . . . . . . . . . . . . 8-42 Producing a Complex Report. . . . . . . . . . . . . . 8-42

ng UniData SQL

Page 222: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

This chapter demonstrates the UniData SQL report commands that format query results into more meaningful reports.

By the time you complete this chapter, you should be able to do the following:

Define a report.Define report columns.Format report columns.Define report titles.Organize reports into groups.Perform computations at breaks.Set the report environment.Prepare a complex report.

8-3 Using UniData SQL

Page 223: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Understanding UniData SQL ReportsA report is the result of a UniData SQL query organized into a finished, meaningful format.

The following example illustrates the process of constructing a report. The example illustrates how to analyze the annual income of three categories of videotapes: categories C, R, and S.

sql> SELECT CATEGORIES,NAME,INCOME FROM TAPESsql> UNNEST CATEGORIES WHERE CATEGORIES INsql> ("C","R","S") ORDER BY CATEGORIES;Page 1Type of Vide Tape Name Tape Rev------------ -------------------- --------C American Graffiti 242.50C Catch 22 786.50C Girl Friday 22.68C Help 202.50R Gone With The Wind 311.52R Love Story 47.50R Tammy 3.18S 2001 985.50S A Clockwork Orange 52.52S Flash Gordon 163.80S The Stalker 20.2011 records listed

Note: Although the result in the example shown above is correct, it includes redundant information and is not formatted in a manner that is easy to understand.

8-4

Page 224: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The following example displays the output from the query in the previous example in a meaningful and useful format. The commands that format this report are covered in detail in this chapter.

OLD CLASSIC VIDEO STORE ANNUAL INCOME ANALYSIS REPORT

CATEGORY VIDEO TAPE ANNUAL PERCENTNAME NAME INCOME STORE-------- ---------- ------ -------Comedy American Graffiti $242.50 8.54 Catch 22 $786.50 27.71 Girl Friday $22.68 0.80 Help $202.50 7.13 ------- ------- $1,254.18 44.18

Romance Gone With The Wind $311.52 10.98 Love Story $47.50 1.67 Tammy $3.18 0.21 ------- ------- $362.20 12.76

Science Fi 2001 $985.50 10.98 A Clockwork Orange $52.52 1.85 Flash Gordon $163.80 0.71 The Stalker $20.20 0.71 ------- ------- $1,222.02 43.05

FISCAL YEAR 1996-97

8-5 Using UniData SQL

Page 225: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Constructing Report ColumnsThe basic organizational element of a report is the column. When you query the database, UniData SQL displays the output in columns with headings. For reports based on a base table, column headings are the display names defined in the dictionary entry for the attribute.

Using the COLUMN CommandIn some cases, using attribute names as column headings might not be meaningful to the reader of the report, or the arrangement of the columns might not be optimal. With UniData SQL, you can choose to use the display names that are already defined in the dictionary, or you can rename them by specifying attribute labels in the SELECT statement that creates the report. Additionally, you can define column headings and reformat the columns with the COLUMN command.

COLUMN settings apply to all attributes of the same name in any table.

The COLUMN command lets you modify columns in a report in the following ways:

Set up column headings.Format columns.Set text justification.Determine what to do with values that are wider than the column.Determine how to display, suppress, and clear column definitions.

8-6

Page 226: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Syntax

COLUMN {attribute_name | expression} [ALIAS alias] [CLEAR | DEFAULT] [FORMAT column_format] [HEADING "text" [JUSTIFY {LEFT | CENTER | RIGHT}]] [LIKE {expression | attribute_label}] [NEWLINE] [NEW_VALUE new_val] [OLD_VALUE old_val] [NOPRINT | PRINT] [NULL "text"] [ON | OFF] [SPACE n] [WRAPPED | WORD_WRAPPED | TRUNCATED]

Points to Remember about COLUMN

When you use the COLUMN command, UniData SQL operates according to the following rules:

A column definition remains in effect until you issue a new COLUMN command for the attribute or until you issue a COLUMN OFF statement.You can issue multiple COLUMN statements, and they all can be in effect at the same time.A new COLUMN definition replaces the old one if the new one defines the same attributes (defines the HEADING for the same attribute).More than one COLUMN command can contain the same attribute name if the clauses are different. For example, you can use the same attribute in a HEADING clause and a FORMAT clause. UniData SQL will implement both of them.

8-7 Using UniData SQL

Page 227: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

COLUMN Command Options

The following table lists the options for the COLUMN command.

Parameter Description

attribute_name Specifies the attribute to format.

expression Any combination of attribute names, constants, arithmetic operators, and UniData SQL functions that together select attri-butes to be associated with display formats. Expressions that contain spaces must be enclosed in quotation marks. expression must be defined the same way as in the SELECT statement. Keywords must be entered uppercase even if they were lowercase in the SELECT statement.

ALIAS alias Assigns an alias to expression or attribute_spec. You can use this alias in expression or attribute_spec anywhere in the statement; however, alias must be defined for each statement.

CLEAR Removes the column definition for expression or attribute_spec.

DEFAULT Resets the column definition to default settings, including PRINT ON and WRAP ON.

FORMAT column_format

Formats values displayed in this column. For further information, see “Formatting Report Columns” on page 8-14.

HEADING "text" Displays a column heading. The default is the attribute name or the expression itself. Enclose text within quotation marks if it contains spaces or special characters. If the text contains HEADSEP, the column heading is displayed over multiple lines.

JUSTIFY Aligns the column header. HEADING must be specified to use JUSTIFY. LEFT – Left-align column header.CENTER – Center column header.RIGHT – Align column header at right column margin.

LIKE “expression”LIKE attribute_label

Copies the COLUMN specification of another column.

NEWLINE With SET WRAP HORI, starts a new line before displaying the value of a column. With SET WRAP DEF, switches to vertical format.

COLUMN Parameters

8-8

Page 228: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Setting Up Column HeadingsWhen the system displays your report, the attribute names or expressions become the column headings (unless you specify an attribute_label in the SELECT clause). To change the column headings, use the COLUMN command with a HEADING clause.

Note: If you enter a COLUMN statement with an attribute name, UniData SQL displays all the current definitions for that attribute. If you enter a COLUMN statement without any attribute names, UniData SQL displays all the current COLUMN definitions.

NEW_VALUE new_val Saves the current value of an attribute for use in TTITLE statements to print a header that reflects current attribute values.

NOPRINT PRINT

Turns on or off printing column text. The default is PRINT.

NULL "text" Replaces null values with text in reports.

OFF ON

Turns COLUMN settings off or on without affecting the settings. The default is ON.

OLD_VALUE old_val Saves the current value of an attribute for use in BTITILE statements to print a footer that reflects current attribute values.

SPACE n Places the next column n spaces to the right of the current position. Defaults to the position established by the SET command (SET SPACE n).

WRAPPED WORD_WRAPPED TRUNCATED

Specifies wrapping or truncating of column text when text is wider than the column. WRAPPED wraps text to the next line; default.WORD_WRAPPED wraps text without breaking words. TRUNCATED deletes text that does not fit in the column.

attribute_name_ expression no option

Displays current column definitions.

Parameter Description

COLUMN Parameters (continued)

8-9 Using UniData SQL

Page 229: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The following example queries the database for the income from tape categories C, R, and S and specifies the headings and format for the columns in the report:

sql> COLUMN CATEGORIES HEADING "CATEGORY|CODE" FORMAT "A10";sql> COLUMN NAME HEADING "VIDEO TAPE|NAME" FORMAT "A18";sql> COLUMN INCOME HEADING "ANNUAL|INCOME";sql> SELECT CATEGORIES,NAME,INCOME FROM TAPES UNNEST CATEGORIESsql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES;Page 1CATEGORY VIDEO TAPE ANNUALCODE NAME INCOME---------- ------------------ --------C American Graffiti 242.50C Catch 22 786.50C Girl Friday 22.68C Help 202.50R Gone With The Wind 311.52R Love Story 47.50R Tammy 3.18S 2001 985.50S A Clockwork Orange 52.52S Flash Gordon 163.80S The Stalker 20.2011 records listed

Note: The vertical bar (|) within quotation marks tells UniData SQL to display the heading text on different lines. This is the UniData SQL default; you can choose other characters as well for this purpose. For further information, see Chapter 5, “Manipulating Data.”

8-10

Page 230: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Justifying Text in a Column HeadingThe following example queries the database for the same income information as shown in the previous example. In addition, the query contains a JUSTIFY clause in the second COLUMN statement to position the heading for tape name at the center of the column.

sql> COLUMN CATEGORIES HEADING "CATEGORY|CODE" FORMAT "A10";sql> COLUMN NAME HEADING "VIDEO TAPE|NAME" JUSTIFY CENTER;sql> COLUMN INCOME HEADING "ANNUAL|INCOME";sql> SELECT CATEGORIES,NAME,INCOME FROM TAPES UNNEST CATEGORIESsql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES;Page 1CATEGORY VIDEO TAPE ANNUALCODE NAME INCOME---------- ------------------ --------C American Graffiti 242.50C Catch 22 786.50C Girl Friday 22.68C Help 202.50R Gone With The Wind 311.52R Love Story 47.50R Tammy 3.18S 2001 985.50S A Clockwork Orange 52.52S Flash Gordon 163.80S The Stalker 20.2011 records listed

Controlling Column SpacingUnless you change column spacing, UniData SQL puts one space between columns. You can control the spacing between columns in two ways:

Use a SPACE clause in a SET statement to control the number of spaces between two columns.Use a SPACE clause within a COLUMN statement to tell UniData SQL which column to display following a specific number of spaces after the previous column.

8-11 Using UniData SQL

Page 231: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Controlling Spaces between Two ColumnsThe following example shows how to use a SPACE clause in a SET statement to control the number of spaces between two columns:

sql> COLUMN CATEGORIES HEADING “CATEGORY|CODE” FORMAT "A10";sql> COLUMN NAME HEADING "VIDEO TAPE|NAME" JUSTIFY CENTER;sql> COLUMN INCOME HEADING "ANNUAL|INCOME";sql> SET SPACE 5;sql> SELECT CATEGORIES,NAME,INCOME FROM TAPES UNNEST CATEGORIESsql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES;Page 1CATEGORY VIDEO TAPE ANNUALCODE NAME INCOME---------- -------------------- --------C American Graffiti 242.50C Catch 22 786.50C Girl Friday 22.68C Help 202.50R Gone With The Wind 311.52R Love Story 47.50R Tammy 3.18S 2001 985.50S A Clockwork Orange 52.52S Flash Gordon 163.80S The Stalker 20.2011 records listed

8-12

Page 232: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Controlling Spaces Between Specific ColumnsThe following example shows how to use a SPACE clause within a COLUMN statement to tell UniData SQL which column to display following a specific number of spaces after the previous column. In this example, notice the difference in space between the columns. This is because the SPACE clause in the COLUMN statement is set up to show 15 spaces between the last two columns.

sql> COLUMN CATEGORIES HEADING "CATEGORY|CODE" FORMAT "A10";sql> COLUMN NAME HEADING "VIDEO TAPE|NAME" JUSTIFY CENTER;sql> COLUMN INCOME HEADING "ANNUAL|INCOME" SPACE 15;sql> SELECT CATEGORIES,NAME,INCOME FROM TAPES UNNEST CATEGORIESsql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES;Page 1CATEGORY VIDEO TAPE ANNUALCODE NAME INCOME---------- -------------------- --------C American Graffiti 242.50C Catch 22 786.50C Girl Friday 22.68C Help 202.50R Gone With The Wind 311.52R Love Story 47.50R Tammy 3.18S 2001 985.50S A Clockwork Orange 52.52S Flash Gordon 163.80S The Stalker 20.2011 records listed

8-13 Using UniData SQL

Page 233: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Formatting Report ColumnsTo define the display format of data within a column, use a COLUMN statement with a FORMAT clause.

SyntaxCOLUMN attribute.name FORMAT column_format

column_format Options

column_format specifies the display format for values in the column. column_format must be enclosed in quotation marks, and can be one of the following:

Character Format Options – The format for a character string is An where n is the column width. The default is the length specified in the dictionary definition of the attribute.Date Format Options – You cannot specify format options for date attri-butes; the formatting specified in the dictionary definition of the attribute is used.Numeric Format Options – Use the options in the following table to build a display mask for formatting numeric values:

Option Explanation Example of Mask

9 Represents one numeric display position. 9999

0 Display leading zeros. 0999

$ Prefix displayed value with a dollar sign. $9999

B Print leading zeros as blank. B999

MI Display minus sign (-) after a negative value. 9999MI

PR Display a negative value in angle brackets 9999PR

. Align on the decimal point. 99.99

column_format Numeric Options

8-14

Page 234: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

ExampleIn the next example, the FORMAT clause formats the INCOME column of a report to place a dollar sign before the value:

sql> COLUMN CATEGORIES HEADING "CATEGORY|CODE" FORMAT "A10";sql> COLUMN NAME HEADING "VIDEO TAPE|NAME" JUSTIFY CENTER;sql> COLUMN INCOME HEADING "ANNUAL|INCOME" FORMAT "$999.99";sql> SELECT CATEGORIES,NAME,INCOME FROM TAPES UNNEST CATEGORIESsql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES;Page 1CATEGORY VIDEO TAPE ANNUALCODE NAME INCOME---------- ------------------ -------C American Graffiti $242.50C Catch 22 $786.50C Girl Friday $22.68C Help $202.50R Gone With The Wind $311.52R Love Story $47.50R Tammy $3.18S 2001 $985.50S A Clockwork Orange $52.52S Flash Gordon $163.80S The Stalker $20.2011 records listed

, Insert a comma where placed in the mask. 99,999

V Multiply the value by the n power of 10, where n is the number of 9s after V.

999V99

EEEE Display the scientific notation (the format must contain four Es).

9.99EEEE

Option Explanation Example of Mask

column_format Numeric Options (continued)

8-15 Using UniData SQL

Page 235: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Copying a FormatIf you want two columns in a report to be formatted the same way, use the LIKE clause to copy the format of one to the other. For example, if you want to format the COST column of a report the same way you formatted the INCOME column, you could enter the following COLUMN statement:

sql> COLUMN CATEGORIES HEADING "CATEGORY|CODE" FORMAT "A10";sql> COLUMN NAME HEADING "VIDEO TAPE|NAME" JUSTIFY CENTER;sql> COLUMN INCOME HEADING "ANNUAL|INCOME" FORMAT "$999.99";sql> COLUMN COST LIKE INCOME HEADING "UNIT|PRICE";sql> SELECT CATEGORIES,NAME,INCOME,COST FROM TAPES sql> UNNEST CATEGORIESsql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES;Page 1CATEGORY VIDEO TAPE ANNUAL UNITCODE NAME INCOME PRICE---------- -------------------- -------- --------C American Graffiti $242.50 $45.00C Catch 22 $786.50 $45.00C Girl Friday $22.68 $22.50C Help $202.50 $23.50R Gone With The Wind $311.52 $78.00R Love Story $47.50 $25.00R Tammy $3.18 $9.99S 2001 $985.50 $45.00S A Clockwork Orange $52.52 $77.00S Flash Gordon $163.80 $23.50S The Stalker $20.20 $35.0011 records listed

Displaying Long ValuesIf an attribute value is too long to fit within the column, you can format it in several ways:

Execute the SET command with the WRAP option to redefine the default line width. This tells UniData SQL when to display the report vertically or horizontally.

8-16

Page 236: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Execute the SET command with the WRAPPED option to define when column text is wrapped in one of three ways:

The option WRAPPED wraps the value when it exceeds the column width.The option WORD_WRAPPED wraps the value between words.The option TRUNCATED truncates the value when it is too wide to fit in the column.

Wrapping Values at Specified Lengths

The next example illustrates how to modify the column definition for the tape name to 10 characters:

sql> COLUMN CATEGORIES HEADING "CATEGORY|CODE" FORMAT "A10";sql> COLUMN NAME HEADING "VIDEO TAPE|NAME" FORMAT "A10" WRAPPED;sql> COLUMN INCOME HEADING "ANNUAL|INCOME" FORMAT "$999.99";sql> COLUMN COST LIKE INCOME HEADING "UNIT|PRICE"; sql> SELECT CATEGORIES,NAME,INCOME,COST FROM TAPES sql> UNNEST CATEGORIESsql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES;Page 1CATEGORY VIDEO TAPE ANNUAL UNITCODE NAME INCOME PRICE---------- ---------- -------- --------C American G $242.50 $45.00 raffitiC Catch 22 $786.50 $45.00C Girl Frida $22.68 $22.50 yC Help $202.50 $23.50R Gone With $311.52 $78.00 The WindR Love Story $47.50 $25.00R Tammy $3.18 $9.99S 2001 $985.50 $45.00S A Clockwor $52.52 $77.00 k OrangeS Flash Gord $163.80 $23.50 onS The Stalke $20.20 $35.00 r11 records listed

8-17 Using UniData SQL

Page 237: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Wrapping between Words

In the next example, notice the difference in the display of the data within the second column when the FORMAT clause sets the WORD_WRAPPED option:

sql> COLUMN CATEGORIES HEADING "CATEGORY|CODE" FORMAT "A10";sql> COLUMN NAME HEADING "VIDEO TAPE|NAME" FORMAT "A10" sql> WORD_WRAPPED;sql> COLUMN INCOME HEADING "ANNUAL|INCOME" FORMAT "$999.99";sql> COLUMN COST LIKE INCOME HEADING "UNIT|PRICE";sql> SELECT CATEGORIES,NAME,INCOME,COST FROM TAPES sql> UNNEST CATEGORIESsql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES;Page 1CATEGORY VIDEO TAPE ANNUAL UNITCODE NAME INCOME PRICE---------- ---------- -------- --------C American $242.50 $45.00 GraffitiC Catch 22 $786.50 $45.00C Girl $22.68 $22.50 FridayC Help $202.50 $23.50R Gone With $311.52 $78.00 The WindR Love Story $47.50 $25.00R Tammy $3.18 $9.99S 2001 $985.50 $45.00S A $52.52 $77.00 Clockwork OrangeS Flash $163.80 $23.50 GordonS The $20.20 $35.00 Stalker11 records listed

8-18

Page 238: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Defining Report TitlesIn UniData SQL, an entire screen display of a query result is called a “page.” You can put titles on the top or bottom of each page to improve the readability of the report. UniData SQL provides two title functions:

TTITLE to define headers at the top of the page.BTITLE to define footers at the bottom of the page.

Turning Titles On or Off

Syntax

{TTITLE | BTITLE} ON{TTITLE | BTITLE} OFF

Note: If you enter only TTITLE or BTITLE at the UniData SQL prompt, the system displays the current definition.

Formatting HeadersTTITLE establishes a header for printed and displayed reports. You can specify any number of constants and variables. These parameters are executed in the order in which they are defined. These parameters are executed in the order in which they are defined. You can apply any number of TTITLE commands to one or more attributes. If more than one TTITLE command is applied to the same attribute, the last command supersedes all previous commands.

Syntax

TTITLE [ print_clause | ON | OFF]

print_clause syntax:

[SKIP [n] ] [COL [n] | LEFT | CENTER | RIGHT] [ “text”] [FORMAT format | [TAB [n] ] [new_val] ]...

8-19 Using UniData SQL

Page 239: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

If you code simply TTITLE text, UniData SQL:

Prints the current date and page appear on the first line at the right.text appears on the second line, centered. UniData SQL computes the actual position of the title text according to the MARGIN and LINESIZE setting. The default left margin is 1 and the LINESIZE is 80. You can use the SET statement to reset these parameters.

Parameters

The following table describes each parameter of the syntax.

BTITLE/TTITLE Parameters

Parameter Description

print_clause Sets the following:Skip columns.Skip lines.Align title data left, center or right.Format "text" for display.See the next table for print_clause options.

ON Turns the header or footer on, causing "text" to be printed.

OFF Turns the header or footer off.You do not have to redefine “text” to turn on headers or footers again you have turned them off.

8-20

Page 240: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

print_clause Parameters

The following table describes each parameter of print_clause.

Clause Description

COL n Skips to the nth column before displaying the header. The first column is numbered 0.

SKIP n Skips n lines before printing out the text. The default is 1.

LEFT, CENTER, RIGHT

Aligns the title data on the current line. The following data item (variable or text) is aligned as a group to the end of the statement or the next LEFT, CENTER, RIGHT or COL, SKIP or TAB. CENTER and RIGHT are calculated based on the LINESIZE option of the SET statement.

FORMAT format Specifies a format model for the following data item. FORMAT is effective until the end of the statement or until another FORMAT clause is encountered in the same statement. format options are discussed following this table.

Print Clause Parameters

8-21 Using UniData SQL

Page 241: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

old_val new_val

For footers (BTITLE): Displays the current value of the variable old_val, set by OLD_VALUE in the previously executed COLUMN statement.For headers (TTITLE): Displays the current value of the variable new_val, set by NEW_VALUE in the previously executed COLUMN statement.

“text” Displays a two-line header or footer. The first line contains the date at the left and the page number on the right; the second line contains the center-aligned text. In addition to literal text, you can include any number of the following heading options:B – Inserts the current value of the attribute named in the BREAK.ON clause; if the B option is included in both HEADING and BREAK, UniData SQL generates a new page every time the value in the BREAK attribute changes.C[n] – Centers heading or footing text within a line of n width.D – Inserts the current system date in the heading.F – Inserts filename.L – Executes a new line.N – Suppresses the default prompt, “Enter new line to continue...”, that appears at the bottom of each screen page. Pages scroll without stopping until the report is finished.P or S – Inserts the current page number. T – Inserts the time and date when report generation began.

TAB n Skips to the nth column from the current position.

Clause Description

Print Clause Parameters (continued)

8-22

Page 242: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Creating a Multiple-Line Title

The next example displays a TTITLE statement that creates a multiple line title:

sql> SET LINESIZE 50;sql> TTITLE ON;sql> TTITLE CENTER "OLD CLASSIC" SKIP LEFT "INCOME ANALYSIS"sql> RIGHT "1993-94" SKIP 2 COL 9 "CATEGORY C R S" SKIP;sql> COLUMN CATEGORIES HEADING "CATEGORY|CODE" FORMAT "A10";sql> COLUMN NAME HEADING "VIDEO TAPE|NAME" JUSTIFY CENTER;sql> COLUMN INCOME HEADING "ANNUAL|INCOME" FORMAT "$999.99";sql> COLUMN COST LIKE INCOME HEADING “UNIT|PRICE”;sql> SELECT CATEGORIES,NAME,INCOME,COST FROM TAPESsql> UNNEST CATEGORIESsql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES; OLD CLASSICINCOME ANALYSIS 1993-94

CATEGORY C R S

CATEGORY VIDEO TAPE ANNUAL UNITCODE NAME INCOME PRICE---------- -------------------- -------- --------C American Graffiti $242.50 $45.00C Catch 22 $786.50 $45.00C Girl Friday $22.68 $22.50C Help $202.50 $23.50R Gone With The Wind $311.52 $78.00R Love Story $47.50 $25.00R Tammy $3.18 $9.99S 2001 $985.50 $45.00S A Clockwork Orange $52.52 $77.00S Flash Gordon $163.80 $23.50S The Stalker $20.20 $35.00

Tip: With UniData SQL, you can position parts of a title independently by using separate formatting clauses.

Formatting FootersBTITLE establishes a footer for printed and displayed reports created by SELECT statements. You can specify any number of constants and variables. These parameters are executed in the order in which they are defined. You can apply any number of BTITLE options to one or more attributes. If more than one BTITLE command is applied to the same attribute, the last command supersedes all previous commands.

8-23 Using UniData SQL

Page 243: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Syntax

BTITLE [ print_clause | OFF | ON]

print_clause syntax:

{COL [n] | LEFT | CENTER | RIGHT} [ “text”] [FORMAT format | [TAB [n] ] old_val | “text”]...

Note: UniData SQL always puts the footer at the end of each page even if the page is not full. To adjust the page size, use the SET function.

Parameters

For a description of the syntax parameters, see “Formatting Headers” on page 8-19.

8-24

Page 244: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Example

In the next example, the BTITLE statement adds “FISCAL YEAR 1993-94” to the tape income report as a footer:

sql> SET LINESIZE 50;sql> TTITLE ON;sql> TTITLE CENTER "OLD CLASSIC" SKIP LEFT "INCOME ANALYSIS"sql> RIGHT "1993-94" SKIP 2 COL 9 "CATEGORY C R S" SKIP;sql> BTITLE ON;sql> BTITLE SKIP CENTER "FISCAL YEAR 1993-94";sql> COLUMN CATEGORIES HEADING "CATEGORY|CODE" FORMAT "A10";sql> COLUMN NAME HEADING "VIDEO TAPE|NAME" JUSTIFY CENTER;sql> COLUMN INCOME HEADING "ANNUAL|INCOME" FORMAT "$999.99";sql> COLUMN COST LIKE INCOME HEADING "UNIT|PRICE";sql> SELECT CATEGORIES,NAME,INCOME,COST FROM TAPES sql> UNNEST CATEGORIESsql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES; OLD CLASSICINCOME ANALYSIS 1993-94

CATEGORY C R S

CATEGORY VIDEOTAPE ANNUAL UNITCODE NAME INCOME PRICE---------- -------------------- -------- --------C American Graffiti $242.50 $45.00C Catch 22 $786.50 $45.00C Girl Friday $22.68 $22.50R Gone With The Wind $311.52 $78.00R Love Story $47.50 $25.00R Tammy $3.18 $9.99S 2001 $985.50 $45.00S A Clockwork Orange $52.52 $77.00S Flash Gordon $163.80 $23.50S The Stalker $20.20 $35.00

FISCAL YEAR 1993-94

Note: Always enclose options in single quotation marks within a heading string that is enclosed in double quotation marks.

Including Attribute Values in Headers and FootersIn some cases, you might want to use attribute values in a header or footer. Use the COLUMN NEW_VALUE or COLUMN OLD_VALUE clause with an optional FORMAT clause in the TTITLE and BTITLE statements to accomplish this task.

8-25 Using UniData SQL

Page 245: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The NEW_VALUE clause defines a variable that can be used in the TTITLE statement, while the OLD_VALUE clause defines a variable that can be used in the BTITLE statement. The variables are used to keep the current value for the attribute specified by the COLUMN command.

8-26

Page 246: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The TTITLE and BTITLE statements both use the FORMAT clause to specify the display format of the attribute value when it appears in the statements. The FORMAT option applies only to variables defined by NEW_VALUE or OLD_VALUE. A FORMAT clause remains in effect until you define the next FORMAT.

sql> COLUMN CATEGORIES NEW_VALUE CAT;sql> TTITLE CENTER "OLD CLASSIC" SKIP LEFT "CATEGORY:" COL 12 CAT SKIP;sql> TTITLE ON;sql> BTITLE SKIP CENTER "FISCAL YEAR 1996-97";sql> BTITLE ON;sql> COLUMN CATEGORIES HEADING "CATEGORY|CODE" FORMAT "A10";sql> COLUMN NAME HEADING "VIDEO TAPE|NAME" JUSTIFY CENTER;sql> COLUMN INCOME HEADING "ANNUAL|INCOME" FORMAT "$999.99";sql> COLUMN COST LIKE INCOME HEADING "UNIT|PRICE";sql> SELECT CATEGORIES,NAME,INCOME,COST FROM TAPES UNNEST CATEGORIESsql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES; OLD CLASSICCATEGORY: C

CATEGORY VIDEO TAPE ANNUAL UNITCODE NAME INCOME PRICEC American Graffiti $242.50 $45.00C Catch 22 $786.50 $45.00C Girl Friday $22.68 $22.50C Help $202.50 $23.50R Gone With The Wind $311.52 $78.00R Love Story $47.50 $25.00R Tammy $3.18 $9.99S 2001 $985.50 $45.00S A Clockwork Orange $52.52 $77.00C American Graffiti $242.50 $45.00C Catch 22 $786.50 $45.00C Girl Friday $22.68 $22.50C Help $202.50 $23.50R Gone With The Wind $311.52 $78.00R Love Story $47.50 $25.00R Tammy $3.18 $9.99S 2001 $985.50 $45.00S A Clockwork Orange $52.52 $77.00S Flash Gordon $163.80 $23.50S The Stalker $20.20 $35.00

FISCAL YEAR 1996-97

8-27 Using UniData SQL

Page 247: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Organizing Reports by GroupYou may need to compute totals or subtotals of a group of data based on various classification criteria. You can use UniData SQL group functions to execute the following computations:

SumAverageMaximumMinimumCount

When you execute a group function, you can obtain only the aggregate result — you cannot display the detail line and the aggregate result at the same time. The UniData SQL report statements BREAK and COMPUTE do print detail when combined with aggregate functions.

Creating Breaks in a ReportA break occurs during execution of a SELECT statement, causing UniData SQL to take the action associated with the BREAK statement. The break can be triggered by a change in attribute or expression values, at the end of a page, or the end of the report. The resultant action could include printing some text, skipping a certain number of lines, and so forth. The BREAK statement itself improves the appearance of a report, but more importantly, it can be used in conjunction with the COMPUTE statement to accomplish more sophisticated tasks.

SyntaxBREAK ON event [text] [SKIP n] [option]

8-28

Page 248: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Valid break events are described in the following table.

BREAK Events

Event Description

attribute Whenever the specified attribute changes.

ROW Breaks at each row.

REPORT Breaks at the end of the report.

The skip actions include:

SKIP Options

Option Description

BSKIP n Skip n lines before any other action takes place.

SKIP n After print/display action, skip n lines.

SKIP PAGE After print/display action, skip to a new page.

8-29 Using UniData SQL

Page 249: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Creating a Report with Blank Lines

The following example demonstrates how to use BREAK to create a report with two blank lines between each category:

sql> SET LINESIZE 46;sql> BREAK ON CATEGORIES SKIP 1;sql> TTITLE ON;sql> TTITLE CENTER "INCOME ANALYSIS REPORT" SKIP;sql> BTITLE OFF;sql> COLUMN CATEGORIES HEADING "CATEGORY|CODE" FORMAT "A10";sql> COLUMN NAME HEADING "VIDEO TAPE|NAME" FORMAT "A18";sql> COLUMN INCOME HEADING "ANNUAL|INCOME" FORMAT "$999.99";sql> SELECT CATEGORIES,NAME,INCOME FROM TAPESsql> UNNEST CATEGORIESsql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES; INCOME ANALYSIS REPORT CATEGORY VIDEO TAPE ANNUALCODE NAME INCOME---------- ------------------ --------C American Graffiti $242.50 Catch 22 $786.50 Girl Friday $22.68 Help $202.50 R Gone With The Wind $311.52 Love Story $47.50 Tammy $3.18 S 2001 $985.50 A Clockwork Orange $52.52 Flash Gordon $163.80 The Stalker $20.20

8-30

Page 250: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Creating a Report with Columns, Breaks, and a Header

The next example illustrates the interaction between the BREAK, COLUMN, and TTITLE statements. The statements in the example cause UniData SQL to report each category on a separate page, print the category code on the top title of each page, and suppress the CATEGORIES column printing:

sql> SET LINESIZE 46;sql> BREAK ON CATEGORIES SKIP PAGE;sql> TTITLE ON;sql> TTITLE CENTER "INCOME REPORT" SKIP LEFT "CODE" COL 6 CAT SKIP;sql> COLUMN CATEGORIES NEW_VALUE CAT NOPRINT;sql> COLUMN NAME HEADING "VIDEO TAPE|NAME" JUSTIFY LEFT;sql> COLUMN INCOME HEADING "ANNUAL|INCOME" FORMAT "$999.99";sql> SELECT CATEGORIES,NAME,INCOME FROM TAPESsql> UNNEST CATEGORIESsql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES; INCOME REPORTCODE C VIDEO TAPE ANNUALNAME INCOME-------------------- --------American Graffiti $242.50Catch 22 $786.50Girl Friday $22.68Help $202.50

Enter <New line> to continue... INCOME REPORTCODE R VIDEO TAPE ANNUALNAME INCOME-------------------- --------Gone With The Wind $311.52Love Story $47.50Tammy $3.18

Enter <New line> to continue...

Note: If you enter BREAK without any options, UniData SQL displays all the current break definition. To remove break definitions, use CLEAR BREAKS.

8-31 Using UniData SQL

Page 251: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Performing Computations at BreaksYou can perform various computations at breaks. The COMPUTE statement enables you to specify which computation to perform and on which attribute.

SyntaxCOMPUTE computation OF attribute, attribute, ... ON break_attribute

The following table lists all the computations.

COMPUTE Options

Option Explanation

SUM Sum of the attribute values in a group.

AVG Average of the attribute values in a group.

MAX Maximum value of the attributes in a group.

MIN Minimum value of the attributes of a group.

COUNT Number of values in a group.

NUMBER Number of items in a group.

STD Standard deviation of the attributes of a group.

VAR Variance of the attribute values in a group.

8-32

Page 252: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Computing SubtotalsYou must execute a BREAK statement to trigger the COMPUTE command. This illustrates a COMPUTE statement that calculates the total income for tapes in each video tape category:

sql> SET LINESIZE 46;sql> BREAK ON CATEGORIES SKIP 2;sql> TTITLE ON;sql> TTITLE CENTER "INCOME ANALYSIS REPORT" SKIP 1;sql> COLUMN CATEGORIES PRINT;sql> COLUMN CATEGORIES HEADING "CATEGORY|CODE" FORMAT "A10";sql> COLUMN NAME HEADING "VIDEO TAPE|NAME" FORMAT "A18";sql> COLUMN INCOME HEADING "ANNUAL|INCOME" FORMAT "$9,999.99";sql> COMPUTE SUM OF INCOME ON CATEGORIES;sql> SELECT CATEGORIES,NAME,INCOME FROM TAPESsql> UNNEST CATEGORIESsql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES; INCOME ANALYSIS REPORT CATEGORY VIDEO TAPE ANNUALCODE NAME INCOME---------- ------------------ ----------C American Graffiti $242.50 Catch 22 $786.50 Girl Friday $22.68 Help $202.50********** ----------sum $1,254.18 R Gone With The Wind $311.52 Love Story $47.50 Tammy $3.18********** ----------sum $362.20 S 2001 $985.50 A Clockwork Orange $52.52 Flash Gordon $163.80 INCOME ANALYSIS REPORT CATEGORY VIDEO TAPE ANNUALCODE NAME INCOME---------- ------------------ ---------- The Stalker $20.20********** ----------sum $1,222.02

Note: Remember to restore the proper column definition for CATEGORIES in the tape income analysis report.

8-33 Using UniData SQL

Page 253: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Executing Multiple ComputationsYou can execute a computation on more than one attribute, and you can execute multiple computations on the same attribute. In the next example, the computation statement sums and the averages the income for each group in the tape income analysis report:

sql> SET LINESIZE 46;sql> BREAK ON CATEGORIES SKIP 2;sql> TTITLE ON;sql> TTITLE CENTER "INCOME ANALYSIS REPORT" SKIP 1;sql> COLUMN CATEGORIES PRINT;sql> COLUMN CATEGORIES HEADING "CATEGORY|CODE" FORMAT "A10";sql> COLUMN NAME HEADING "VIDEO TAPE|NAME" FORMAT "A18";sql> COLUMN INCOME HEADING "ANNUAL|INCOME" FORMAT "$9,999.99";sql> COMPUTE SUM AVG OF INCOME ON CATEGORIES;sql> SELECT CATEGORIES,NAME,INCOME FROM TAPESsql> UNNEST CATEGORIESsql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES; INCOME ANALYSIS REPORT CATEGORY VIDEO TAPE ANNUALCODE NAME INCOME---------- ------------------ ----------C American Graffiti $242.50 Catch 22 $786.50 Girl Friday $22.68 Help $202.50********** ----------avg $313.55

Note: The SUM and AVG options can also be issued in separate COMPUTE statements to obtain the same results.

8-34

Page 254: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Computing a Grand TotalThe COMPUTE statement can also compute a grand total, as shown in the next example. This shows the total income of all tapes:

sql> BREAK ON REPORT SKIP 1 ON CATEGORIES SKIP 1;sql> TTITLE ON;sql> TTITLE CENTER "INCOME ANALYSIS REPORT" SKIP 1;sql> COLUMN CATEGORIES HEADING "CATEGORY|CODE" FORMAT "A10";sql> COLUMN NAME HEADING "VIDEO TAPE|NAME" FORMAT "A18";sql> COLUMN INCOME HEADING "ANNUAL|INCOME" FORMAT "$9,999.99";sql> COMPUTE SUM AVG OF INCOME ON CATEGORIES;sql> COMPUTE SUM OF INCOME ON REPORT;sql> SELECT CATEGORIES,NAME,INCOME FROM TAPES UNNEST CATEGORIESsql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES; INCOME ANALYSIS REPORT

CATEGORY VIDEO TAPECODE NAME Tape Reven---------- ------------------ ----------C American Graffiti $242.50 Catch 22 $786.50 Girl Friday $22.68 Help $202.50********** ----------avg $313.55sum $1,254.18

R Gone With The Wind $311.52 Love Story $47.50 Tammy $3.18********** ----------avg $120.73sum $1,254.18

R Gone With The Wind $311.52 Love Story $47.50 Tammy $3.18********** ----------avg $120.73sum $362.20 S 2001 $985.50 INCOME ANALYSIS REPORT

CATEGORY VIDEO TAPE ANNUALCODE NAME INCOME---------- ------------------ ---------- A Clockwork Orange $52.52 Flash Gordon $163.80 The Stalker $20.20********** ----------

8-35 Using UniData SQL

Page 255: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

avg $305.51sum $1,222.02

Displaying and Clearing Breaks and ComputationsWhen you enter BREAK or COMPUTE without options, UniData SQL displays the current definition.

When you want to discard all break or computation definitions, execute CLEAR BREAK or CLEAR COMPUTE.

8-36

Page 256: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Setting the Report EnvironmentWhen you generate a report, you work within a report environment that is defined by UniData SQL system defaults. For example, the default space between two columns is 1 character and the default page size is 20 lines. You can use the SET statement to change these definitions.

SyntaxSET {HEADING {OFF | ON} | LINESIZE n | MARGIN n | NEWPAGE n | NULL “text” | PAGESIZE n | PAUSE {ON | OFF} | SPACE n | WRAP {VERT | HORI | DEF} UNDERLINE{”char” | OFF | ON}

The following table lists the SET parameters.

Parameter Description

HEADING ON HEADING OFF

Enables or suppresses the printing of column headings in reports. The default is ON.

LINESIZE n Sets the width of the report line. The default is 80.

MARGIN n Sets the left margin of the display or report and enables you to align the display. The default is 1.

NEWPAGE n Sets a number of blank lines to be printed between the bottom title of each page and the top title of the next page. If n is 0, UniData SQL issues a form feed between pages. The default is 1.

NULL “text” Assigns text to replace the null value in display or print.

SET Parameters

8-37 Using UniData SQL

Page 257: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

PAGESIZE n Sets the number of lines per page for display of the results of query_spec or SELECT statements. The default is 23. This option remains in effect if you return to UniData when you exit UniData SQL.

PAUSE ON | OFF

In interactive mode, when PAUSE is ON, display stops at the end of each page and displays the prompt Enter <New line> to continue.... The next page displays when the user presses ENTER.The default in interactive mode is ON; PAUSE ON has no effect in UniData SQL scripts.

SPACE Sets the number of spaces between the columns in a report. The default is 1.

WRAP Determines how UniData SQL displays columns in results of query_spec or SELECT statements VERT – Displays each column on a new line; column headings and column values can wrap on several lines. HORI – Displays columns across the line, wrapping when LINESIZE is exceeded.DEF – Follows UniData conventions: when a whole row fits on one line, UniData SQL displays it horizontally; when it does not, UniData SQL displays it vertically.

UNDERLINE char ON | OFF

Sets the character used to underline headings. Standard characters are '-' and '='.

Parameter Description

SET Parameters (continued)

8-38

Page 258: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Setting Report ParametersThe next example illustrates how to set three parameters: line size, space between columns, and page size.

sql> SET LINESIZE 80;sql> SET SPACE 15;sql> SET PAGESIZE 25;sql> BREAK ON REPORT SKIP 1 ON CATEGORIES SKIP 1;sql> TTITLE CENTER "INCOME ANALYSIS REPORT" SKIP 1;sql> COLUMN CATEGORIES HEADING "CATEGORY|CODE" FORMAT "A10";sql> COLUMN NAME HEADING "VIDEO TAPE|NAME" FORMAT "A18";sql> COLUMN INCOME HEADING "ANNUAL|INCOME" FORMAT "$9,999.99";sql> COMPUTE SUM AVG OF INCOME ON CATEGORIES;sql> COMPUTE SUM OF INCOME ON REPORT;sql> SELECT CATEGORIES,NAME,INCOME FROM TAPES UNNEST CATEGORIES sql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES; INCOME ANALYSIS REPORT

CATEGORY VIDEO TAPECODE NAME Tape Reven---------- ------------------ ----------C American Graffiti $242.50 Catch 22 $786.50 Girl Friday $22.68 Help $202.50********** ----------avg $313.55sum $1,254.18

R Gone With The Wind $311.52 Love Story $47.50 Tammy $3.18********** ----------avg $120.73sum $362.20...

8-39 Using UniData SQL

Page 259: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Wrapping Text VerticallyThe following example shows the effect of the WRAP VERT option:

sql> SET WRAP VERT;sql> SET MARGIN 10;sql> BREAK ON CATEGORIES SKIP PAGE; sql> COMPUTE SUM OF INCOME ON CATEGORIES; sql> COMPUTE AVG OF INCOME ON CATEGORIES; sql> COLUMN CATEGORIES NEW_VALUE newval; sql> COLUMN NAME HEADING "VIDEO TAPE|NAME"; sql> COLUMN INCOME HEADING "ANNUAL|INCOME"; sql> TTI ON; sql> TTI CENTER "OLD CLASSIC VIDEO STORE" SKIP sql> CENTER "ANNUAL INCOME ANALYSIS REPORT" SKIP 1 sql> LEFT "CATEGORY: "newval;sql> SELECT CATEGORIES,NAME,INCOME FROM TAPES UNNEST CATEGORIES WHEREsql> CATEGORIES IN ("C","R","S")sql> ORDER BY CATEGORIES; OLD CLASSIC VIDEO STORE ANNUAL INCOME ANALYSIS REPORTCATEGORY: C Type of Vide ------------ C VIDEO TAPE NAME American Graffiti ANNUAL INCOME 242.50 Type of Vide ------------ VIDEO TAPE NAME Catch 22 ANNUAL INCOME 786.50 Type of Vide ------------ VIDEO TAPE NAME Girl Friday ANNUAL INCOME 22.68 Type of Vide ------------ VIDEO TAPE NAME Help ANNUAL INCOME 202.50 OLD CLASSIC VIDEO STORE ANNUAL INCOME ANALYSIS REPORTCATEGORY: C ********** Start break line ********** ANNUAL INCOME’s sum 1254.18 ANNUAL INCOME’s avg 313.55 ********** Finish of Break **********

... OLD CLASSIC VIDEO STORE ANNUAL INCOME ANALYSIS REPORTCATEGORY: S ********** Start break line ********** ANNUAL INCOME’s sum 1222.02 ANNUAL INCOME’s avg 305.51 ********** Finish of Break **********

8-40

Page 260: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Displaying Report Environment ParametersTo display the report environment parameters, use the SHOW statement.

Syntax

SHOW {parameter | ALL}

For example, to display the current PAGESIZE and NEWPAGE settings, enter the following statements:

sql> SHOW PAGESIZE;Page size is 23sql> SHOW NEWPAGE;Newpage is 0

8-41 Using UniData SQL

Page 261: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Preparing Complex ReportsThis section demonstrates how to produce reports with values expressed as percentages of a total. The reports produced in earlier sections contained columns from a single table. However, the next example shows a report that has columns from more than one table. The VIDEO TAPE NAME data comes from the TAPES table; the CATEGORY CODE data is from the CATEGORIES table; and the data in the PERCENT STORE column is not contained is derived from the ANNUAL INCOME column:

OLD CLASSIC VIDEO STORE ANNUAL INCOME ANALYSIS REPORT

CATEGORY VIDEO TAPE ANNUAL PERCENTNAME NAME INCOME STORE-------- ---------- ------ -------C American Graffiti $242.50 9.30 Catch 22 $786.50 27.43 Girl Friday $22.68 0.79 Help $202.50 7.06 ------- ------- $1,254.18 44.58

R Gone With The Wind $311.52 10.86 Love Story $47.50 1.82 Tammy $3.18 0.11 ------- ------- $362.20 12.79

Producing a Complex ReportComplete the following steps to produce a report of this kind:

1. Compute the total annual income.2. Join the table TAPES with the table CATEGORIES and compute the desired

percentages.3. Format and print the report.4. Finalize the finished report.

An experienced UniData SQL user could issue a single set of query statements to produce the final result. For purposes of demonstration, however, the procedure is divided into four steps.

8-42

Page 262: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Note: If you have entered all the examples up to this point and before you continue with the next examples, reset all report formats to the default settings.

Computing Total Annual Income

The following example shows how to compute a total annual income:

sql> SELECT SUM(INCOME)sql> FROM TAPESsql> UNNEST CATEGORIESsql> WHERE CATEGORIES IN ("C","R","S");

Page 1SUM(Tape-------- 2838.40 11 record(s) calculated

8-43 Using UniData SQL

Page 263: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Joining Tables and Computing Percentages

To print out the category name instead of the category code, join the tables TAPES and CATEGORIES. To compute the percentages, you need only include an expression in the SELECT statement.

sql> SELECT X.NAME,Y.NAME,INCOME,INCOME/2838.40*100sql> FROM CATEGORIES X,TAPES Ysql> UNNEST CATEGORIESsql> WHERE CATEGORIES IN ("C","R","S")sql> AND X.@ID = Y.CATEGORIESsql> ORDER BY CATEGORIES;

Page 1Category Type Tape Tape Rev INCOME/2838.40*100---------------- ------------------ -------- ------------------Comedy American Graffiti 242.50 8.5400Comedy Catch 22 786.50 27.7100Comedy Girl Friday 22.68 0.8000Comedy Help 202.50 7.1300Romance Gone With The Wind 311.52 10.8500Romance Love Story 47.50 1.6700Romance Tammy 3.18 0.1100Science Fiction 2001 985.50 34.7200Science Fiction A Clockwork Orange 52.52 1.8500Science Fiction Flash Gordon 163.80 5.7700Science Fiction The Stalker 20.20 0.7100

11 records listed

Formatting and Printing the Report

To format the result into a report, add the following:

Header and footer (using TTITLE and BTITLE).Column headings and formats (using COLUMN).BREAK and COMPUTE statements to compute subtotals.

8-44

Page 264: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Notice that three attribute labels are used in the COLUMN statements:

CNAME for NAME in CATEGORIES.TNAME for NAME in TAPES.PS for the expression in the SELECT clause.

sql> SET SPACE 4;sql> SET LINESIZE 65;sql> COLUMN CNAME HEADING "CATEGORY|NAME"sql> FORMAT "A10" TRUNCATED;sql> COLUMN TNAME HEADING "VIDEO TAPE|NAME";sql> COLUMN INCOME HEADING "ANNUAL|INCOME" FORMAT "$9,999.99";sql> COLUMN PS HEADING "PERCENT|STORE" FORMAT "999.99";sql> BREAK ON CNAME SKIP 1;sql> COMPUTE SUM OF INCOME PS ON CNAME;sql> TTITLE ON;sql> TTITLE CENTER "OLD CLASSIC VIDEO STORE" SKIPsql> CENTER "ANNUAL INCOME ANALYSIS REPORT" SKIP;sql> BTITLE ON;sql> BTITLE SKIP 2 CENTER "FISCAL YEAR 1996-97";sql> SELECT X.NAME CNAME,Y.NAME TNAME,sql> INCOME,INCOME/2838.40*100 PSsql> FROM CATEGORIES X,TAPES Ysql> UNNEST CATEGORIES WHERE CATEGORIES IN ("C","R","S")sql> AND X.@ID = Y.CATEGORIES ORDER BY CATEGORIES;

8-45 Using UniData SQL

Page 265: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The output looks like this:

OLD CLASSIC VIDEO STORE ANNUAL INCOME ANALYSIS REPORT

CATEGORY VIDEO TAPE ANNUAL PERCENTNAME NAME INCOME STORE---------- -------------------- ---------- -------Comedy American Graffiti $242.50 8.54 Catch 22 $786.50 27.71 Girl Friday $22.68 0.80 Help $202.50 7.13********** ---------- -------sum $1,254.18 44.18 Romance Gone With The Wind $311.52 10.98 Love Story $47.50 1.67 Tammy $3.18 0.11********** ---------- -------sum $362.20 12.76 Science Fi 2001 $985.50 34.72

FISCAL YEAR 1996-97 OLD CLASSIC VIDEO STORE ANNUAL INCOME ANALYSIS REPORT CATEGORY VIDEO TAPE ANNUAL PERCENTNAME NAME INCOME STORE---------- -------------------- ---------- ------- A Clockwork Orange $52.52 1.85 Flash Gordon $163.80 5.77 The Stalker $20.20 0.71********** ---------- -------sum $1,222.02 43.05

FISCAL YEAR 1996-97

Finalizing the ReportYou can improve on two elements of the report format from the previous example. The COMPUTE statement generates these items:

The row of asterisks (*) “sum” in the CATEGORY NAME column

8-46

Page 266: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

In the query that produces the final report format, you select the NAME attribute in CATEGORIES twice:

The first time, you designate the attribute label DUMMY.The second time, you designate the attribute label CNAME.

Next, add a COLUMN statement for DUMMY and stipulate a NOPRINT option. This causes the DUMMY column to disappear from the final report. UniData SQL performs the BREAK and COMPUTE statements on this DUMMY column.

The DUMMY column is included in the SELECT statement to serve as an object for the COMPUTE statement. The COMPUTE statement computes sums when the value in DUMMY changes. Because UniData SQL will not print the DUMMY column, the asterisks (*) and the word “sum” associated with it also disappear from the final report:

sql> SET SPACE 2;sql> SET LINESIZE 80;sql> COLUMN CNAME HEADING "CATEGORY|NAME" FORMAT "A10" TRUNCATED;sql> COLUMN TNAME HEADING "VIDEO TAPE|NAME";sql> COLUMN INCOME HEADING "ANNUAL|INCOME" FOMAT "$9,999.99";sql> COLUMN PS HEADING "PERCENT|STORE" FORMAT "999.99";sql> COLUMN DUMMY NOPRINT;sql> BREAK ON CNAME ON DUMMY SKIP 1;sql> CLEAR COMPUTE;sql> COMPUTE SUM OF INCOME PS ON DUMMY;sql> TTITLE ON;sql> TTITLE CENTER "OLD CLASSIC VIDEO STORE" SKIPsql> CENTER "ANNUAL INCOME ANALYSIS REPORT" SKIP;sql> BTITLE ON;sql> BTITLE SKIP 2 CENTER "FISCAL YEAR 1996-97";sql> SELECT X.NAME DUMMY,X.NAME CNAME,Y.NAME TNAME,sql> INCOME,INCOME/2838.40*100 PSsql> FROM CATEGORIES X,TAPES Ysql> UNNEST CATEGORIES WHERE CATEGORIES IN ("C","R","S")sql> AND X.@ID = Y.CATEGORIES ORDER BY CATEGORIES;

Note: The BREAK statement breaks on both DUMMY and CNAME, which change their value at the same time. This is necessary for UniData SQL to generate the final report properly. DUMMY is specified in BREAK because it is to be used in the COMPUTE statement and a COMPUTE column must be a BREAK column. The CNAME is specified in BREAK because you want the CATEGORY NAME listed only once for each category, not for every row in the report.

8-47 Using UniData SQL

Page 267: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The output looks like this:

OLD CLASSIC VIDEO STORE ANNUAL INCOME ANALYSIS REPORT

CATEGORY VIDEO TAPE ANNUAL PERCENTNAME NAME INCOME STORE-------- ---------- ------ -------Comedy American Graffiti $242.50 8.54 Catch 22 $786.50 27.71 Girl Friday $22.68 0.80 Help $202.50 7.13

$1,254.18 44.18

Romance Gone With The Wind $311.52 10.98 Love Story $47.50 1.67 Tammy $3.18 0.11

$362.20 12.76

Science Fi 2001 $985.50 34.72...

FISCAL YEAR 1996-97

8-48

Page 268: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

9Chapter

Security and Administration

UniData SQL Security . . . . . . . . . . . . . . . . . 9-3Viewing Privileges . . . . . . . . . . . . . . . . . . 9-4Granting Privileges . . . . . . . . . . . . . . . . . . 9-7 GRANT . . . . . . . . . . . . . . . . . . . . 9-7Revoking Privileges . . . . . . . . . . . . . . . . . . 9-10 REVOKE. . . . . . . . . . . . . . . . . . . . 9-10Converting Files for UniData SQL . . . . . . . . . . . . . 9-14 Requirements . . . . . . . . . . . . . . . . . . 9-15 CONVERT.SQL . . . . . . . . . . . . . . . . . 9-16 Converting Demo Tables . . . . . . . . . . . . . . . 9-18

Page 269: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

This chapter describes the security methods UniData SQL uses to maintain table integrity and to control users’ access to the data. In addition, this chapter explains what you need to do to convert UniData files so UniData SQL can access them.

Note: When you attempt to enter UniData SQL, you might receive the error message "No UniData SQL privilege file in this account, creating

privilege file". Otherwise, you might successfully enter UniData SQL, but find you are unable to use the SELECT statement to retrieve data from the UniData demo database. In either case, contact your system administrator for information on properly configuring your system to allow you to access the demo database.

By the time you complete this chapter, you should be able to complete the following tasks:

Understand the methods UniData SQL uses for maintaining security on UniData SQL tables.View the privilege information in your account.Use the GRANT command.Use the REVOKE command.Use the CONVERT.SQL command.

9-2

Page 270: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

UniData SQL SecurityWhen a user creates a UniData SQL table, subtable, or view, the user owns the object. The owner is initially the only user who can access the object. If other users need to use the table, subtable, or view, the owner must grant them rights to access it. These access rights are called privileges. The owner can add and change privileges for other users.

If the owner grants privileges to another user with grant option, that user can grant any of the same privileges for the table, subtable, or view to other users.

Note: Only the owner of a table can drop it. Even if another user is granted ALL PRIVILEGES on a table, this does not give the user the ability to drop a table. For further information on dropping tables, see Chapter 3, “Creating and Modifying Tables.”

Any changes in privileges for underlying tables and views affect the privileges of views defined on them. If a base table is removed, UniData SQL drops any views created on that table. If the owner of a view loses all privileges on a base table, all views based on that table are dropped as well.

9-3 Using UniData SQL

Page 271: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Viewing PrivilegesUniData SQL stores privilege information in the privilege table. UniData SQL automatically creates a privilege file for each account.

The privilege table contains the following:

The user ID of the table owner, an asterisk, and the table name.The privileges the user has been granted, or “OWNER”.The WITH GRANT OPTION flag (0 or 1).The name of the user who granted the privilege.The name of the user to whom the privilege was granted.

9-4

Page 272: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

To view the privilege information in your account, execute the statement in the following example. This example shows privilege information for an account in UniData for UNIX. In UniData for Windows Platforms, the grantor would be Admin-istrator instead of root.

sql> SELECT * FROM privilege; Page 1privilege access field grant_op grantor grantee-------------------------- -------- ---------- -------- ---------- ----------0*CATEGORIES ALL 1 root PUBLIC0*ENGLISH.MSG ALL 1 root PUBLICPUBLIC*CTLGTB SELECT 0 root INSERT 0 root DELETE 0 root UPDATE ALL 0 root1210*sysobjects OWNER PUBLICPUBLIC*syscolumns SELECT 0 user INSERT 0 user DELETE 0 user UPDATE ALL 0 user0*CUSTOMER ALL 1 root PUBLIC1210*INVENTORY_LINE_ITEM_M OWNERV_SUB SELECT 0 root INSERT 0 root DELETE 0 root UPDATE ALL 0 root1210*SQLTables OWNER PUBLIC0*_REPORT_ ALL 1 root PUBLIC1210*INVENTORY_NF_SUB OWNER SELECT 0 root INSERT 0 root DELETE 0 root UPDATE ALL 0 rootPUBLIC*CLIENTS SELECT 0 root INSERT 0 root DELETE 0 root UPDATE ALL 0 root1210*sysalternates OWNER PUBLIC0*CTLGTB ALL 1 root PUBLIC0*_SCREEN_ ALL 1 root PUBLIC0*__V__VIEW ALL 1 root

9-5 Using UniData SQL

Page 273: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

PUBLIC1210*INVENTORY_NF OWNER SELECT 0 root INSERT 0 root DELETE 0 root UPDATE ALL 0 root...1210*INVENTORY_Accounting OWNER SELECT 01210*SQLColumns OWNER PUBLIC0*&MAP& ALL 1 root PUBLICPUBLIC*SQLStatistics SELECT 0 user INSERT 0 user DELETE 0 user UPDATE ALL 0 userPUBLIC*STAFF SELECT 0 root INSERT 0 root DELETE 0 root UPDATE ALL 0 root74 records listed

You can query the privilege table, but do not attempt to modify the information it contains. You could destroy the existing privileges and cause your UniData SQL tables to become inaccessible.

9-6

Page 274: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Granting PrivilegesInitially, only the owner of a table, subtable, or view can access the object. If other users need to use the table, subtable, or view, the owner must grant them privileges to access it.

If the owner grants privileges to another user with grant option, that user can grant any of the same privileges for the table, subtable, or view to other users.

If you attempt to grant privileges on a table, view, or subtable for which you do not have privileges, or on an object that does not exist, the following error message appears:

Sorry, you have no privilege on this file!

GRANTUse the GRANT command to grant privileges to other users for a table, subtable, or view you own or for which you have privilege. This command makes entries to the privilege table, described in “Viewing Privileges” on page 9-4.

Syntax

GRANT {ALL PRIVILEGES| privilege[,privilege]...} ON table_spec TO {PUBLIC | user_name[, user_name]...} [WITH GRANT OPTION]

9-7 Using UniData SQL

Page 275: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Parameters

The following table describes each parameter of the syntax.

GRANT Parameters

Privilege Description

ALL PRIVILEGES Grants all privileges the user of the command is allowed to grant.If the user is the owner of the object, all privileges are DELETE, INSERT, SELECT, and UPDATE.If the user is not the owner of the object, the user can grant only those privileges acquired with grant option.

privilege Specifies privilege(s) to grant the user(s):DELETE – Privilege to delete rows from a table, subtable, or view.INSERT – Privilege to insert rows in a table, subtable, or view.SELECT – Privilege to select data in a table, subtable, or view.UPDATE – Privilege to change values in a table, subtable, or view.

ON table_spec Specifies the table, subtable, or view on which to grant privileges.

TO PUBLIC Grants privilege to all users who have access to the server machine.

TO user_name Grants access to the user specified by user_name.

WITH GRANT OPTION

Gives the recipient(s) permission to grant the privileges they acquired on this table, subtable, or view.

Granting Privileges to Users

The following example shows how to grant all privileges to a single user for a table:

sql> GRANT ALL PRIVILEGES ON STUDENT TO sue;

The following example shows how to grant a specific privilege to two users:

sql> GRANT SELECT ON STUDENT TO sue, bob;

The following example shows how to grant a privilege with grant option:

sql> GRANT SELECT ON STUDENT TO SUE WITH GRANT OPTION;

This enables the user Sue to grant SELECT privilege on STUDENT to other users.

9-8

Page 276: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Granting Privileges on Views

UniData SQL enables you to select the view for which you want to grant privileges. In this way, you can limit user access to a portion of a table. For further information on views, see Chapter 7, “Creating and Querying Views.”

The following example illustrates the security mechanism based on views. Imagine you want Sue to see only certain data from the STUDENT table. First, the example shows how to create a view of a portion of data in the STUDENT table. Second, the example shows how to grant SELECT privileges to Sue, only on the view, not on the base table.

sql> CREATE VIEW ST_NAME AS SELECT FNAME,LNAME FROM STUDENT; View ST_NAME created.

sql> GRANT SELECT ON ST_NAME TO sue;

9-9 Using UniData SQL

Page 277: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Revoking PrivilegesUniData SQL enables you to revoke privileges on a table, subtable, or view that you have previously granted.

If more than one person grants a user access to a table, the user continues to have access to the table until everyone who granted access revokes the privilege. When you revoke privileges from a user, UniData SQL revokes privileges from all other users who were granted privileges by that user.

REVOKEUse the REVOKE command to remove privileges on a table, subtable, or view that you have previously granted. This command makes entries to the privilege table, which is described in “Viewing Privileges” on page 9-4.

Syntax

REVOKE privilege ON table_spec FROM user_name[, user_name]...;

Revoking Privileges from Users

The following example demonstrates how to revoke the same privilege from two users:

sql> REVOKE SELECT ON STUDENT FROM sue, bob;

9-10

Page 278: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Examples of Granting and Revoking Privileges

GRANT

TABLE1 owner: Sam

Sarah: CREATE VIEW V1 ON TABLE1;

TABLE1

owner: SamSarah’s

V1 owner: Sarahprivileges: select

Sam: GRANT UPDATE ON TABLE1 TO Sarah;

Sam: GRANT SELECT ON TABLE1 TO Sarah;

privileges: selectTABLE1 owner: Sam

Sarah’s

update

V1 owner: Sarahprivileges: select update

privileges: selectTABLE1

owner: SamSarah’sprivileges: select

9-11 Using UniData SQL

Page 279: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Sam: GRANT SELECT ON TABLE1 TO Sarah;

Sarah: CREATE VIEW V1 ON TABLE1;

V1

Sam: REVOKE SELECT ON TABLE1 FROM Sarah;

TABLE1 owner: Sam

TABLE1owner: SamSarah’sprivileges: select

TABLE1owner: SamSarah’sprivileges: select

owner: SarahSarah’sprivileges: select

TABLE1 owner: Sam

(view has been dropped)

REVOKE

9-12

Page 280: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

GRANT

TABLE1 owner: Sam

Sam: GRANT ALL PRIVILEGES ON TABLE1 TO Sarah;

TABLE1 owner: SamSarah’s

deleteupdateinsert

ase 1

ase 2

TABLE1

privileges: select

Sam: GRANT SELECT, DELETE ON TABLE1 TO Sarah WITH GRANT OPTIO

TABLE1 owner: Sam

Sam: GRANT UPDATE ON TABLE 1 TO Sarah;

TABLE1

Sam: GRANT UPDATE ON TABLE 1 TO SARAH;

privileges: selectTom’s

delete

owner: SamSarah’sprivileges: select with grant option

update

owner: SamSarah’sprivileges: select with grant option delete with grant option update

delete with grant option

9-13 Using UniData SQL

Page 281: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Converting Files for UniData SQLUniData and UniData SQL share data and dictionary files. Therefore, when you create a new table in UniData SQL, it is immediately accessible by all other UniData tools such as UniQuery, UniBasic, and ECL. From within UniData SQL, however, only the person who created the table can access it. To make the table accessible to other users, the owner must grant other users access to the table.

On the other hand, all UniData files must undergo a conversion process for UniData SQL to access them.

The CONVERT.SQL ECL command checks the UniData file for conformance to the SQL requirements. Where it detects an inconsistency, UniData responds depending upon the CONVERT.SQL option selected:

CHECKONLY – Displays a message and does not make any changes.FORCE – Makes necessary changes during the conversion process without prompting for user response.No option – UniData displays a conforming alternative and prompts for user input.

UniData takes the following actions:

Checks the name of the file being converted. If the filename is ODBC compliant, UniData uses this name for the table. If the filename is not ODBC compliant, UniData creates a new, duplicate dictionary file with a compliant name for use by ODBC/UniData SQL.Checks attribute specifications for missing value code and format specification.Creates synonyms (also called aliases) in the dictionary for attribute names that do not conform to the ODBC conventions. For each noncompliant attribute name, UniData creates or adds an entry in the attributes @SYNONYM and @ORIGINAL to link the new compliant attribute name with the original attribute name.Adds conforming names of the converted files to the UniData SQL privilege table.

9-14

Page 282: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

CONVERT.SQL does not:

Change the data portion of files being converted. Create 1NF schema (1NF views or subtables); therefore, converted tables are not necessarily accessible through UniClient tools. For further infor-mation on UniData ODBC, see Developing UniData ODBC Applications. For further information on 1NF schema management, see Using VSG and the Schema API.

Note: Converted files are called base tables.

RequirementsYou must be at the UniData colon prompt (:) to use the ECL CONVERT.SQL command.

User Requirements

To execute this command, you must be one of the following:

If you are using UniData for UNIX, you must be the UNIX owner of the file or you must log on as root.If you are using UniData for Windows Platforms, you must be the owner of the file or you must log on as Administrator.

UniData SQL Table RequirementsFor a table to be accessible through UniData SQL, the table name and attribute names must meet certain conditions.

Valid names can contain the following types of characters:Alphabetic charactersNumbersSpecial characters: “_”, “@”, “#”, and “$”

The first character of the name must be an alphabetic character, underscore (_), or at symbol (@).

9-15 Using UniData SQL

Page 283: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Note: If you plan to access the data in a table, subtable, or view through ODBC, do not use @, #, or $ anywhere in the table name or attribute name, and do not use an underscore (_) as the first character.

The name can be no longer than 30 characters.The name cannot be a UniData SQL reserved word.A table name must be unique among tables, subtables, and views in the database, and an attribute name must be unique among attribute names within the table, subtable, or view.

CONVERT.SQLUse the CONVERT.SQL ECL command to convert files for UniData SQL.

Syntax

CONVERT.SQL [filename] [length] [CHECKONLY | FORCE] [PUBLIC [privilege]]

Parameters

The following table describes the parameters for this command.

Parameter Description

filename Specifies the name of the file to convert. If you omit filename, CONVERT.SQL converts all file names contained in the active select list, if one exists.

CONVERT.SQL Parameters

9-16

Page 284: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Example

Suppose you have a UniData file called test.example in your account. The following example shows how to convert test.example so it can be accessed in UniData SQL. During the conversion process, UniData checks for missing value code and format.

length Specifies the length of the input file name (maximum is 30 characters).

CHECKONLY | FORCE

CHECKONLY reports the problems found in the conversion process, but does not make any changes.FORCE makes necessary file changes during the conversion process and displays changes on the terminal.No option – UniData displays each file and attribute name that does not conform to ODBC requirements, suggests an acceptable name, and waits for the user to enter an acceptable name or to press ENTER and accept the suggested name.

PUBLIC privilege

Grants the privilege specified in privilege to all users. If PUBLIC is specified, but privilege is omitted, privilege defaults to ALL.You can use the following options: ALL, INSERT, UPDATE, DELETE, or SELECT. For information about these options, see “Parameters” on page 9-8 for the GRANT command.You must log on as root in UniData for UNIX or as Administrator in UniData for Windows Platforms to grant this privilege.

Parameter Description

CONVERT.SQL Parameters (continued)

9-17 Using UniData SQL

Page 285: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

In this example, the user enters S for a singlevalue attribute type, and 8R for format specification. UniData supplies the name test_example for the noncompliant file name test.example, but the user overrides this with the table name INVENTORY.

:convert.sql test.example default name length 30 is usedchecking file 'test.example' ... missing or illegal S_M spec for field ‘UP_NAME’enter [S/MV/MS/M]SS_M spec of field 'UP_NAME' has been changed to 'S'invalid FMT ''in field 'ACT'enter new FMT [number[R8RFMT spec of field 'ACT' has been changed to '8R' 2 conversions have been made to dictionaryfile name 'test.example' will be changed to 'test_example'enter <CR> to accept, or enter your own synonym name: INVENTORYfile name 'test.example' will be changed to 'INVENTORY' file synonym 'INVENTORY' has been added to VOC 1 file has been converted

Converting Demo TablesWhen you first install UniData, all the UniData tables that are in the sample databases should already be converted for UniData SQL and should be granted PUBLIC privi-leges. These sample databases are used throughout the UniData SQL documentation for demonstration and tutorial purposes. If you cannot access these tables in UniData SQL, you will be unable to follow the examples throughout this book.

If you find that the tables in the sample databases have not been converted, ask your system administrator to convert the files using the CONVERT.SQL instructions and grant PUBLIC privileges to each table.

You may need to convert the following tables in the sample databases:

CUSTOMERTAPESCATEGORIESSTUDENTSTAFFCOURSES

9-18

Page 286: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

CLIENTSORDERSINVENTORY

9-19 Using UniData SQL

Page 287: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

10Chapter

UniData SQL Transaction Processing

Benefits of UniData SQL TP . . . . . . . . . . . . . . . 10-4 ACID Properties . . . . . . . . . . . . . . . . . 10-4UniData SQL TP and Other UniData Products . . . . . . . . . 10-5 UniData SQL TP and RFS . . . . . . . . . . . . . . 10-5 UniData SQL TP and UniBasic . . . . . . . . . . . . . 10-5Transaction Semantics . . . . . . . . . . . . . . . . . 10-6 Initiation . . . . . . . . . . . . . . . . . . . . 10-6 Termination . . . . . . . . . . . . . . . . . . . 10-6UniData SQL TP Locks . . . . . . . . . . . . . . . . 10-7 Other Types of Locks . . . . . . . . . . . . . . . . 10-7Transaction Isolation . . . . . . . . . . . . . . . . . 10-8 Types of Transaction Errors . . . . . . . . . . . . . . 10-8 UniData SQL Isolation Levels . . . . . . . . . . . . . 10-10UniData SQL TP Commands . . . . . . . . . . . . . . . 10-16 TP Commands . . . . . . . . . . . . . . . . . . 10-16 Transaction-Initiating Commands . . . . . . . . . . . . 10-16 Unsupported Commands . . . . . . . . . . . . . . . 10-16SET DISPLAY TPMESSAGE . . . . . . . . . . . . . . 10-18SET TRANSACTION . . . . . . . . . . . . . . . . . 10-20COMMIT . . . . . . . . . . . . . . . . . . . . . 10-22ROLLBACK . . . . . . . . . . . . . . . . . . . . 10-23AUTO COMMIT . . . . . . . . . . . . . . . . . . 10-24LOCK TABLE . . . . . . . . . . . . . . . . . . . 10-26Examples of UniData SQL TP . . . . . . . . . . . . . . 10-28 Example 1 – Read Committed vs. Repeatable Read . . . . . . 10-28 Default Transaction Settings . . . . . . . . . . . . . . 10-31Other UniData SQL TP Considerations. . . . . . . . . . . . 10-34

Page 288: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

10-2 U

System Administration . . . . . . . . . . . . . . . 10-34 Performance . . . . . . . . . . . . . . . . . . . 10-35 Interaction of UniData SQL with Other Transactional

Environments . . . . . . . . . . . . . . . . . . 10-36Tips on Transactions . . . . . . . . . . . . . . . . . . 10-40 Optimizing Performance . . . . . . . . . . . . . . . 10-40 Limitations . . . . . . . . . . . . . . . . . . . 10-40

sing UniData SQL

Page 289: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

UniData SQL transaction processing (TP) treats multiple physical file updates that occur in one transaction as one logical update. Once a transaction starts, all of its operations either commit or roll back. If a transaction commits, all updates are made even if a failure occurs at a later point.

UniData SQL syntax is compliant with ANSI ‘92 SQL standards. It also incorporates a few UniData SQL–specific extensions that relate to the NF2 data model.

10-3

Page 290: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Benefits of UniData SQL TPYou can perform the following operations with UniData SQL TP:

Start transactions from UniData SQL or continue in UniData SQL with a transaction that has started in an encompassing UniBasic program.Specify the access mode and isolation level of a UniData SQL–initiated transaction.Control whether a transaction consists of a single SQL statement, or multiple statements.

ACID PropertiesUniData SQL TP provides ACID properties: atomicity, consistency, isolation, and durability. See Administering the Recoverable File System for a description of each of these properties.

10-4 Using UniData SQL

Page 291: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

UniData SQL TP and Other UniData ProductsThe ability of UniData SQL to perform transaction processing is dependent on your use of other UniData products.

UniData SQL TP and RFSUniData SQL TP is based on the UniData Recoverable File System (RFS), which provides the logging and recovery facilities. The full ACID properties of UniData SQL transactions apply only to recoverable files. Therefore, although operations on non-RFS files are allowed within UniData SQL transactions, operations on these files are not recoverable.

UniData SQL TP and UniBasicUniData SQL follows ANSI ‘92 standards, but UniBasic does not. For this reason, the types of transaction errors that can occur and the isolation levels that can be achieved differ between the two products.

Note: IBM recommends that you not execute applications that perform transactions and those that do not perform transactions at the same time. If both types of applications make updates to the same UniData file at the same time, indexes based on virtual fields might not be updated, and the only notification you will receive is a warning recorded in the sm.log file.

10-5

Page 292: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Transaction Semantics

InitiationA transaction is initiated when UniData SQL encounters the first transaction-initi-ating statement after a user logs into UniData SQL or after a previous transaction terminates.

TerminationA transaction is terminated when one of the following conditions exists:

AUTOCOMMIT is OFF and UniData SQL encounters a COMMIT or ROLLBACK statement.AUTOCOMMIT is ON. In this case, UniData SQL performs an auto commit of each statement.An application terminates. A commit is performed when an application terminates normally. A rollback is performed when an application termi-nates abnormally.

Note: You cannot turn off UniData SQL TP.

10-6 Using UniData SQL

Page 293: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

UniData SQL TP LocksUniData SQL TP uses an automatic locking mechanism to implement different isolation schemes. UniData SQL employs a record-locking mechanism and two lock modes:

SharedExclusive

Shared locks are set on records and tables involved in read-only operations, such as SQL SELECT. Multiple shared locks can be set on a single record by multiple concurrent transactions.

Exclusive locks are set on records and tables involved in insert, update and delete operations. An exclusive lock prevents other users from acquiring shared or exclusive locks on the same record.

Other Types of LocksTo reduce the number of locks held by a process, UniData SQL employs additional locking techniques for certain types of operations, such as large table scans with high levels of isolation. These techniques are controlled by UniData without direction from the user. For example, regardless of the isolation level specified, UniData SQL always places exclusive locks on all records that are involved in an insert, update, or delete operation, and holds these locks until the end of the transaction.

10-7

Page 294: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Transaction IsolationIdeally, the execution of concurrent transactions produces the same effect as if these transactions were executed serially. This highest level of isolation is called serial-izable. However, for performance reasons, this level of isolation may be unrealistic. Therefore, UniData SQL supports four levels of isolation, each of which prevents different types of transaction errors.

Types of Transaction ErrorsANSI ‘92 defines the levels of isolation in terms of the types of violations of serial-izability allowed and prevented, which include the following:

Dirty Read – During a transaction, a query executed by another process obtains a value that is no longer valid when the first process rolls back.Unrepeatable Read – The same query executed at two different times in the same transaction obtains different values for the same attribute because another process changes the value between the two queries.Phantom – A query executed at two different times obtains additional values the second time because another process adds a value between the two queries.

UniBasic and UniData SQL TP differ in the following ways with regard to the minimum protection provided by the product against transaction errors:

UniData SQL TP always prevents lost updates and dirty reads, but may allow phantoms or unrepeatable reads.UniBasic TP always prevents dirty reads and phantoms but allows lost updates.

10-8 Using UniData SQL

Page 295: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Example of a Dirty Read

In this example, transaction 2 retrieves a value that no longer exists after the rollback.

Dirty Read Example

Transaction 1 Transaction 2attr 1 Value

SELECT attr1 FROM T WHERE ID=123

1

UPDATE T SET attr1=2 WHERE ID=123

2

SELECT attr1 FROM T WHERE ID=123

2

ROLLBACK 1

Example of an Unrepeatable Read

In this example, transaction 2 retrieves an attribute twice, obtaining two different values.

Unrepeatable Read Example

Transaction 1 Transaction 2attr 1 Value

SELECT attr1 FROM T WHERE ID=123

1

SELECT attr1 FROM T WHERE ID=123

1

UPDATE T SET attr1=2 WHERE ID=123 COMMIT

SELECT attr1 FROM T WHERE ID=123

2

10-9

Page 296: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Example of a Phantom

In this example, transaction 1 executes the same query twice, but obtains an additional value in the second result set.

Phantom Example

Transaction 1 Transaction 2 Values Retrieved

SELECT attr1 FROM T WHERE attr2="a"

attr1=1 attr1=2

INSERT INTO T(id,attr1,attr2) values(1,3,"a") COMMIT

SELECT attr1 FROM T WHERE attr2="a"

attr1=1 attr1=2 attr1=3

UniData SQL Isolation LevelsFor RFS files, UniData SQL supports all four SQL isolation levels. For non-RFS files, UniData SQL supports only Repeatable Read (RR) and Serializable (S). Isolation level is specified in the UniData SQL SET TRANSACTION command.

Regardless of the isolation level, exclusive locks are placed on all records being modified. These locks are maintained until the transaction is comitted or aborted.

10-10 Using UniData SQL

Page 297: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Summary of Isolation Levels

The table below summarizes the application of isolation levels in UniData SQL.

Summary of Isolation Levels

Isolation Level Notes Access Modes

Shared Locks Set by SELECT

Read Uncommitted

Allows dirty reads; may allow the database to remain inconsistent.

read-only no

Read Committed

Supported for RFS files only; repeated queries may return different results.

read-only read/write (default)

no

Repeatable Read Supported for RFS and non-RFS files; repeated queries return the same results; allows phantoms.

read-only read-write (default)

yes

Serializable Supported for RFS and non-RFS files; repeated queries return the same results; phantoms are not permitted.

read-only read/write (default)

yes

Read Uncommitted (RU)Transactions executed with an isolation level of RU may read dirty data, and may allow the database to remain inconsistent when the transaction that “dirties” the data rolls back; therefore, transactions that run at RU level are read-only.

UniData SQL places no locks on records read at isolation level RU.

Read Committed (RC)With the isolation level RC, you can specify either read-only or read/write access mode. If none is specified, UniData SQL assumes read/write.

For RFS files, since the local buffer is used, and no dirty data will be perceived by other transaction, UniData SQL does not place any locks on records that are being read. This implies that if a record is reread within the same transaction, its values may not be the same, or the repeatability of the read record is violated.

10-11

Page 298: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Note: If a transaction has the read-write access mode, which is the default, then a user can enter SELECT, UPDATE, INSERT, and DELETE statements. Because SQL SELECT is a read-only operation, it does not place any locks on records that are being read; but exclusive record locks are held until the end of the transaction. This prevents other users from updating the same record, and transactions with higher isolation levels from retrieving the record that is being updated.

Repeatable Read (RR)

When this isolation level is specified in the SET TRANSACTION statement, UniData SQL ensures, that all read operations within this transaction are repeatable. You can specify a read-only or read-write access mode. If none is specified, the system assumes read-write.

UniData SQL places shared locks on all records that are being read and keeps them until the end of the transaction. It ensures, that if a record is reread within the same transaction, then its values are guaranteed to be the same, since no other transaction can update or delete a record that is locked in shared mode.

If a transaction has read/write access mode, a user can enter SELECT, UPDATE, INSERT and DELETE statements. Since SQL SELECT is a read-only operation, it places shared locks on records that are being read until the end of the transaction, as was explained above. Specifying this isolation level may lead to a reduced level of concurrency. Because shared locks are held for the duration of the transaction, no other transaction can update or delete any record retrieved by this transaction until this transaction terminates. Use this isolation level only if your application requires the repeatability of retrieved values. Also, keep such transactions short.

As with other isolation levels, exclusive record locks are placed on all records that are being inserted, updated or deleted and these locks are held until the end of the transaction.

Serializable (SR)

When SR isolation level is specified, UniData SQL ensures that all read operations within this transaction are repeatable and that no phantoms are possible. You can specify read-only or read/write access mode. If none is specified, read/write is assumed.

UniData SQL uses a mixture of file and record-level locks depending on the way the data is being accessed:

10-12 Using UniData SQL

Page 299: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

If UniData SQL can access a record directly, as in a case where the target record @ID is supplied, UniData SQL places shared locks on records being read, and exclusive locks on records being updated. If UniData SQL needs to read an entire table to find records that satisfy the search condition, it places a file-level shared lock on the table being read, and record-level exclusive locks on records being updated. This ensures that no phantoms are possible, since file-level locks prevent other users from inserting data into locked files.

The following fragment presents an example where record-level locks are used by UniData SQL. Note the use of the ID in the WHERE clause.

This transaction locks only two records, since UniData SQL performs query optimi-zation to directly access the two records. The first statement places shared locks and the second statement places exclusive locks. For further information on optimizing queries, see Chapter 7, “Creating and Querying Views.”

sql> SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;sql> SELECT * FROM ORDERS WHERE ID='912' OR ID='913';Transaction started.Page 1 Order Order Order Client Number Date Time Number Product Nu Color Qty Price---------- ---------- ------- ---------- ---------- ---------- ------ ---------- 912 01/13/1996 12:30PM 9984 53000 N/A 6 $129.95 913 01/13/1996 03:36PM 10010 13005 Gray 5 $500.002 records listed sql> DELETE FROM ORDERS '913';1 record(s) deleted or updated.sql> COMMIT; Transaction committed.

10-13

Page 300: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

When you use standard SQL statements without specifying specific records (using the ID LIST clause or, as in the example above, ID=‘912’), UniData SQL locks the whole table, as in the following example:

sql> SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; sql> SELECT * FROM ORDERS WHERE CLIENT_NO='9984'; Transaction started. Page 1 Order Order Order Client Number Date Time Number Product Nu Color Qty Price---------- ---------- ------- ---------- ---------- ---------- ------ ---------- 912 01/13/1996 12:30PM 9984 53000 N/A 6 $129.951 records listed

Note that, even if this query is processed using an index (that is, an index exists on CLIENT_NO), UniData SQL still locks the entire data file, because if allowed, other transactions might add new records that would result in new index values being added.

Tip: Serializable transactions may have negative effects on the concurrency level of the database. Use this isolation level only when you must prevent any possibility of phantoms being created.

10-14 Using UniData SQL

Page 301: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

UniData SQL TP Commands

TP CommandsUniData SQL TP consists of the following commands:

SET DISPLAYSET DISPLAY TPMESSAGECOMMITROLLBACKAUTO COMMITLOCK TABLE

Transaction-Initiating CommandsThe following commands initiate transactions:

SELECTINSERTUPDATEDELETELOCK TABLE

Unsupported CommandsAn error occurs and the transaction terminates when one of the following commands is encountered in a transaction:

CREATE [TABLE | VIEW | SUBTABLE | INDEX]DROP [TABLE | VIEW | SUBTABLE | INDEX]ALTER TABLEGRANTREVOKE

10-15

Page 302: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

! (shell escape)SET TRANSACTIONAUTO COMMIT {ON | OFF}

10-16 Using UniData SQL

Page 303: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

SET DISPLAY TPMESSAGE

SyntaxSET DISPLAY TPMESSAGE [ON | OFF]

DescriptionThe SET command option DISPLAY TPMESSAGE turns on or off display of trans-action processing notification messages for all transactions.

Note: UniData SQL always displays “Transaction aborted” when a transaction is rolled back, regardless of the TPMESSAGE setting.

Unless SET DISPLAY TPMESSAGE is ON, UniData SQL transaction processing displays no message when a transaction starts or commits.

After the execution of the above command, UniData SQL displays:

“Transaction started.”

when a UniData SQL transaction is started, and displays:

“Transaction committed.”

when a transaction is committed.

The SET DISPLAY statement spans transaction boundaries. After it is turned on, it remains on until turned off.

To display current setting of transaction message option, enter:

SET DISPLAY TPMESSAGE

ExamplesThe following example demonstrates turning on display of transaction start and trans-action commit messages:

sql> SET DISPLAY TPMESSAGE ON;

10-17

Page 304: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

After the preceding SET DISPLAY TMESSAGE ON statement is executed, any statement that creates, updates, or deletes a table generates Transaction started and Transaction committed messages, as in the following example:

sql> INSERT INTO INVENTORY (ID, FEATURES, COLOR, QTY, PRICE, REORDER)sql> VALUES (99999, "133 MHz CPU, 25-in. SVGA Monitor, Keyboard, Mouse,sql> Microsoft Office", "Black", 50, 1000.00, 10);Transaction started.1 record(s) created.

Transaction committed.

sql> SELECT * FROM INVENTORY WHERE ID = "99999"; Transaction started.Page 1INVENTORY 99999Inventory Date Inventory Time Product Name Features 133 MHz CPU, 25-in. SVGA Monitor, Keyboard, Mouse,Microsoft OfficeColor Quanti Price Reorde---------- ------ ---------- ------Black 50 $1,000.00 10 1 records listed

Transaction committed.

10-18 Using UniData SQL

Page 305: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

SET TRANSACTION

SyntaxSET TRANSACTION [READ ONLY | READ WRITE] ISOLATION LEVEL{READ UNCOMMITTED | READ COMMITTED | REPEATABLE READ | SERIALIZABLE}

DescriptionThe SET command option TRANSACTION specifies the access mode and isolation level of the next transaction to be initiated. It does not start a new transaction, and it cannot be executed within an active transaction. If you do not specify both access mode and isolation level, default UniData SQL settings are applied: READ WRITE ISOLATION LEVEL READ COMMITTED.

This statement applies to the next transaction only. After that default settings are returned. You can change the level of isolation for your environment by changing the environment variable DEFAULT_ISO_LEVEL. For further information, see Admin-istering UniData.

Note: SET TRANSACTION is included in the SET section of the UniData SQL Commands Reference.

10-19

Page 306: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

ParametersThe following table describes each parameter of the syntax.

SET TRANSACTION Parameters

Parameter Description

READ ONLY Specifies that the next transaction is read-only.

READ WRITE Specifies that the next transaction is read-write.

ISOLATION LEVEL Select one of the following four isolation levels:READ UNCOMMITTED READ COMMITTED REPEATABLE READ SERIALIZABLEFor details on isolation levels, see “UniData SQL Isolation Levels” on page 10-10.

ExampleThe transaction in the following example is read-only and has the isolation level of read uncommitted:

sql>SET TRANSACTION READ ONLY ISOLATION LEVEL READ UNCOMMITTED;SELECT * FROM STUDENT;EMP_NAME='Dow, John' WHERE EMPID='1001';COMMIT;

10-20 Using UniData SQL

Page 307: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

COMMIT

SyntaxCOMMIT [WORK]

DescriptionThe UniData SQL COMMIT command concludes an active transaction. The optional keyword WORK is provided for backward compatibility. If a COMMIT command executes without an active transaction, UniData SQL displays the following error message:

Invalid transaction termination: no active transaction.

The system performs the following steps during a transaction commit:

Disables the interrupt key.Writes all updates.Releases all locks acquired within the transaction.Enables the break key.

If the transaction cannot commit, the system performs the following steps:

Aborts the transaction.Releases all locks acquired within the transaction.

10-21

Page 308: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

ROLLBACK

SyntaxROLLBACK [WORK]

DescriptionThe UniData SQL ROLLBACK command cancels an active transaction. UniData SQL discards pending writes and releases all locks acquired during the transaction. The optional keyword WORK is provided for backward compatibility with legacy systems.

All commands issued from the beginning of the transaction are undone; therefore, no updates associated with the transaction take place.

A transaction can be rolled back due to any of several conditions in addition to execution of a ROLLBACK command, including:

File-access errors (such as no privilege, violation of operation system level security, and so forth).Locking errors, such as deadlocks.Invalid command or invalid command syntax.If SB_FLAG is OFF, executing the ROLLBACK command produces a system message indicating that the transaction has been aborted when it has not.

10-22 Using UniData SQL

Page 309: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

AUTO COMMIT

SyntaxAUTO COMMIT [ ON | OFF ]

DescriptionAUTO COMMIT ON causes each statement to immediately commit.

ParametersThe following table describes each parameter of the syntax.

AUTO COMMIT Parameters

Parameter Description

ON Each UniData SQL statement is immediately committed, releasing all locks. The default is interactive mode

OFF Several statements can be combined into one transaction.Set AUTO COMMIT OFF to be able to commit or roll back a set of state-ments as a single unit.

no option Displays the current setting of AUTO COMMIT.

Note: Unlike SET TRANSACTION, which sets options that apply to the next transaction only, AUTO COMMIT affects all subsequent transactions until UniData SQL encounters another AUTO COMMIT statement.

10-23

Page 310: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

ExampleThe following example demonstrates the use of AUTO COMMIT to display or change its status:

sql> AUTO COMMIT;Transaction auto commit option is ON.sql> AUTO COMMIT OFF;sql> AUTO COMMIT;Transaction auto commit option is OFF.

10-24 Using UniData SQL

Page 311: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

LOCK TABLE

SyntaxLOCK TABLE table_name [,table_name...] IN {SHARE | EXCLUSIVE} MODE [NOWAIT]

DescriptionLOCK TABLE overrides UniData’s automatic locking system, thus providing a means of controlling the level of isolation for tables. LOCK TABLE is the only UniData SQL command that explicitly locks tables. See Administering UniData for an explanation of the UniData locking scheme.

Examples of situations in which you should use LOCK TABLE:

A transaction accesses many files, but you need to isolate only one key file from other transactions. LOCK TABLE enables you to specify a lower-level isolation (such as RC) for a transaction, while locking a file at a higher level. An application may eventually lock almost all records in a file. UniData SQL locks records as they are needed, then converts to a file lock when a majority of the records are locked. This can result in a deadlock. To avoid this, use LOCK TABLE to lock the file at the beginning of the application.A batch process that updates records.

When LOCK TABLE is issued and no transaction is active, UniData SQL starts a new transaction. Upon termination of the transaction, all locks are released.

When an application requests a file lock against records that are already locked by another user, the application waits until the locks are released. This can appear to be a system or terminal hang to the user. Include the NOWAIT keyword to avoid this.

UniData SQL allows a maximum of 128 files to be locked within a transaction — including system-imposed locks as well as locks set by the user.

10-25

Page 312: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

ParametersThe following table describes each parameter of the syntax.

LOCK TABLE Parameters

Parameter Description

table_name Specifies the table to be locked.

IN SHARE MODE Indicates that a shared lock is to be placed on the table.

IN EXCLUSIVE MODE

Indicates that an exclusive lock is to be placed on the table.

NOWAIT Aborts the transaction rather than wait for a lock to be released. If you do specify NOWAIT and include several files in single LOCK TABLE command, and any one of the files is already locked, the command fails.

10-26 Using UniData SQL

Page 313: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Examples of UniData SQL TPThe following examples illustrate how different locking schemes affect isolation levels with the ORDERS database file.

Attributes in ORDERS Database

ID F1 F2

2 4 a

8 3 a

1 3 b

3 2 c

5 3 d

6 1 b

7 4 a

Example 1 – Read Committed vs. Repeatable ReadThis example demonstrates a nonrepeatable read: different results are obtained from the same SELECT statement in steps 1 and 4.

Read Committed Isolation Level

Step Transaction 1 (RC level) Transaction 2 (any level)

1 SELECT F2 FROM ORDERS WHERE ID = 2;(result ‘a’)

2 UPDATE ORDERS SET F2=’b’ WHERE ID=2;

3 COMMIT;

4 SELECT F2 FROM ORDERS WHERE ID = 2;(result ‘b’)

10-27

Page 314: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

In the next example, transaction 1 is executing with the isolation level RR (Repeatable Read), thus preventing nonrepeatable reads by either transaction.

Repeatable Read Isolation Level

Step Transaction 1 (RR Level) Transaction 2 (any level)

1 SELECT F2 FROM ORDERS WHERE ID = 2; (result ‘a’; record 2 locked)

2 UPDATE ORDERS SET F2=’b’ WHERE ID=2; (exclusive lock on 2 not granted; wait)

3 SELECT F2 FROM ORDERS WHERE ID= 2;

(result ‘a’)

4 COMMIT; (release S lock)

5 (x lock granted) (change ‘a’ to ‘b’) COMMIT;

Example 2 – Repeatable Read vs. Serializable

The following example demonstrates the phantom of two transactions when the first is executed in the Repeatable Read isolation level.

Step Transaction 1 (RR level) Transaction 2 (any level)

1 SELECT F1 FROM ORDERS WHERE F1=4;(result records 2,7 locked)

Repeatable Read Isolation Level

10-28 Using UniData SQL

Page 315: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Default Transaction Settings

Example 1 – Interactive UniData SQL

In the following example, UniData SQL performs an implicit commit after the first SELECT statement and after the subsequent UPDATE statement. This operation is the same regardless of whether you invoke UniData SQL from ECL or from the operating system because the default AUTO COMMIT setting for interactive UniData SQL is ON.

sql> SET DISPLAY TPMESSAGE ON;sql> SELECT * FROM ORDERS WHERE ID='801';Transaction started.Page 1 Order Order Order Client Number Date Time Number Product Nu Color Qty Price---------- ---------- ------- ---------- ---------- ---------- ------ ---------- 801 09/28/1995 04:34PM 10018 11000 Gray 1 $1,799.001 records listed Transaction committed

sql> UPDATE ORDERS SET QTY='5' WHERE ID='801';Transaction started.1 record(s) updated.

Transaction committed.

Example 2 – Manual Control of Isolation Level

The following example illustrates several points:

2 INSERT INTO ORDERS VALUES (4,4,’b’)

3 COMMIT;

4 SELECT F1 FROM ORDERS WHERE F1= ‘4’ (result records 2,4,7)

Step Transaction 1 (RR level) Transaction 2 (any level)

Repeatable Read Isolation Level (continued)

10-29

Page 316: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

You can override the default AUTO COMMIT option default (ON). In this example, AUTO COMMIT is OFF for all subsequent UniData SQL trans-actions until the end of the UniData SQL session or until another AUTO COMMIT command executes.With AUTO COMMIT OFF, you are in full control of each transaction’s isolation level and its termination. For example, with AUTO COMMIT ON, you have no reason to set isolation level, because each statement commits immediately. On the other hand, with AUTO COMMIT OFF, you can set isolation level, as is done in this example. Here, the user sets the isolation level to repeatable read, ensuring that no other user modifies the record being read.

After you turn AUTO COMMIT OFF, you must execute the COMMIT command to terminate the transaction.

:SQLsql> SET DISPLAY TPMESSAGE ON;sql> AUTO COMMIT OFF;sql> SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;sql> SELECT * FROM ORDERS WHERE ID='970';Transaction started.Page 1 Order Order Order Client Number Date Time Number Product Nu Color Qty Price---------- ---------- ------- ---------- ---------- ---------- ------ ---------- 970 01/15/1996 10:00AM 9988 13003 Gray 5 $250.001 records listed sql> UPDATE ORDERS SET QTY='10'WHERE ID='970';1 record(s) updated.sql> COMMIT; Transaction committed. sql> QUIT:

10-30 Using UniData SQL

Page 317: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Example 3 – Quitting UniData SQL with AUTO COMMIT OFF

This example illustrates quitting from UniData SQL without explicitly terminating a transaction while AUTO COMMIT option is OFF. UniData SQL performs an implicit commit before exiting. The fact that an implicit commit is performed on quit when the AUTO COMMIT option is ON is a trivial consequence of the rule that every statement is immediately committed.

%sql> AUTO COMMIT OFF; sql> SELECT * FROM ORDERS; Page 1 Order Order Order Client Number Date Time Number Product Nu Color Qty Price ---------- ---------- ------- ---------- ---------- ---------- ------ ---------- 912 01/13/1996 12:30PM 9984 53000 N/A 6 $129.95 801 09/28/1995 04:34PM 10018 11000 Gray 1 $1,799.00 941 01/14/1996 03:00PM 10009 50000 Gray 10 $1,399.99 . . . sql> DELETE FROM ORDERS WHERE ID='970'; 1 record(s) deleted or updated. Transaction committed. sql> QUIT:

Example 4 – Immediately Commiting a Transaction

When a UniData SQL statement is executed from the ECL prompt or from a paragraph, it is always immediately committed. In this example, two UniData SQL statements are executed and immediately committed:

:SQL SELECT * FROM ORDERS; Page 1 Order Order Order Client Number Date Time Number Product Nu Color Qty Price ---------- ---------- ------- ---------- ---------- ---------- ------ ---------- 912 01/13/1996 12:30PM 9984 53000 N/A 6 $129.95 801 09/28/1995 04:34PM 10018 11000 Gray 1

10-31

Page 318: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

$1,799.00 . . . :SQL UPDATE ORDERS SET QTY='1' WHERE ID='970'; 1 record(s) updated.

10-32 Using UniData SQL

Page 319: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Other UniData SQL TP ConsiderationsThis section outlines various parts of the UniData system impacted by UniData SQL TP. These areas are:

System AdministrationPerformanceInteraction of UniData SQL with Other Transactional Environments

System Administration

UniData SQL TP and the System Buffer

UniData SQL TP is the default behavior The only way to disable UniData SQL TP is by turning off the system buffer. You can do this within the udtconfig file located in /usr/ud72/include by changing the SB_FLAG parameter.

The default parameter is:

SB_FLAG=1

You can turn the system buffer off by making the following change:

SB_FLAG=0

Note: By turning off the system buffer, you also disable UniBasic TP and RFS, as well as UniData SQL TP. Check to make sure that this functionality is not used by your application before turning it off.

Setting the Default Isolation LevelAn environment variable specifies the default isolation level for this installation (the default is READ COMMITTED if this variable is not specified).

DEFAULT_ISO_LEVEL

10-33

Page 320: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Setting Maximum Number of Locks

Another environment variable specifies the maximum number of record locks allowed per file at a given time. This environment variable is:

MAX_RECORD_LOCKS

You can set this environment variable in the .login or .profile scripts for each user, as appropriate for your environment.

When the number of record locks on a specific file exceeds the defined value, UniData SQL attempts a lock escalation by converting record locks to a single file lock.

PerformanceSince UniData SQL TP uses existing UniData TP facilities, the performance of UniData SQL TP largely depends on the underlying facilities. However, record locking, which is not enforced by UniBasic, may have an adverse affect on perfor-mance. To reduce the number of lock requests, IBM recommends using Read Committed as the default isolation level, as opposed to ANSI’92 SQL–stipulated Serializable. UniData SQL also supports a LOCK TABLE command, giving applica-tions a certain degree of control to reduce system-enforced record locks. UniData also has a lock escalation scheme — when a large number of record locks are set, they are replaced by a single file lock.

Avoiding System DeadlocksIn a deadlock, two users hold locks and request the lock the other holds; both would wait forever unless one is aborted. When UniData detects a deadlock, the transaction whose request causes the deadlock is terminated and automatically rolled back.

10-34 Using UniData SQL

Page 321: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The example below demonstrates a deadlock resulting when transaction1 waits for Transaction2 to release the lock on record 2, while Transaction 2 waits for transaction1 to release the lock on record1.

Deadlock Example

Step Transaction 1 Transaction 2

1 lock record1 update record1

2 lock record2 update record2

3 lock record2

4 lock record1

Interaction of UniData SQL with Other Transactional EnvironmentsAlthough nested transactions are not supported in UniData and UniData SQL trans-action processing, a single transaction can span more than one execution environment. ANSI’92 SQL standards dictate that a transaction started in a particular environment must terminate in the same environment. The following explains how this rule is applied to UniData transaction environments.

UniBasic Subroutines Executed from UniData SQL

The following rules apply to transactions executed from UniData SQL:

If a UniBasic subroutine is executed from within UniData SQL while a transaction is active (such as a SUBR in a virtual attribute definition), all rules that apply to active transactions apply to the execution of the UniBasic subroutine. For example, the UniBasic TRANSACTION START command is not allowed, and no transaction terminating commands, such as TRANS-ACTION COMMIT or TRANSACTION ABORT, are allowed within the subroutine. Locking within UniBasic subroutines operate the same way regardless of the environment the subroutine is called from: records are not automatically locked on a read, regardless of the isolation level specified in UniData SQL.

10-35

Page 322: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The outcome of the execution of a subroutine is determined by the outcome of the execution of the encompassing UniData SQL transaction. That is, if the encompassing UniData SQL transaction terminates with COMMIT, the updates made by the subroutine are committed; if the encompassing UniData SQL transaction terminates with rollback, any updates made in the subroutine are aborted as well.If a UniBasic subroutine is aborted due to a fatal system error or a deadlock, the encompassing UniData SQL transaction is rolled back as well. UniData SQL transactions are always rolled back if any statement fails.If a UniBasic subroutine is executed with no UniData SQL transaction active, the subroutine controls the transactional environment. An example of this situation is when a CREATE.INDEX command is executed to build a virtual field index that invokes a UniBasic subroutine that contains TRANSACTION START and/or TRANSACTION COMMIT/ABORT. This execution may invoke hundreds, even thousands, of transactions, each subroutine execution being one of them.Because a UniData SQL environment cannot be reentered recursively, a UniBasic subroutine executed from UniData SQL cannot contain EXECUTESQL or EXECUTE statements that execute UniData SQL statements.

UniData SQL Executed in UniBasic

EXECUTE “SQL” and EXECUTESQL

If UniData encounters an EXECUTE “SQL ...;” or EXECUTESQL statement while no UniBasic transaction is active, the following two possibilities exist:

If this UniData SQL statement is not a transaction-initiating command, no transactional semantics apply. If this UniData SQL statement is one of the transaction-initiating commands, a transaction is initiated and committed immediately.

Within a UniBasic program in which a transaction is active, EXECUTE “SQL ...;” or EXECUTESQL statements:

Do not initiate new transactions, even if they are transaction-initiating statements.

10-36 Using UniData SQL

Page 323: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Transaction-terminating statements (COMMIT or ABORT) and UniData SQL statements not allowed within a transaction result in an error.The active UniBasic transaction does not terminate when the processing of the EXECUTE or EXECUTESQL statement completes unless a fatal system error is encountered. Therefore, many UniData SQL statements may be executed within the same UniBasic transaction. The outcome of the encompassing UniBasic transaction determines the outcome of all UniData SQL statements within this transaction.The UniBasic STATUS function returns a value greater than zero to indicate failure of a UniData SQL statement.

A UniBasic EXECUTE statement can invoke the execution of a paragraph that can contain one or more UniData SQL statements.

If a paragraph containing UniData SQL statements is executed while no UniBasic transaction is active, the following rules apply:

Transactional semantics do not apply to UniData SQL statements that do not initiate transactions.Each transaction-initiating UniData SQL statement within this paragraph is immediately committed.

If a paragraph containing UniData SQL statements is executed while a UniBasic transaction is active, the following rules apply:

No new transactions are initiated by the UniData SQL statements. No transaction-terminating statements are allowed in the paragraph.UniData SQL statements disallowed in transactions are illegal in the paragraph. The encompassing UniBasic transaction remains active when UniData SQL statements completes unless a fatal system error is encountered. Therefore, multiple UniData SQL statements may be executed within the paragraph. The outcome of the surrounding UniBasic transaction determines the outcome of all of the UniData SQL statements within this paragraph.

10-37

Page 324: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

UniData SQL TP and READNEXTTUPLE

The UniBasic READNEXTTUPLE statement does not interface with the UniData SQL environment. In order to step through a result set using a READNEXTTUPLE statement, the result set must have already been placed in a temporary file using the TO option of the SELECT statement which had been executed using the EXECUTESQL statement.

UniData SQL and ODBC Transactional Semantics

ODBC transactional semantics are similar to UniData SQL transactional semantics with the following two exceptions:

The ODBC transaction access modes stay in effect until changed by a subse-quent ODBC SetConnectOption command or until the client session ends.ODBC isolation level also remains in effect until changed by another ODBC SetConnectOption command or until the client session ends.

Five isolation levels exist in ODBC: four of them correspond to the four ANSI’92 SQL isolation levels, and the fifth, SQL_TXN_VERSIONING, is designed for nonlocking protocols such as Oracle’s Read Consistency. This fifth ODBC isolation level is not supported in UniData SQL.

10-38 Using UniData SQL

Page 325: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Tips on Transactions

Optimizing PerformanceThe following tips make for better transaction processing and improve system performance:

Do not use a higher level of isolation than necessary. Higher-level isolations (Repeatable Read and Serializable) tend to lock large numbers of records or entire files.To reduce record lock contention, avoid creating “hot spots,” where a great deal of file access is concentrated. For example, a file of summary records that must be updated by every transaction may contribute to the creation of a hot spot if the file modulo is small; resize the file so that records are evenly distributed to ease contention on the summary records. A file that constantly gets extended because of new record additions may also create a hot spot.Do not run long transactions during heavy system loads. The longer the transaction, the longer locks are held; this blocks other transactions and results in increased incidence of deadlocks.Avoid transactions that involve user interaction, such as keyboard input.Although you can’t completely avoid deadlocks, if you follow certain principles in all applications, you can reduce the occurrence of deadlocks:Always request locks in the same order. If multiple files are to be modified by different applications, always update them in a fixed, predetermined order.

Limitations

TP Semantics and RFS

UniData SQL TP semantics are enforced only on RFS files, except for repeatable read and serializable isolation, which is enforced for non-RFS files.

Warning: If users are mixing RFS and non-RFS files in a single transaction, full ACID properties are not guaranteed.

10-39

Page 326: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Statements Excluded from Transaction Processing

Currently, UniData SQL transaction processing does not support SQL DDL state-ments. Specifically, the following statements cannot appear in a transaction:

CREATE [TABLE | VIEW | SUBTABLE | INDEX]DROP [TABLE | VIEW | SUBTABLE | INDEX]ALTER TABLE

Additionally, the following statements are prohibited within transactions:

GRANTREVOKESET TRANSACTION AUTO COMMIT! (shell escape symbol)

When such statements are encountered within a transaction, one of the following two actions takes place:

If the transaction is initiated from UniData SQL, the transaction is aborted.If the transaction is initiated from another environment (such as UniBasic), an error condition is returned and control is returned to the encompassing environment.

UniData SQL TP does not support nested transactions, either directly or indirectly (such as through a subroutine call).

10-40 Using UniData SQL

Page 327: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

11Chapter

UniData SQL and 1NF Mapping

Terminology . . . . . . . . . . . . . . . . . . . . 11-31NF Mapping . . . . . . . . . . . . . . . . . . . . 11-5 NF2 Data Model vs. 1NF Data Model . . . . . . . . . . . 11-5 What Is a 1NF Mapping View? . . . . . . . . . . . . . 11-5Subtables . . . . . . . . . . . . . . . . . . . . . 11-7 Rules for Updating Subtables . . . . . . . . . . . . . 11-7 Primary and Foreign Keys . . . . . . . . . . . . . . 11-8 Creating Subtables . . . . . . . . . . . . . . . . . 11-10 Creating Keys . . . . . . . . . . . . . . . . . . 11-12Examples of Read-Only Mapping . . . . . . . . . . . . . 11-15 Creating a View for Singlevalued Attributes . . . . . . . . . 11-16 Creating a View for the Multivalued Attribute . . . . . . . . 11-16 Creating a View for Multivalued and Multi-Subvalued Attributes . . 11-17Examples of Updatable Mapping. . . . . . . . . . . . . . 11-19 Create a Nested Level 0 Subtable . . . . . . . . . . . . 11-19 Create a Nested Level 1 Subtable . . . . . . . . . . . . 11-20 Create a Nested Level 2 Subtable . . . . . . . . . . . . 11-21Updatable Mapping Commands . . . . . . . . . . . . . . 11-23 CREATE SUBTABLE . . . . . . . . . . . . . . . 11-23 NLn_KEY . . . . . . . . . . . . . . . . . . . 11-28 DROP SUBTABLE . . . . . . . . . . . . . . . . 11-30

Page 328: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

This chapter introduces updatable mapping.

Note: Once you upgrade an account from a release earlier than 4.0, you will not be able to access the account with the earlier version of UniData SQL. IBM recom-mends that you perform a backup of your system before upgrading.

This chapter includes the following sections:

Terminology1NF MappingSubtablesExamples of Read-Only MappingExamples of Updatable MappingUpdatable Mapping Commands

11-2 Using UniData SQL

Page 329: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

TerminologyIt is important to familiarize yourself with the following terms to help you understand the changes to UniData SQL:

SQL – Structured Query Language. An industry standard for data management, data definition, data manipulation, access protections, and transaction control. UniData SQL – The UniData implementation of SQL. UniData SQL handles tables both in the NF2 (nested relational) structure and the 1NF model.Database – In general terms, a database is a collection of data that:

Conforms to a common structure with a format defined by the metadata.Is operated on (stored, modified, retrieved) by a database management system.Can be concurrently accessed by multiple users under the protection of data sharing and concurrency rules provided by the database management system.

ODBC – Microsoft’s Open Database Connectivity (ODBC) interface that enables a variety of applications to access data in databases using SQL. The ODBC components consist of an application, driver manager, driver, and a data source.1NF Database – A database that conforms to the first normal form type of data storage. Most databases are 1NF databases; as such, they have only singlevalued attributes. DB2 is a 1NF database.NF2 Database – A database that conforms to the nested relational model. This model enables you to store data in a variety of attributes: singlevalued, multivalued, and multi-subvalued. This model avoids data redundancy. UniData is a NF2 database.1NF Mapping – A mechanism that enables data stored in UniData relational tables to be viewed (read-only mapping) or updated (updatable mapping) by applications that operate on 1NF data, with the assumption that the data conforms to the 1NF model in which all attribute values are atomic.Base Table – The place where the data resides. It includes the VOC pointer to a dictionary and a physical file.

11-3

Page 330: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Record ID – Commonly known in UniData terms as the @ID. This ID has the location of 0 LOC(0) and is the primary key of a table. Subtable – This new type of UniData SQL view is designed for updatable 1NF mapping from an NF2 database. The subtable translates data stored in singlevalued, multivalued, or multi-subvalued formats into three distinct nested levels: 0, 1, and 2.Nested Levels – In a UniData SQL table, singlevalued attributes are not nested (they correspond to the top level of nesting). Associations that combine related multivalued and multisubvalued attributes are nested subrelations. Within each association, multivalued and multi-subvalued attributes correspond to the first and second level of nesting, respectively. A subtable in UniData SQL contains related attributes that belong to the same nesting level.

A subtable containing the singlevalued attributes of a UniData SQL table is a nested level 0 subtable.A subtable containing either a unassociated multivalued attribute or the multivalued attributes of one association is a nested level 1 subtable. A subtable containing either a unassociated multisubvalued attribute, or the multi-subvalued attributes of one association, is the nested level 2 subtable.

Schema – In SQL, a collection of database objects, such as tables, views, indexes, and so forth. sharing the same namespace. Each UniData account is a separate namespace and therefore fits the definition of a schema. In UniData, the term schema means the metadata that describes the UniData data. A schema, in UniData terms, is a set of catalog tables that contain names of 1NF views and subtables that map UniData nested data into 1NF format A UniData schema also contains the names and data types of its attributes.Schema Generation – This process translates UniData dictionary infor-mation into a standard SQL form to store it in the database schema and creates UniData SQL views and subtables that serve as the 1NF mapping mechanism.Schema Generator – A set of tools that guide a user through the translation process and acts on 1NF views and their descriptions to complete the translation.

11-4 Using UniData SQL

Page 331: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

1NF Mapping1NF mapping enables ODBC-compliant applications to access data stored in UniData (1NF) tables. The following definitions will help you understand the differ-ences between the 1NF format and the UniData Nested Relational (NF2) data structure.

NF2 Data Model vs. 1NF Data ModelBefore you perform updatable mapping, you must understand the current state of your data. Is it in 1NF or NF2 format?

NF2 Data – Data that conforms to the nested relational model. This model enables you to store data in a variety of attributes: singlevalued, multi-valued, and multi-subvalued. This model avoids data redundancy. UniData is a NF2 database.1NF Data – Data that conforms to the first normal form type of data storage. Most databases are 1NF databases; they have only singlevalued attributes. DB2 is a 1NF database.

Because UniData stores data in NF2 format, that data must be unnested before being passed to a 1NF application. If the application requires only read access, you can use 1NF mapping views to unnest it. If the application updates UniData tables, you must unnest the data by creating subtables.

What Is a 1NF Mapping View?A 1NF mapping view in UniData SQL presents data in such a way that it can be viewed by using a an SQL SELECT statement.

11-5

Page 332: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Creating 1NF Mapping Views

Singlevalued Attribute Views – Any singlevalued attribute can be presented to 1NF applications without any mapping performed on it. All you need to do to access data in this form, is to include the attribute in a view. Because the record ID attribute uniquely identifies each record in a UniData table, you must also include this attribute to identify the nested relational record the view record comes from. The following statement creates a 1NF mapping view:

sql> CREATE VIEW ORDER_INFO sql> AS SELECT ID, CLIENT_NO, ORD_DATE, ORD_TIMEsql> FROM ORDERS; View ORDER_INFO created.

Multivalued and Multi-Subvalued Attribute Views – You must create a separate view for each association, for each unassociated multivalued, and for each unassociated multi-subvalued attribute. The following statements create 1NF mapping views for these types of attributes.

This first example creates a view that unnests attributes in the association LINE_ITEMS:

sql> CREATE VIEW ORDER_LINE_ITEMSsql> AS SELECT ID, PRODUCT_NO, COLOR, QTY, PRICEsql> FROM ORDERS sql> UNNEST PRODUCT_NO, COLOR, QTY, PRICE; View ORDER_LINE_ITEMS created

This example creates a view that unnests the unassociated multivalued attribute ADDRESS:

sql> CREATE VIEW ORDER_ADDRESSsql> AS SELECT ID, ADDRESSsql> FROM ORDERS sql> UNNEST ADDRESS; View ORDER_ADDRESS created

11-6 Using UniData SQL

Page 333: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

SubtablesA subtable is a UniData SQL view that presents data stored in a UniData SQL table in such a way that it can be viewed and updated using 1NF SQL data manipulation commands. As a result, ODBC-compliant and other 1NF applications can select, insert, update, and delete data stored in UniData nested relational tables.

In a UniData SQL table, singlevalued attributes are not nested (they correspond to the 0th level of nesting). Associations that combine related multivalued and multi-subvalued attributes can be viewed as nested subrelations. Within each association, multivalued and multi-subvalued attributes correspond to the 1st and 2nd level of nesting, respectively. A subtable in UniData SQL contains related attributes that belong to the same nesting level. The nested levels are referred to as NL0, NL1, and NL2.

NL0 subtable represents singlevalued attributes. NL1 subtable represents associated multivalued attributes or unassociated multivalued attributes. All multivalued attributes must be in the same association.NL2 subtable represents associated multi-subvalued attributes or unasso-ciated multi-subvalued attributes.

These subtables are linked through primary and foreign keys.

Rules for Updating SubtablesThe following general rules apply to the update of a subtable:

If you need to insert a record with a new record ID, you must first insert it into the nested level 0 subtable. This will result in an automatic insertion of a row with this ID into each subtable defined on the specified table. These new rows will have the specified value in their record ID attribute while all other attributes will receive no values (remain empty). If you need to delete a record ID, you must delete it from a nested level 0 subtable. This will result in an automatic deletion of all the rows with this ID from all subtables defined on the specified table.

11-7

Page 334: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Primary and Foreign KeysTo preserve the integrity of NF2 data, 1NF applications that update these data must understand the real data relationships in NF2 tables. UniData uses standard ANSI SQL and ODBC concepts to describe such relationships to 1NF applications.

The NL0 subtable defines the primary key. The purpose of a primary key is to specify one or more attributes whose data values are unique among all data values of the same attributes in that subtable. UniData SQL does not allow a record to be added to a table with a duplicate key value.

The primary key of the NL0 subtable becomes the foreign key in the NL1 subtable. So that UniData SQL can locate the primary key, you name the NL0 subtable in the REFERENCES clause of the CREATE SUBTABLE statement that creates the NL1 subtable.

To create an NL2 subtable, you use the primary key of the NL1 subtable as the NL2 table’s foreign key, and list the NL1 subtable name in the REFERENCES clause. No primary key is required when you create an NL2 subtable, because no lower-level subtable will reference this (NL2) subtable; however, you may want to define a primary key for NL2 subtables to ensure the uniqueness of the data. The primary and foreign keys accomplish the same data relationships in subtables as associations do in UniData SQL base tables.

The following table summarizes the number and value type of attributes required to create primary and foreign keys in subtables.

Primary and Foreign Keys for Subtables

Key Subtable

Type NL0 NL1 NL2

Primary 1 S 1 S, 1 MV 1 S, 1 MV, 1 MS

Foreign n/a 1 S 1 S, 1 MV

Note: If you create an NL1 subtable without a primary key, and then want to create an NL2 key, you have to drop and recreate an NL1 subtable that names a primary key. Then you can create an NL2 key that references the NL1 subtable.

11-8 Using UniData SQL

Page 335: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Warning: If two subtables map to the same association, but specify different primary keys, UniData SQL has no way of ensuring that primary keys are unique. This could result in duplicate values being added through UPDATE or INSERT, or by more than one row being updated by UPDATE.

Types of Primary and Foreign Keys

Keys can be unique or generated. The concept of unique and generated keys applies to both primary and foreign keys, because the primary key of one subtable is the foreign key of another.

Unique Keys

In a unique key, the uniqueness of the key value depends on the data itself. In this case, actual attribute names are used in the PRIMARY KEY or FOREIGN KEY clauses.

Generated Keys

When you specify generated keys, UniData SQL assigns a number to be part of each key value, so that they key value is unique even when the data itself is not. In this case, you use NL1_KEY or NL2_KEY keyword in the SELECT statement, rename the selected values, and use these new names in the PRIMARY KEY or FOREIGN KEY clause.

In addition to serving as a unique record identifier, a generated key provides infor-mation about the order in which rows are stored. 1NF databases assume that the order of rows in a table is not important: every row is identified with the values of its attri-butes, not the order in which they are stored. In a UniData table though, the order in which values of a multivalued or a multi-subvalued attribute are stored within a record may be important. It corresponds to the concept of a list structure which is not supported by 1NF databases. Generated keys, on the other hand, provide support for the list structures that exist in UniData tables.

Points to Remember about Subtables

Remember the following when creating and using subtables:

11-9

Page 336: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Provide a primary key definition in a level 0 subtable. Provide a primary key definition in a level 1 subtable if you will later need to create a nested level 2 subtable referencing it. A record ID value is required in all insert statements. It must be an existing value when inserting into a level 1 or 2 subtable. To unambiguously identify rows of a subtable for update or delete, you must uniquely identify each row by its primary key. If a primary key is defined using the unique key technique, then:

UniData SQL ensures its uniqueness on insert and update.Inserted rows are appended after the last existing row.

If a primary key is defined using the generated key technique and you want to insert a row in a particular order, then specify the position using the generated key value; you can also leave the generated key value empty, and UniData SQL will append it to the end of the list. All attributes of a nested level 1 or 2 subtable can be updated except for the record ID and the generated key attribute.If you delete the last row of a nested level 1 or 2 subtable with the specified record ID, the row does not disappear, but all the attribute values (except record ID) become empty.

Creating Subtables

Nested Level 0 Subtables

The record ID attribute uniquely identifies each record in a UniData table. By including this attribute in a nested level 0 subtable, each row of this subtable is uniquely identified as well. Using standard SQL terminology, the record ID attribute is the primary key of a nested level 0 subtable. Therefore, the definition of a nested level 0 subtable must include the primary key specification.

For example:

sql> CREATE SUBTABLE ORDER_NL0 sql> AS SELECT ID, CLIENT_NO, ORD_DATE, ORD_TIMEsql> FROM ORDERSsql> PRIMARY KEY ID;

11-10 Using UniData SQL

Page 337: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Nested Level 1 Subtables

For a nested level 1 subtable, the record ID values do not uniquely identify each row since these values are replicated due to unnesting of the multivalued attributes. On the other hand, by including the record ID attribute in a nested level 1 subtable, it becomes possible to identify which NF2 record each row of the nested level 1 subtable belongs to. Therefore, the record ID attribute is always included in a nested level 1 subtable. Every value of this record ID attribute in the nested level 1 subtable matches the corresponding record ID value of the nested level 0 subtable. Such a subtable relationship can be described using the standard SQL concept of a foreign key. Therefore, the definition of a nested level 1 subtable includes the foreign key specification.

For example:

sql> CREATE SUBTABLE ORDER_NL1sql> AS SELECT ID, PRODUCT_NO, PROD_NAMEsql> FROM ORDERSsql> UNNEST PRODUCT_NO, PROD_NAMEsql> PRIMARY KEY ID, PRODUCT_NOsql> FOREIGN KEY ID REFERENCES ORDER_NL0;

The implied referential constraint of this foreign key is DELETE CASCADE. The corresponding nested level 0 subtable name follows the keyword REFERENCES. The following referential integrity rules apply:

By the foreign key definition, any row inserted into a nested level 1 subtable must have its record ID value matching one of the existing record ID values in the corresponding nested level 0 subtable. By the rule of delete cascade, when a row is deleted from a nested level 0 subtable, all the rows of the corresponding nested level 1 subtable with the matching record ID are automatically deleted.

11-11

Page 338: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Nested Level 2 Subtables

For a nested level 2 subtable, the primary key values of the corresponding nested level 1 subtable do not uniquely identify each row because these values are replicated when the multisubvalued attributes are unnested. By including the primary key attri-butes of the nested level 1 subtable in a nested level 2 subtable, we can identify the multivalued attribute values within the NF2 record that correspond to each row of the nested level 2 subtable. Therefore, the primary key attributes of the corresponding nested level 1 subtable are always included in a nested level 2 subtable. We specify the relationship between these attributes of the nested level 1 subtable and the subor-dinate nested level 2 subtable using the primary and foreign key concepts similar to the primary key/foreign key relationship between the primary key of the nested level 0 subtable and the foreign key of its subordinate nested level 1 subtable.

sql>CREATE SUBTABLE ORDER_NL2sql>AS SELECT ID, PRODUCT_NO, COLOR, QTY, PRICEsql>FROM ORDERSsql>UNNEST PRODUCT_NO, COLOR, QTY, PRICEsql>FOREIGN KEY ID, PRODUCT_NO REFERENCES ORDER_NL1;

Note: A nested level 2 subtable may or may not need to have its own primary key. In order to unambiguously identify rows of such a subtable for update or delete, it is necessary to identify its primary key. Both the unique key and the generated key techniques are available for nested level 2 subtables.

The following is an example of a generated key NL2 subtable:

sql>CREATE SUBTABLE ORDER_GEN2(ID, PRODUCT_NO, DETAIL, COLOR, QTY, PRICE)sql>AS SELECT ID, PRODUCT_NO, NL2_KEY(COLOR, QTY, PRICE), COLOR, QTY, PRICE sql>FROM ORDERSsql>UNNEST PRODUCT_NO, COLOR, QTY, PRICEsql>PRIMARY KEY ID, PRODUCT_NO, DETAILsql>FOREIGN KEY ID, PRODUCT_NO REFERENCES ORDER_NL1;

Creating KeysWhile the values of generated key attributes can be manipulated with standard SQL insert and update commands, the semantics of these operations on generated key attributes are slightly different from those on other attributes.

11-12 Using UniData SQL

Page 339: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

When inserting, you can omit the value of a generated key, in which case the row will be stored after the last existing row. If you specify the value of a generated key that is within the range of existing key values, the new row is stored at the position specified by this value. Other rows are “shifted down” to make space for the new row. If the specified value of a generated key is larger than the largest existing value, the row is appended. If you want to append to the end of a list, but do not know what the largest value of a generated key is, specify 0 to tell UniData SQL to store the new row at the end of the list.

Unique Keys

Specifying the unique key technique for a nested level 1 subtable consists of identi-fying a single multivalued attribute in the specified association whose values are unique (distinct) within each NF2 record. Then, together with the record ID, this attribute comprises the primary key of this nested level 1 subtable, as demonstrated in the following example (PRIMARY KEY ID, PRODUCT_NO).

sql> CREATE SUBTABLE ORDER_NL1sql> AS SELECT ID, PRODUCT_NO, PROD_NAMEsql> FROM ORDERSsql> UNNEST PRODUCT_NO, PROD_NAMEsql> PRIMARY KEY ID, PRODUCT_NOsql> FOREIGN KEY ID REFERENCES ORDER_NL0;

In this subtable, PRODUCT_NO has unique values within each NF2 record; therefore, this attribute can serve as the unique key. When no such a single multi-valued attribute exists that can serve as a unique key, the generated key technique must be used.

Generated KeysA generated key in a nested level 1 subtable is a calculated attribute whose values represent the position number of each row of this subtable. The numbering of rows starts with 1 and is incremented by 1 for each next row. The generated key attribute is defined with the NL1_KEY function within the CREATE SUBTABLE statement. Together with the record ID, this attribute comprises the primary key of this nested level 1 subtable.

sql>CREATE SUBTABLE ORDER_GEN(ID, PROD_ID, PRODUCT_NO)sql>AS SELECT ID, NL1_KEY(PRODUCT_NO), PRODUCT_NOsql>FROM ORDERSsql>UNNEST PRODUCT_NOsql>PRIMARY KEY ID, PROD_IDsql>FOREIGN KEY ID REFERENCES ORDER_NL0;

11-13

Page 340: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Examples of Read-Only MappingThis section uses the ORDERS table to demonstrate read-only mapping. Notice that associated multivalued attributes and multi-subvalued attributes are represented in this table:

LISTDICT ORDERS; Page 1@ID TYP LOC CONV NAME FORMAT SM ASSOC--------------- --- ------------- ---- --------------- ------ -- ----------@ID D 0 ORDERS 10R SID D 0 Order Number 10R SORD_DATE D 1 D4/ Order Date 10R SORD_TIME D 2 MTH Order Time 7R SCLIENT_NO D 3 Client Number 10R SPRODUCT_NO D 4 Product Number 10R MV LINE_ITEMSCOLOR D 5 Color 10T MS LINE_ITEMSQTY D 6 Qty 6R MS LINE_ITEMSPRICE D 7 MD2, Price 10R MS LINE_ITEMS...LINE_ITEMS PH PRODUCT_NO PR...28 records listed

11-14 Using UniData SQL

Page 341: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Creating a View for Singlevalued AttributesThis first view combines the record ID and all selected singlevalued attributes in a view:

CREATE VIEW ORDERS_VIEW AS SELECT ID, ORD_DATE, ORD_TIME, CLIENT_NO FROM ORDERS;

View ORDERS_VIEW created.

SELECT * FROM ORDERS_VIEW; Page 1 Order Order Order Client Number Date Time Number---------- ---------- ------- ---------- 912 10/24/2000 12:30PM 9984 801 10/13/2003 04:34PM 10018 941 10/24/2001 03:00PM 10009 805 10/14/2000 11:11AM 9987 830 10/25/2001 03:09PM 10013 863 10/20/2000 09:45AM 10006 834 10/25/2001 03:27PM 10004 861 10/20/2009 12:51PM 10020 890 10/25/2000 07:00PM 10009 914 10/24/2000 02:00PM 9975...Page 11 Order Order Order Client Number Date Time Number---------- ---------- ------- ---------- 922 10/24/2000 09:39AM 10021 811 10/13/2007 10:10PM 10023192 records listed

Creating a View for the Multivalued AttributeThis example creates and uses a view for the table’s multivalued attribute. It includes:

IDMultivalued attribute

CREATE VIEW ORDERS_MV1_VIEWAS SELECT ID, PRODUCT_NOFROM ORDERSUNNEST PRODUCT_NOWHERE ID BETWEEN 810 AND 815;

View ORDERS_MV1_VIEW created.

11-15

Page 342: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

SELECT * FROM ORDERS_MV1_VIEW;Page 1 Order Number Product Nu---------- ---------- 813 30000 813 34000 813 11020 810 40008 810 40013 810 13005 812 10001 812 14001 812 12002 812 33000 812 10008 811 13001 811 13002 811 1500114 records listed

Creating a View for Multivalued and Multi-Subvalued AttributesThis view selects all multivalued and multi-subvalued attributes. All of these attri-butes belong to the same association. This view contains:

Record ID

11-16 Using UniData SQL

Page 343: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Unnested multivalued and multi-subvalued attributesCREATE VIEW ORDERS_SMV_VIEWAS SELECT ID, PRODUCT_NO, COLOR, QTY, PRICEFROM ORDERSUNNEST PRODUCT_NO, COLOR, QTY, PRICEWHERE ID BETWEEN 810 AND 815;

View ORDERS_SMV_VIEW created. SELECT * FROM ORDERS_SMV_VIEW;Page 1 Order Number Product Nu Color Qty Price---------- ---------- ---------- ------ ---------- 813 30000 Black 1 $99.96 813 34000 Oak grain 1 $199.87 813 11020 Black 1 $69.94 810 40008 White 2 $69.92 810 40013 Silver 1 $47.72 810 13005 Gray 2 $500.00 812 10001 Gray 1 $1,995.00 812 14001 Black 3 $49.95 812 12002 N/A 1 $1,999.00 812 33000 Cherry 1 $599.96 812 10008 Black 1 $400.00 811 13001 N/A 6 $94.00 811 13002 N/A 1 $150.00 811 15001 N/A 6 $119.0014 records listed

11-17

Page 344: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Examples of Updatable MappingThis section demonstrates creating and using subtables through which you can update the base table. The three levels (NL0, NL1, and NL2) are linked by primary and foreign keys. They represent the three levels of nested data contained in UniData NF2 base tables:

NL0 – Represents singlevalued attributes.NL1 – Represents multivalued attributes.NL2 – Represents multi-subvalued attributes.

Note: You cannot create a single subtable that contains attributes from different associations or that combine more than one value type — such as combining singl-evalued and multi-vlaued attributes. If you do, UniData returns an error message indicating the type of error, such as: a subtable cannot contain both ‘MV’ and ‘MS’ attributes. (Note that the foreign key, which is the primary key of the subtable or table at the next-higher level, is the only exception to this rule.)

Create a Nested Level 0 SubtableThis first subtable combines the Record ID and selected singlevalued attributes into a updatable subtable. It contains:

Record ID.Singlevalued attributes.

11-18 Using UniData SQL

Page 345: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Primary key to enable referencing by the NL1 subtable.CREATE SUBTABLE ORDER_NL0 AS SELECT ID, CLIENT_NO, ORD_DATE, ORD_TIMEFROM ORDERSPRIMARY KEY ID;

Subtable ORDER_NL0 created.

SELECT * FROM ORDER_NL0WHERE ID BETWEEN 810 AND 815;Page 1 Order Client Order Order Number Number Date Time---------- ---------- ---------- ------- 813 10024 10/10/2007 05:00PM 810 9975 10/10/2006 08:55AM 812 10008 10/11/2004 04:00PM 811 10023 10/13/2007 10:10PM4 records listed

Create a Nested Level 1 SubtableThis next subtable represents the base table’s multivalued attribute. It contains:

Record ID.Unnested multivalued attribute.Foreign key that references the NL0 subtable.

11-19

Page 346: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Primary key to enable referencing by the NL2 subtable.CREATE SUBTABLE ORDER_NL1 AS SELECT ID, PRODUCT_NO FROM ORDERS UNNEST PRODUCT_NO, PROD_NAME PRIMARY KEY ID, PRODUCT_NOFOREIGN KEY ID REFERENCES ORDER_NL0;

Subtable ORDER_NL1 created.

SELECT * FROM ORDER_NL1 WHERE ID BETWEEN 810 AND 815;Page 1 Order Number Product Nu Product Na---------- ---------- ---------- 813 30000 CD System 1 813 34000 Speaker 813 11020 TV 810 40008 Telephone 810 40013 Telephone 810 13005 Hard Drive 812 10001 Computer 812 14001 Memory 812 12002 Monitor 812 33000 CD System 3 812 10008 Printer 811 13001 Adapter 811 13002 Adapter 811 15001 Modem14 records listed

Create a Nested Level 2 SubtableThe final subtable represents the base table’s multi-subvalued attribute. It contains:

Record ID.Unnested multi-subvalued attributes.The primary key from the multivalued attributes subtable.Foreign key that references the NL1 subtable.

11-20 Using UniData SQL

Page 347: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

A unique key to uniquely identify rows to be updated or deleted.CREATE SUBTABLE ORDER_NL2 AS SELECT ID, PRODUCT_NO, COLOR, QTY, PRICEFROM ORDERS UNNEST PRODUCT_NO, COLOR, QTY, PRICEFOREIGN KEY ID, PRODUCT_NO REFERENCES ORDER_NL1;

Subtable ORDER_NL2 created.

SELECT * FROM ORDER_NL2 WHERE ID BETWEEN 810 AND 815;Page 1 Order Number Product Nu Color Qty Price---------- ---------- ---------- ------ ---------- 813 30000 Black 1 $99.96 813 34000 Oak grain 1 $199.87 813 11020 Black 1 $69.94 810 40008 White 2 $69.92 810 40013 Silver 1 $47.72 810 13005 Gray 2 $500.00 812 10001 Gray 1 $1,995.00 812 14001 Black 3 $49.95 812 12002 N/A 1 $1,999.00 812 33000 Cherry 1 $599.96 812 10008 Black 1 $400.00 811 13001 N/A 6 $94.00 811 13002 N/A 1 $150.00 811 15001 N/A 6 $119.0014 records listed

11-21

Page 348: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Updatable Mapping Commands

CREATE SUBTABLE

Syntax

CREATE SUBTABLE subtable_name [(attribute_subtable_name [,attribute_subtable_name]...)] AS SELECT query_spec [PRIMARY KEY attribute_name[,attribute_name]...] [FOREIGN KEY attribute_name[,attribute_name]... REFERENCES subtable_name]

Description

CREATE SUBTABLE creates a UniData SQL view that presents values from the base table in such a way that those values can be viewed and updated using 1NF ANSI-standard SQL Data Manipulation Language (DML) commands. This enables you to update data in UniData SQL base tables using desktop tools that access these subtables through UniData ODBC or UniOLEDB.

Note: UniData SQL updatable mapping does not duplicate, replicate, modify, normalize, or replace the nested relational data. Data values are stored only once — in native nested relational form. Subtables are simply views of the data in its native (NF2) form. Tools that generate ANSI-standard SQL DML commands manipulate data in the subtables as if it were stored in standard 1NF tables.

11-22 Using UniData SQL

Page 349: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Parameters

The following table describes each parameter of the syntax.

CREATE SUBTABLE Parameters

Parameter Description

subtable_name Specifies the name of the new subtable. Subtable names can contain alphabetic characters, numbers, or the underscore character. ODBC prohibits the use of other special characters.The following restrictions apply to subtable names:The first character of the name cannot be a number. The subtable name must be unique among tables, subtables, and views in the database. The maximum length of the table name is 30 characters.

attribute_subtable_name The name to be used for the attribute in this subtable. If you rename one attribute, you must list all attributes, even if you use the attribute name from the base table. You must rename attri-butes when a generated key is used.

AS SELECT query_spec Selects data to include in the subtable. query_spec is defined in the SELECT statement section of this manual.You must UNNEST nested attributes to create a subtable through which you can update the base table. The SELECT clause cannot contain more than 255 virtual attributes.query_spec cannot contain aggregation function or expressions (except for NL1_key or NL2_key).

PRIMARY KEY attribute_name

One or more attributes to use as the primary key for this subtable. If you rename an attribute (see attribute_subtable_name, above), you must use the new name here.

FOREIGN KEY attribute_name

One or more attributes to use as the foreign key for this subtable. The foreign key refers to the primary key of a subtable one nested level higher. If you rename an attribute (see renamed_attribute, above), you must use the new name here.

REFERENCES subtable_name

The corresponding subtable name, one nested level higher, that contains, as a primary key, the attribute_names listed in the FOREIGN KEY clause of this statement.

11-23

Page 350: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Examples

This series of examples demonstrates creating NL0, NL1, and NL2 subtables that are linked by primary and foreign keys. This first statement creates the NL0 subtable. Notice that this statement does not rename the attributes, but uses the attribute names from the CLIENTS table dictionary. The new subtable contains unique primary keys; no foreign key is allowed because this is the top (NL0) level subtable.

sql> CREATE SUBTABLE ORDER_NL0 sql> AS SELECT ID, CLIENT_NO, ORD_DATE, ORD_TIMEsql> FROM ORDERSsql> PRIMARY KEY ID;

Subtable ORDER_NL0 created.

And the following SELECT statement lists the contents of this new subtable:

sql> SELECT * FROM ORDER_NL0;Page 1 Order Client Order Order Number Number Date Time---------- ---------- ---------- ------- 912 9984 01/13/1996 12:30PM 801 10018 09/28/1995 04:34PM 941 10009 01/14/1996 03:00PM 805 9987 10/05/1995 11:11AM 830 10013 01/24/1996 03:09PM 970 9988 01/15/1996 10:00AM 863 10006 12/04/1995 09:45AM... 834 10004 01/24/1996 03:27PM 922 10021 01/13/1996 09:39AM 811 10023 10/02/1995 10:10PM193 records listed

This example creates the NL1 subtable. Notice that multivalued attributes are selected and unnested in the subtable.

Note: Because PROD_NAME is a virtual field, it cannot be included in an INSERT statement and its value cannot be updated with UPDATE.

sql> CREATE SUBTABLE ORDER_NL1sql> AS SELECT ID, PRODUCT_NO, PROD_NAMEsql> FROM ORDERSsql> UNNEST PRODUCT_NO, PROD_NAMEsql> PRIMARY KEY ID, PRODUCT_NOsql> FOREIGN KEY ID REFERENCES ORDER_NL0;

11-24 Using UniData SQL

Page 351: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The following SELECT statement displays the (unnested) multivalued table, ORDER_NL1:

sql> SELECT * FROM ORDER_NL1;Page 1 Order Number Product Nu Product Na---------- ---------- ---------- 912 53000 Printer Cartridge 801 11000 Computer 941 50000 Computer... 818 14001 Memory 818 14002 Memory 818 14003 Memory 818 13004 Hard Drive 818 13005 Hard Drive 818 13006 Hard Drive 818 54030 Hard Drive 818 54060 Hard Drive 818 54080 Disk Drive...Page 32 Order Number Product Nu Product Na---------- ---------- ---------- 811 13002 Adapter 811 15001 Modem487 records listed

The next example creates the NL2 subtable, which unnests the multi-subvalued attri-butes. Because EPRICE is a virtual field, it cannot be included in an INSERT statement and its value cannot be updated with UPDATE.

sql> CREATE SUBTABLE ORDER_NL2AS SELECT ID, PRODUCT_NO, COLOR, QTY, PRICE, EPRICE FROM ORDERSUNNEST PRODUCT_NO, COLOR, QTY, PRICEFOREIGN KEY ID, PRODUCT_NO REFERENCES ORDER_NL1;

Subtable ORDER_NL2 created.

11-25

Page 352: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

This final example displays a portion of the NL2 subtable:

sql> SELECT * FROM ORDER_NL2;Page 1 Order Number Product Nu Color Qty Price Extended Pri---------- ---------- ---------- ------ ---------- ------------ 912 53000 N/A 6 $129.95 $779.70 801 11000 Gray 1 $1,799.00 $1,799.00 941 50000 Gray 10 $1,399.99 $13,999.90 805 11140 Gray 5 $149.97 $749.85 805 10120 Standard 25 $429.94 $10,748.50 805 10050 Yellow 13 $29.97 $389.61 805 10150 Silver 15 $48.82 $732.30 805 10070 Silver 999 $34.97 $34,935.03... 505 records listed

NLn_KEY

Syntax

NL1_KEY(mvattribute | msattribute... | association_name)NL2_KEY(msattribute... | association_name)

Description

The NL1_KEY expression creates a counter for the number of values in one or more associated multivalued and multi-subvalued attributes.

The NL2_KEY expression creates a counter for the number of subvalues in one or more associated multi-subvalued attributes.

Points to remember about NLn_KEY:

At least one attribute must be included in the NLn_KEY expression.All attributes specified in a NLn_KEY must belong to the same association. Only D-type (data type) attributes can be used.If an association name is specified, it is replaced by all D-type attributes in the association.

11-26 Using UniData SQL

Page 353: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

When more than one multivalued or multi-subvalued attributes are used, the counter is incremented even when a value is contained in only one of the attributes. For example, in the following example, the counter is incre-mented for the COLOR attribute value Green, even though no value is present in the QTY attribute:

sql> SELECT * FROM ORDERS; Page 1 ORDER_NUM CLIENT PRODUCT_NO COLOR QTY CNT---------- ---------- ---------- ---------- ------ -------- 949 9990 56090 Red 3 1 Blue 3 2 Gray 3 3 Green 4

Examples

NL1_KEY

In the following example, the SELECT statement displays the value of the counter for each value in PRODUCT_NO. Notice that the attributes must be renamed in this view because NL1_KEY is an expression:

sql> SELECT ID, ORD_DATE, ORD_TIME, CLIENT_NO, NL1_KEY(PRODUCT_NO) sql> FROM ORDERSsql> UNNEST PRODUCT_NO;

Page 1 ORDER_NUM ODATE TIME CLIENT CNT---------- ---------- ------- ---------- -------- 912 01/13/1996 12:30PM 9984 1 801 09/28/1995 04:34PM 10018 1 941 01/14/1996 03:00PM 10009 1 805 10/05/1995 11:11AM 9987 1 805 10/05/1995 11:11AM 9987 2 805 10/05/1995 11:11AM 9987 3 805 10/05/1995 11:11AM 9987 4 805 10/05/1995 11:11AM 9987 5 830 01/24/1996 03:09PM 10013 1 830 01/24/1996 03:09PM 10013 2 830 01/24/1996 03:09PM 10013 3 830 01/24/1996 03:09PM 10013 4 830 01/24/1996 03:09PM 10013 5... 811 10/02/1995 10:10PM 10023 3487 records listed

11-27

Page 354: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

NL2_KEY

The following SELECT statement includes a counter for the multi-subvalued attri-butes COLOR and QTY:

sql> SELECT ID, CLIENT_NO, PRODUCT_NO, sql> COLOR, QTY, NL2_KEY(COLOR, QTY)sql> FROM ORDERS;

Page 1 ORDER_NUM CLIENT PRODUCT_NO COLOR QTY CNT---------- ---------- ---------- ---------- ------ -------- 912 9984 53000 N/A 6 1 801 10018 11000 Gray 1 1 941 10009 50000 Gray 10 1... 833 9974 40004 Almond 100 1 Gray 99 2 40005 White 60 1 Almond 60 2 40007 Gray 60 1... 969 9988 56080 Black 50 1 Red 50 2 Blue 50 3... 949 9990 56090 Red 3 1 Blue 3 2 Gray 3 3 56070 Red 3 1 Blue 3 2...193 records listed

DROP SUBTABLE

Syntax

DROP SUBTABLE subtable_name;

Description

The DROP SUBTABLE command drops a subtable that was created by a CREATE SUBTABLE statement. It also drops all views created on the subtable, but it does not affect the base table.

11-28 Using UniData SQL

Page 355: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

If a higher-level subtable is dropped, it renders invalid all subtables referencing it. Before dropping a higher-level subtable, first drop all of subtables that reference it.

Example

The following example demonstrates creating and dropping a subtable:

sql> CREATE SUBTABLE ORDERS_TST ASsql> SELECT ID, ORD_DATE, ORD_TIME, CLIENT_NOsql> FROM ORDERSsql> PRIMARY KEY ID;

Subtable ORDERS_TST created.

sql> DROP SUBTABLE ORDERS_TST;

Subtable ORDERS_TST has been dropped.

11-29

Page 356: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

12Chapter

Null and Missing Values

What Are Missing Values? . . . . . . . . . . . . . . 12-2 What Are Null Values? . . . . . . . . . . . . . . . 12-3Effects of Null and Missing Values in UniData SQL. . . . . . . . 12-5Null and Missing Values in ODBC . . . . . . . . . . . . . 12-7Working with Null Values . . . . . . . . . . . . . . . . 12-9 Points to Remember . . . . . . . . . . . . . . . . 12-9 Examples . . . . . . . . . . . . . . . . . . . . 12-10

Page 357: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The behavior of missing values in UniData is different from the behavior of ANSI SQL nulls. To make UniData SQL ANSI compliant, UniData uses true null value handling. However, because many existing UniBasic programs are not able to process nulls, we have also provided users with a configuration parameter to turn on or off null value handling.

Tip: After turning null value handling on, IBM recommends that you not turn it off, as the null character may have been introduced into your data. If you must turn null value handling off, be sure to check your data and convert the null value to another string (using a UniBasic program or virtual attribute) before attempting to execute queries, virtual attributes, or UniBasic programs.

Regardless of whether null value handling is on or off, UniData products handle missing values consistently. With null value handling turned on, UniData products handle null values consistently, and UniData SQL is compliant with ANSI standards.

What Are Missing Values?A missing value is one that is not present. Missing values also have the following characteristics:

In display and print, missing values take up no space. If a numeric value is used in an expression, missing values are considered to be 0.If a missing value is used in an expression in which a character is expected, the missing value is considered to be an empty string.A missing value is smaller than any other character value.

Here are some examples of missing values:

In a singlevalued attribute: no value is entered for a particular singlevalued attributeIn a multivalued attribute: two consecutive value marks are entered; the value between them is missing; also, if you enter the literal "}}", UniData inserts three missing values: one before the value marks, a second between the two, and a third after the value marks.Two associated multivalued attributes have different numbers of values. When the association is unnested, both attributes are considered to have the same number of values. To accomplish this, missing values are added to the attribute that originally had fewer values.

12-2

Page 358: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Example

The following example demonstrates the results obtained by unnesting associated multivalued attributes.

Attributes A and B are associated.

Multivalued attribute A: 1 23 4 5 6 7 8

Multivalued attribute B: A BC D

When unnested, the result table has the following values: 1 A 23 BC 4 D 5 (missing value) 6 (missing value) 7 (missing value) 8 (missing value)

What Are Null Values?Null values have the following characteristics in UniData SQL when null value handling is on:

When used in any expression, the result of the expression is null.When compared to any other value, including itself, the result is false. The only way to compare a null value is to use the keywords IS [NOT] NULL.The null value is the lowest value.

12-3 Using UniData SQL

Page 359: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Similarities and Differences in Null and Missing Values

The only similarity between null and missing values is that both types of values are not known when data was entered into the database. Differences between null and missing values include the following:

In an expression, such as X = Y, if X and Y are missing, the expression evaluates to true. If X and Y are null values, the expression evaluates to false.In a numeric expression, such as X + 1, if X is missing, the result is 1, but if X is null, the result is null.In a character expression, such as "ABC"||X. If X is missing, the result is ABC. If X is the null value, the result is the null value.The null value is lower than any other value including missing values.

12-4

Page 360: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Effects of Null and Missing Values in UniData SQLThe following table summarizes the effect of UniData’s handling of null and missing values. Notice that UniData SQL handles missing values consistently regardless of data type.

UniData SQL Operation Null Value Handling

Off On

WHERE (retrieves rows based on values in a particular attribute)

IS NULL selects rows containing missing values.IS NOT NULL excludes rows containing missing values.

IS NULL retrieves rows containing null values. IS NOT NULL excludes rows containing null values.

Aggregation: MIN, MAX, SUM, AVG, COUNT

Missing values are included in calculations.

Missing values are included in calculations. Null values are excluded from calculations.

COUNT(*) Missing values are included in count.

Null and missing values are included in count.

ORDER BY Missing string values are smaller than any other string value.Missing numeric values:If index is not used: -1 < missing < 0If index is used: missing is smaller than any other number.

Missing values are sorted the same way as with null flag off.Null values are the lowest. They are sorted first in an ascending sort.

Null and Missing Values in UniData SQL

12-5 Using UniData SQL

Page 361: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

UPDATE TABLE ORDERS SET X = NULL

Changes X to a missing value.

Changes X to the null value.

INSERT INTO TABLE ORDERS (ID, ATTR1, ATTR2) VALUES(1, NULL, "X")

Inserts a missing value into ATTR1.

Inserts the null value into ATTR1.

INSERT INTO TABLE ORDERS (ID,ATTR2) VALUES(1,"X")

Inserts a missing value into ATTR1.

Inserts a missing value into ATTR1.

UniData SQL Operation Null Value Handling

Null and Missing Values in UniData SQL (continued)

12-6

Page 362: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Null and Missing Values in ODBCUniData missing values are not supported by ODBC and ANSI SQL. In these products, the null value represents both unknown and missing data. Therefore, missing values are translated into nulls by UniData SQL and the client product never sees missing values. What the client sees as null values may be either null or missing values.

Warning: Desktop products handle null and missing values in various ways. Some third-party desktop (client) products are capable of handling zero-length strings. UniData uses the VCHAREMPTY configuration parameter in the uci.config file to determine how to treat an empty, or missing, value. If VCHAREMPTY = ON, UniData does not convert the empty (missing) value to the null value. If VCHAREMPTY=OFF, or is not defined, UniData converts the empty (missing) value to the null value.

The following table summarizes the effects of UniData’s handling of null and missing values through ODBC. Remember that, with null value handing on, you can emulate this processing in UniData SQL by executing SET MISSING NULL.

ODBC Operation Null Value Handling

Off On

WHERE (retrieves rows based on values in a particular attribute)

IS NULL retrieves rows containing missing values.IS NOT NULL excludes rows containing missing values.

IS NULL retrieves rows containing null and missing values.IS NOT NULL excludes rows containing null and missing values.

Aggregation: MIN, MAX, SUM, AVG, COUNT

Missing values are included in calculations.This does not conform to ANSI standards.

Null and missing values are excluded from calculations.

COUNT(*) Missing values are included in count.

Null and missing values are included in count.

Null and Missing Values through ODBC

12-7 Using UniData SQL

Page 363: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

ORDER BY Although the client, through ODBC, sees null values, those values are sorted as UniData missing values.Missing numeric values:If index is not used: -1 < missing < 0If index is used: missing is smaller than any other number.This does not fully comply with ANSI standards.

Null and missing values are all sorted as nulls: the lowest. They are sorted first in an ascending sort.

UPDATE TABLE ORDERS SET X = NULL

Changes X to a missing value.

Changes X to the null value.

INSERT INTO TABLE ORDERS (ID, ATTR1, ATTR2) VALUES(1, NULL, "X")

Inserts a missing value into ATTR1.

Inserts the null value into ATTR1.

INSERT INTO TABLE ORDERS (ID,ATTR2) VALUES(1,"X")

Inserts a missing value into ATTR1.

Inserts a missing value into ATTR1.This does not fully comply with ANSI standards.

ODBC Operation Null Value Handling

Null and Missing Values through ODBC (continued)

12-8

Page 364: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Working with Null ValuesWith the udtconfig parameter NULL_FLAG on, the null value represents an unknown value, and empty string represents missing values: “”. The remainder of this section assumes that null value handling is on.

The ASCII character that represents the null character is determined by the language group. See Administering UniData for instructions on setting the UniData configu-ration parameter NULL_FLAG. See UniData International for information on setting the language group.

Note: The UniData SQL statement SET MISSING NULL causes UniData SQL to treat missing values as null values, as does ODBC. See SET in the UniData SQL Commands Reference for an example.

Points to Remember Remember the following points when writing UniData SQL statements that manip-ulate data containing the null value:

IS NULL returns all null values. IS NOT NULL returns all non-null values. The null value is ignored by the aggregate functions: AVG, COUNT, MAX, MIN, NUMBER, STD, and VARIANCE. Hint: COUNT(*) counts rows that contain the null value. You can convert the null value to another string with the NVL function.The null value affects expressions and functions in the following ways:

When used in arithmetic expressions, the null value is considered to be 0.In comparisons, the null value is considered to be smaller than any character, string, or number. In ORDER BY, the null value is sorted as the lowest value.The result of a Boolean expression that compares any value with the null value returns a result of false. This includes comparisons in which the null value is compared with itself.

12-9 Using UniData SQL

Page 365: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

ExamplesThis section provides examples of null value handling in UniData SQL with null value handling ON (utdconfig parameter NULL_FLAG = 1).

Selecting Null Values

This example demonstrates selecting rows from the table STAFF for which the LNAME attribute contains the null value:

sql> SELECT ID, NVL(LNAME, "NULL"), DEPT, TITLE FROM STAFFsql> WHERE LNAME IS NULL;Page 1STAFF NVL(LNAME,"NULL") Dept Title---------- ----------------- ---- -------4 NULL PSY AscProf1 records listed

12-10

Page 366: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Aggregate Functions and the Null Value

The following example demonstrates the effect of the null value on group functions. Because the null value represents an unknown value, nulls are ignored.

sql> COMPUTE SUM OF PRICE ON PROD_NAME;sql> COMPUTE COUNT OF PRICE ON PROD_NAME;sql> COMPUTE MIN OF PRICE ON PROD_NAME;sql> COMPUTE MAX OF PRICE ON PROD_NAME;sql> COMPUTE STD OF PRICE ON PROD_NAME;sql> COMPUTE VARIANCE OF PRICE ON PROD_NAME;sql> BREAK ON PROD_NAME SKIP 1;sql> SELECT PROD_NAME, PRODUCT_NO, PRICE FROM ORDERSsql> UNNEST PRODUCT_NOsql> WHERE PRODUCT_NO BETWEEN 10010 AND 10020 ORDER BY PRODUCT_NO;Page 1Product Na Product Nu Price---------- ---------- ----------Camcorder 10010 N 10010 N 10010 N 10010 N 10020 $200.00 10020 $200.00 10020 $200.00 10020 $200.00********** ----------cnt 4max $200.00min $200.00std $0.00sum $800.00var $0.00 8 records listed

Counting Rows Containing Null Values

Use COUNT(*) to include in count rows that may contain the null value. COUNT(attribute_name) excludes from the count rows that contain the null value in attribute_name. This next two examples contrasts the COUNT(attribute_name) and COUNT(*).

12-11 Using UniData SQL

Page 367: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Before executing this example, LNAME “James” was changed to the null value. Here are the records to be counted:

sql> SELECT ID, LNAME FROM STAFF WHERE SAL > 30000;Page 1STAFF Last Nam---------- --------3 Eades6 Masters48 Fried4 records listed

As you can see in the following example, COUNT does not count rows for which the attribute being counted is the null value. Four rows are read, but only three are included in the count:

SELECT COUNT(LNAME) FROM STAFFWHERE SAL > 30000;Page 1CNT(Last-------- 3

4 record(s) calculated

COUNT(*), on the other hand, does include rows containing the null value (unless the attribute in the WHERE condition is the null value):

SELECT COUNT(*) FROM STAFFWHERE SAL > 30000;Page 1COUNT(*)-------- 4 4 record(s) calculated

12-12

Page 368: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Converting the Null Value for Display or Print

The following example demonstrates the NVL function, which converts the null value to another string for print or display purposes:

SELECT ID, NVL(LNAME, "Unknown"), DEPT, TITLE FROM STAFF;Page 1STAFF NVL(LNAME,"Unknown") Dept Title---------- -------------------- ---- -------3 Eades FA Prof6 Masters PSY Ascprof9 Aaron PSY Counsel or1 Fisher BUS Prof4 Unknown PSY AscProf7 Carnes ENG Prof2 Otis FA AscProf5 Gibson SPA Prof8 Fried BUS Dean9 records listed

The Null Value in Expressions and String Functions

Before executing this example, the ZIP code for customer Carrie Fischer was changed to the null value. The next example demonstrates the fact that the null value cannot be compared with any value, therefore it is not selected by the comparison “< 10050”.

sql> SELECT @ID, NAME, ZIP FROM CUSTOMER WHERE ZIP < 10050;Page 1 Cust Customer Name Zip C---------- --------------- ----- 100 Jones, Samuel 012121 records listed

12-13 Using UniData SQL

Page 369: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Before executing this example, the salary for Fischer was changed to the null value. This example demonstrates the fact that any arithmetic operation including the null value results in the null value:

sql> SET NULL “N”;sql> SHOW NULL;sql> SELECT @ID, LNAME, SAL, SAL +(SAL/20) "New Pay"sql> FROM STAFF;Page 1STAFF Last Nam Salary New Pay---------- -------- ------- ------------3 Eades 42,000 441006 Masters 35,800 375909 Aaron 19,900 208951 Fisher N N4 James 32,500 341257 Carnes 29,900 313952 Otis 25,800 270905 Gibson 26,800 281408 Fried 98,000 1029009 records listed

12-14

Page 370: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

AAppendix

UniData SQL Reserved Words

This appendix contains a list of words that are reserved for specific usage in UniData SQL. These words should only be used in their proper syntax in UniData SQL statements. Do not use these words as names of files or variables in your UniData SQL statements.

Note: If you use reserved words incorrectly in your UniData SQL state-ments, your statement or program could result in an error.

Page 371: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Using Reserved WordsThe following example shows an incorrect use of the SELECT reserved word. In this example, the SELECT reserved word is used twice; once in its proper syntax and once in place of the name of a file.

sql> SELECT NAME, CITY FROM SELECT;

The following example shows the correct use of the SELECT reserved word. In this example, the SELECT reserved word is used only once, in its proper syntax.

sql> SELECT NAME, CITY FROM CUSTOMER;

A-2

Page 372: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

List of Reserved Words

Reserved Words

ADD ALL ALTER AND

ANY AS ASC AUTO

AVG BETWEEN BREAK BTITLE

BY CHAR CLEAR COLUMN

COMMIT COMO COMPUTE COUNT

CREATE DATA DATE DAY

DEFAULT DELETE DESC DICT

DISTINCT DROP DYNAMIC EVERY

EXISTS EXIT EXP EXPDESC

FROM GRANT GROUP HAVING

IN INDEX INSERT INTERSECT

INTO IS LEFT LIKE

LISTDICT LOCK LONG MAX

MIN MODIFY MONTH NOT

NOWAIT NULL NUMBER OF

OFF ON OPTION OR

ORDER PH PUBLIC QUIT

REVOKE RIGHT ROLLBACK SELECT

SET SHOW SQL STDDEV

SUBTABLE SUM TABLE TRANSACTION

TO TTITLE UNION UNNEST

UniData SQL Reserved Words

A-3 Using UniData SQL

Page 373: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

UPDATE VALUE VALUES VARIANCE

VIEW WHEN WHERE WITH

YEAR

Reserved Words

UniData SQL Reserved Words (continued)

A-4

Page 374: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

BAppendix

More Table Joins

This appendix provides examples of SELECT statements that perform inner and outer joins — extracting data from two or more tables, subtables, or views.

The concept of joining tables is introduced in Chapter 6, “The SELECT Statement.” That chapter provides examples for writing simple joins. This appendix, however, provides examples of more complex joins, such as the following:

Combining joins with other SELECT statement clauses, such as WHERE, ORDER BY and subqueries.Stacking join clauses to include the results from a join in a second join.

The screen examples in this appendix are como files created by executing an SQL script that begins by executing the COMO ON command. Remember, the UniData SQL COMO command captures user input and system response as displayed on the terminal screen.

Page 375: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Tables for Join ExamplesLet’s create some simple tables we can use to try out various kinds of joins:

create table TABLE_AB (attrib_num number, attrib_char char(10)); 2 attribute(s) added. Create file TABLE_AB, modulo/1,blocksize/1024create table TABLE_CD (attrib_num number, attrib_char char(10)); 2 attribute(s) added. Create file TABLE_CD, modulo/1,blocksize/1024

insert into TABLE_AB values (1, 1, "aaa");1 record(s) created.insert into TABLE_AB values (2, 2, "bbb");1 record(s) created.

insert into TABLE_CD values (1, 1, "ccc");1 record(s) created.insert into TABLE_CD values (3, 10, "ddd");1 record(s) created.

Here are the tables we just created:

select * from TABLE_AB;Page 1TABLE_AB attrib_num attrib_char---------- ---------- ----------1 1 aaa2 2 bbb2 records listedselect * from TABLE_CD;Page 1TABLE_CD attrib_num attrib_char---------- ---------- ----------1 1 ccc3 10 ddd2 records listed

B-2

Page 376: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Examples of Outer Joins

Full Outer JoinA full outer join retrieves rows that contain data from only the left table (the first one listed in the SELECT statement) or only the right table (the second one listed in the SELECT statement), as well as rows containing data from both tables. All UniData outer joins must be equi-joins (based on an equal condition).

select TABLE_AB.@ID, TABLE_AB.attrib_num, TABLE_CD.@ID, TABLE_CD.attrib_num from TABLE_AB full outer join TABLE_CD on TABLE_AB.attrib_num = TABLE_CD.attrib_num;Page 1TABLE_AB attrib_num TABLE_CD attrib_num---------- ---------- ---------- ----------1 1 1 1 3 102 23 records listed

Joining Tables on Attributes of the Same NameThis example performs the same select and join as the preceding statement because the following two clauses do the same thing — fieldname (attribute name) must be the same in both tables:

on TABLE_AB.attrib_num = TABLE_CD.attrib_num ON table1.fieldname = table2.fieldnameusing(attrib_num) USING(fieldname)select TABLE_AB.@ID, TABLE_AB.attrib_num, TABLE_CD.@ID, TABLE_CD.attrib_num from TABLE_AB full outer join TABLE_CD using(attrib_num);Page 1TABLE_AB attrib_num TABLE_CD attrib_num---------- ---------- ---------- ----------1 1 1 1 3 102 23 records listed

B-3 Using UniData SQL

Page 377: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Full Outer Join Combined with WHERE ConditionYou can further limit data selected from the result of a join by specifying a search condition in a WHERE clause:

select TABLE_AB.@ID, TABLE_AB.attrib_num, TABLE_CD.@ID, TABLE_CD.attrib_num from TABLE_AB full outer join TABLE_CD on TABLE_AB.attrib_num = TABLE_CD.attrib_numwhere TABLE_AB.@ID > 1;Page 1TABLE_AB attrib_num TABLE_CD attrib_num---------- ---------- ---------- ---------- 1 1 3 102 23 records listed

B-4

Page 378: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Joining on Multivalued AttributesYou must unnest multivalued attributes that are included in a join statement. If you do not, the result table from which records are selected may be missing rows. Here is a sample join with unnest from the demo database:

select a.@ID, a.NAME, a.TAPES_RENTED, a.TAPE_COST, b.@ID, b.RENTAL_PRICEfrom CUSTOMER a FULL JOIN TAPES b ON a.TAPES_RENTED = b.@IDunnest a.TAPES_RENTED;Page 1 CUSTOMER Customer Name Tapes Rental C TAPES Retail C---------- --------------- ---------- -------- ---------- -------- 200 Smith, Leif 201 Wagner, Pat 202 Grundy, Robin 203 Boorman, Rick 204 Frobisher, Kamal 205 Fellini, J. Hoboken 206 LaRue, Karma 207 Doodle, Polly W. 208 Dillon, Matt 209 Byles, Marcy 25 Valenzuela, Carmen 210 Wagner, Esther 2 11 Best, George B2297 $2.50 B2297 2.50 2 Partner, Bonnie B2297 $2.50 B2297 2.50 2 Partner, Bonnie B914 $1.06 B914 1.06 V1077 4.50Page 2 CUSTOMER Customer Name Tapes Rental C TAPES Retail C---------- --------------- ---------- -------- ---------- -------- 3 Fischer, Carrie V110 $2.52 V110 2.52 190 Belafonte, V1234 Harry 8 Jones, Mable V1249 $3.54 V1249 3.54 100 Jones, Samuel V1254 $3.15 V1254 3.15 9 Chase, Carl V1254 $3.15 V1254 3.15 15 James, Bob V2001 $3.75 V2001 3.75 1 Smith, Harry V2001 $3.75 V2001 3.75 90 Steven Spender V2123 90 Steven Spender V2232 100 Jones, Samuel V2343 6 Jones, Bob V4341 $4.54 V4341 4.54 8 Jones, Mable V4499 $4.54 V4499 4.54 9 Chase, Carl V4951 $2.50 V4951 2.50 1 Smith, Harry V5004 $4.40 V5004 4.40 10 Faber, Harry V5151 $3.54 V5151 3.54 12 Jamieson, Dale V6670 $6.75 V6670 6.75

B-5 Using UniData SQL

Page 379: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

V7456 4.04 1 Smith, Harry V8181 $5.50 V8181 5.50 100 Jones, Samuel V8481 $6.75 V8481 6.75Page 3 CUSTOMER Customer Name Tapes Rental C TAPES Retail C---------- --------------- ---------- -------- ---------- -------- 9 Chase, Carl V8481 $6.75 V8481 6.75 7 Jones, Freddie V9431 $4.50 V9431 4.50 14 Darrell Corden V9834 5 Barrie, Dick V996 $4.54 V996 4.54 4 Bowie, David V9961 $5.05 V9961 5.05 v1231 3.79 v4637 3.0342 records listed

Left Outer JoinA left outer join retrieves only rows that contain data from the left table (the first one listed), or both tables included in the statement. You create a left outer join by including the LEFT keyword in the JOIN clause:

select TABLE_AB.@ID, TABLE_AB.attrib_num, TABLE_CD.@ID, TABLE_CD.attrib_num from TABLE_AB left outer join TABLE_CD on TABLE_AB.attrib_num = TABLE_CD.attrib_num;Page 1TABLE_AB attrib_num TABLE_CD attrib_num---------- ---------- ---------- ----------1 1 1 12 22 records listed

Left Outer Join Combined with WHERE ConditionYou can further limit data selected from the result of a join by specifying a search condition in a WHERE clause. This search condition selects values in attribute attrib_num from the 02 table that are equal to 3:

select TABLE_AB.@ID, TABLE_AB.attrib_num, TABLE_CD.@ID, TABLE_CD.attrib_num from TABLE_AB left outer join TABLE_CD on TABLE_AB.attrib_num = TABLE_CD.attrib_numwhere TABLE_AB.attrib_num = 2;Page 1TABLE_AB attrib_num TABLE_CD attrib_num---------- ---------- ---------- ----------2 21 records listed

B-6

Page 380: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Right Outer JoinA right outer join retrieves only rows that contain data from the right table (the last one listed), or both tables included in the statement. You create a right outer join by including the RIGHT keyword in the JOIN clause:

select TABLE_AB.@ID, TABLE_AB.attrib_num, TABLE_CD.@ID, TABLE_CD.attrib_num from TABLE_AB right outer join TABLE_CD on TABLE_AB.attrib_num = TABLE_CD.attrib_num;Page 1TABLE_AB attrib_num TABLE_CD attrib_num---------- ---------- ---------- ----------1 1 1 1 3 102 records listed

Right Outer Join Combined with WHERE ConditionYou can further limit data selected from the result of a join by specifying a search condition in a WHERE clause. This search condition selects values in attribute attrib_num from the 02 table that are not equal to 3:

select TABLE_AB.@ID, TABLE_AB.attrib_num, TABLE_CD.@ID, TABLE_CD.attrib_numfrom TABLE_AB right outer join TABLE_CD on TABLE_AB.attrib_num = TABLE_CD.attrib_numwhere TABLE_CD.attrib_num != 3;Page 1TABLE_AB attrib_num TABLE_CD attrib_num---------- ---------- ---------- ----------1 1 1 1 3 102 records listed

B-7 Using UniData SQL

Page 381: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Joining Three TablesYou cannot join more than two tables in a single join, but you can join the result of a join of two tables with a third table. You do this by stacking JOIN clauses. Notice that rows selected are further limited by the inclusion of a search condition in the WHERE clause:

select TABLE_AB.@ID, TABLE_AB.attrib_num, t2.@ID, t2.attrib_num, t3.@ID, t3.attrib_numfrom TABLE_AB full outer join TABLE_CD t2 on TABLE_AB.attrib_num = t2.attrib_num full outer join TABLE_CD t3 on TABLE_AB.@ID = t3.@IDwhere t3.@ID > 1;Page 1TABLE_AB attrib_num TABLE_CD attrib_num TABLE_CD attrib_num---------- ---------- ---------- ---------- ---------- ---------- 3 101 1 1 12 2 3 104 records listedselect TABLE_AB.@ID, TABLE_AB.attrib_num, t2.@ID, t2.attrib_num, t3.@ID, t3.attrib_numfrom TABLE_AB full outer join TABLE_CD t2 using (attrib_num)full outer join TABLE_CD t3 using (@ID)where t3.@ID > 1;Page 1TABLE_AB attrib_num TABLE_CD attrib_num TABLE_CD attrib_num---------- ---------- ---------- ---------- ---------- ----------2 21 1 1 1 3 10 3 103 records listed

Joining Tables in a SubqueryYou can include a join in a subquery:

select * from TABLE_AB where attrib_num = (select TABLE_CD.attrib_num from TABLE_AB full outer join TABLE_CD on TABLE_CD.attrib_num = TABLE_AB.attrib_num);Page 1TABLE_AB attrib_num attrib_char---------- ---------- ----------1 1 aaa1 records listed

B-8

Page 382: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

The following syntax produces the same results:

select * from TABLE_AB where attrib_num = (select TABLE_CD.attrib_num from TABLE_AB full outer join TABLE_CD using (attrib_num));

Sorting Join ResultsYou can combine a join with the ORDER BY clause to sort the results from the JOIN:

select TABLE_AB.@ID, TABLE_AB.attrib_num, TABLE_CD.@ID, TABLE_CD.attrib_num from TABLE_AB full outer join TABLE_CD on TABLE_AB.attrib_num = TABLE_CD.attrib_numorder by TABLE_AB.attrib_num;Page 1TABLE_AB attrib_num TABLE_CD attrib_num---------- ---------- ---------- ---------- 3 101 1 1 12 23 records listed

The following syntax produces the same results. The USING clause creates an equi-join on the attribute in parentheses:

select TABLE_AB.@ID, TABLE_AB.attrib_num, TABLE_CD.@ID, TABLE_CD.attrib_numfrom TABLE_AB full outer join TABLE_CD using (attrib_num)order by TABLE_CD.@ID;Page 1TABLE_AB attrib_num TABLE_CD attrib_num---------- ---------- ---------- ----------2 21 1 1 1 3 103 records listed

Combining Results of Queries Containing JoinsYou can combine multiple queries, each of which join tables, subtables, or views by using the keyword UNION.

B-9 Using UniData SQL

Page 383: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Note: UNION combines the results of two query_spec statements into a single result set. The number of items in query_spec must be the same; data types of corresponding items must be the same. Duplicate records are discarded.

select TABLE_AB.@ID, TABLE_AB.attrib_num, TABLE_CD.@ID, TABLE_CD.attrib_numfrom TABLE_AB left outer join TABLE_CD using (@ID)unionselect TABLE_CD.@ID, TABLE_CD.attrib_num, TABLE_AB.@ID, TABLE_AB.attrib_numfrom TABLE_CD right outer join TABLE_AB using (attrib_num);Page 1TABLE_AB attrib_num TABLE_CD attrib_num---------- ---------- ---------- ----------1 1 1 12 2 2 23 records listed

Creating a View from Joined TablesThis example creates a view by joining tables. The attributes selected (TABLE_AB.@ID, TABLE_AB.attrib_num...) become the corresponding attributes in the view (v1, v2, v3...).

create view view_1 (v1, v2, v3, v4) as select TABLE_AB.@ID, TABLE_AB.attrib_num, TABLE_CD.@ID, TABLE_CD.attrib_num from TABLE_AB full outer join TABLE_CD on TABLE_AB.attrib_num = TABLE_CD.attrib_num;

View view_1 created.

select * from view_1;Page 1v1 v2 v3 v4---------- ---------- ---------- ----------1 1 1 1 3 102 23 records listed

B-10

Page 384: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Examples of Inner JoinsThis first example joins tables based on data values in attribute attrib_num being equal. Notice that the inner join selects only records that contain equal data in the joined attributes:

select TABLE_AB.@ID, TABLE_AB.attrib_num, TABLE_CD.@ID, TABLE_CD.attrib_num from TABLE_AB join TABLE_CD on TABLE_AB.attrib_num = TABLE_CD.attrib_num;Page 1TABLE_AB attrib_num TABLE_CD attrib_num---------- ---------- ---------- ----------1 1 1 11 records listed

These next two statements use different syntax to create the same inner join, which is based on values in attributes attrib_num in tables TABLE_AB and TABLE_CD being equal:

select TABLE_AB.@ID, TABLE_AB.attrib_num, TABLE_CD.@ID, TABLE_CD.attrib_numfrom TABLE_AB inner join TABLE_CD on TABLE_AB.attrib_num = TABLE_CD.attrib_num;Page 1TABLE_AB attrib_num TABLE_CD attrib_num---------- ---------- ---------- ----------1 1 1 11 records listed

select TABLE_AB.@ID, TABLE_AB.attrib_num, TABLE_CD.@ID, TABLE_CD.attrib_numfrom TABLE_AB inner join TABLE_CD using(attrib_num);Page 1TABLE_AB attrib_num TABLE_CD attrib_num---------- ---------- ---------- ----------1 1 1 11 records listed

B-11 Using UniData SQL

Page 385: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Stacking JOIN ClausesThe first join in the following example creates a temporary table, t3, that is joined with TABLE_AB in the second join clause:

select TABLE_AB.@ID, TABLE_AB.attrib_num, t2.@ID, t2.attrib_num, t3.@ID, t3.attrib_numfrom TABLE_AB inner join TABLE_CD t2 on TABLE_AB.attrib_num = t2.attrib_num inner join TABLE_CD t3 on TABLE_AB.@ID = t3.@ID;Page 1TABLE_AB attrib_num TABLE_CD attrib_num TABLE_CD attrib_num---------- ---------- ---------- ---------- ---------- ----------1 1 1 1 1 11 records listed

Here, the same join is created with the USING clause:

select TABLE_AB.@ID, TABLE_AB.attrib_num, t2.@ID, t2.attrib_num, t3.@ID, t3.attrib_numfrom TABLE_AB inner join TABLE_CD t2 using (attrib_num)inner join TABLE_CD t3 using (@ID);Page 1TABLE_AB attrib_num TABLE_CD attrib_num TABLE_CD attrib_num---------- ---------- ---------- ---------- ---------- ----------1 1 1 1 1 11 records listed

Combining Inner Join Results with UNIONThe following two statements each join the same two tables:

select TABLE_AB.@ID, TABLE_AB.attrib_num, TABLE_CD.@ID, TABLE_CD.attrib_numfrom TABLE_AB inner join TABLE_CD using (@ID);Page 1TABLE_AB attrib_num TABLE_CD attrib_num---------- ---------- ---------- ----------1 1 1 11 records listed

select TABLE_CD.@ID, TABLE_CD.attrib_num, TABLE_AB.@ID, TABLE_AB.attrib_numfrom TABLE_CD inner join TABLE_AB using (attrib_num);Page 1TABLE_CD attrib_num TABLE_AB attrib_num---------- ---------- ---------- ----------1 1 1 11 records listed

B-12

Page 386: Using UniData SQL - Rocket Software UniData SQL iii The above trademarks are property of the specified companies in the United States, other countries, or both. All other products

Creating a View from an Inner JoinThis statement creates a view based on a subquery that creates an inner join of tables TABLE_AB and TABLE_CD. The attributes in view_2 (v1, v2, and so on) corre-spond to the attributes in the select statement (TABLE_AB.@ID, TABLE_AB.attrib_num., and so on):

create view view_2 (v1, v2, v3, v4) as select TABLE_AB.@ID, TABLE_AB.attrib_num, TABLE_CD.@ID, TABLE_CD.attrib_num from TABLE_AB inner join TABLE_CD on TABLE_AB.attrib_num = TABLE_CD.attrib_num;

View view_2 created.

Here’s the view created by the preceding statement:

select * from view_2;Page 1v1 v2 v3 v4---------- ---------- ---------- ----------1 1 1 11 records listed

B-13 Using UniData SQL


Recommended