Rocket UniData. Using UniData SQL. Version February 2015 UDT-810-SQLU-1
|
|
|
- Cynthia Collins
- 9 years ago
- Views:
Transcription
1 Rocket UniData Using UniData SQL Version February 2015 UDT-810-SQLU-1
2 Notices Edition Publication date: February 2015 Book number: UDT-810-SQLU-7 Product version: Rocket UniData Copyright Rocket Software, Inc. or its affiliates All Rights Reserved. Trademarks Rocket is a registered trademark of Rocket Software, Inc. For a list of Rocket registered trademarks go to: All other products or services mentioned in this document may be covered by the trademarks, service marks, or product names of their respective owners. Examples This information might contain examples of data and reports. The examples include the names of individuals, companies, brands, and products. All of these names are fictitious and any similarity to the names and addresses used by an actual business enterprise is entirely coincidental. License agreement This software and the associated documentation are proprietary and confidential to Rocket Software, Inc. or its affiliates, are furnished under license, and may be used and copied only in accordance with the terms of such license. Note: This 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. 2
3 Corporate information Rocket Software, Inc. develops enterprise infrastructure products in four key areas: storage, networks, and compliance; database servers and tools; business information and analytics; and application development, integration, and modernization. Website: Rocket Global Headquarters 77 4th Avenue, Suite 100 Waltham, MA USA To contact Rocket Software by telephone for any reason, including obtaining pre-sales information and technical support, use one of the following telephone numbers. Country Toll-free telephone number United States Australia Belgium Canada China France Germany Italy Japan Netherlands New Zealand South Africa United Kingdom Contacting Technical Support The Rocket Customer Portal is the primary method of obtaining support. If you have current support and maintenance agreements with Rocket Software, you can access the Rocket Customer Portal and report a problem, download an update, or find answers in the U2 Knowledgebase. To log into the Rocket Customer Portal or to request a Rocket Customer Portal account, go to In addition to using the Rocket Customer Portal to obtain support, you can send to [email protected] or use one of the following telephone numbers. Country Toll-free telephone number North America United Kingdom/France +44(0) or +44(0) Europe/Africa +44 (0) Australia or +61 (0) New Zealand
4 Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Table of Contents Table of Contents Chapter 1 Chapter 2 Chapter 3 Introduction to UniData SQL UniData SQL Commands Reference Additional Reading The UniData RDBMS Elements of the UniData Database UniData Demo Databases Overview of UniData SQL Features of UniData SQL Elements of UniData SQL UniData SQL Tables The SELECT Statement Multivalued Attributes Associations Unnesting Multivalued Attributes The UniData Dictionary Elements of Dictionary Records Getting Started Starting UniData SQL Creating a Table Inserting Data into a Table Updating Data in a Table Deleting Data from a Table Selecting Data from a Table Removing Tables Exporting Selected Data to a Sequential File Exporting Selected Data to a Temporary Table Creating and Modifying Tables Creating a New Table C:\Users\awaite\Documents\U2Doc\UniData\8.1\Source\SQLU\SQLUTOC.fm (booktoc.template) June 20, :46 pm
5 Defining Attributes Default Format and Conversion Codes Defining Attribute Name Defining Data Type Defining Virtual Attributes Defining Location Defining Display Name Defining Format Defining Value Type Defining Associations Examining Table Definitions Modifying Table Definitions ALTER TABLE Keywords Adding Attributes Modifying Tables Using the MODIFY Keyword Modifying Association Names Modifying an Association Deleting Attributes Resizing Tables Removing Tables Indexing Tables What Is Indexing? Creating and Dropping Indexes Chapter 4 Chapter 5 The Command Stack Introduction to the Command Stack Using the Command Stack Command Stack Operators Appending to an Existing Statement Changing Statements in the Stack Deleting Statements in the Stack Inserting a Statement Line into the Stack Listing Statements in the Stack Recalling a Statement in the Stack Storing Statements for Later Use Manipulating Data Inserting Data into a Table The INSERT Command Table of Contents 5
6 Inserting a Single Record Inserting Data into Specified Attributes Inserting Empty Strings and the Null Value Inserting a Record with Multiple Values Copying Multiple Records from Other Tables Updating Data in a Table The UPDATE Command Updating Specific Attributes Updating Multiple Records Updating Multivalued Attributes Adding Values and Subvalues Deleting Data from a Table The DELETE Command Deleting a Set of Records Deleting All Records in a Table Deleting Data in Multivalued Attributes Restoring the Database Chapter 6 The SELECT Statement Retrieving Data with SELECT Separation Characters Writing Simple Queries Selecting Rows from the Result Table Selecting Specific Attributes Selecting All Attributes Selecting or Excluding Duplicate Values Selecting Multivalued Attributes Selecting Multi-Subvalued Attributes Selecting Virtual Attributes Selecting Records by Specifying Record IDs Selecting Tables with FROM Qualifying Attribute Names with Table Labels Joining Tables Types of Joins How to Join Tables Inner Joins Outer Joins Unnesting Query Results with UNNEST How to Unnest Unnesting Multivalued Attributes Using UniData SQL
7 Unnesting Multi-Subvalued Attributes Unnesting Multivalued and Multi-Subvalued Attributes Selecting Records with WHERE Using Greater Than in a WHERE Clause Combining Selection Criteria with AND Combining Selection Criteria with OR Combining the AND and OR Operators Selecting Values That Do Not Meet Conditions Applying Conditions to Every Value Selecting Records That Match Patterns Searching for Patterns with the LIKE Operator Using Range Specifiers Using Wild Cards in Patterns Dictionary Conversions and the LIKE Operator LIKE Clauses and Strings Incorrect Pattern Specification The IN Operator Selecting Records within a Range Sorting Query Results Sorting in Ascending Order Sorting in Descending Order Sorting by Multiple Attributes Combining Ascending and Descending Operators Sorting Based on Multivalued Attributes Unnesting and Sorting Based on Multivalued Attributes Unnesting an Association and Sorting Sorting and Unnesting Subqueries Combining Multiple Queries into a Single Query Using ANY, ALL, and IN with Subqueries Writing Compound Queries Passing Data from Query to Subquery Group Functions Selecting Summary Information from One Group Multiple Group Functions Correct and Incorrect Group Function Use Using DISTINCT and COUNT with Attributes Writing Column Headings Selecting Summary Information from Multiple Groups Table of Contents 7
8 Including Multiple Attribute Names in a GROUP BY Clause Specifying a Search Condition for Groups Group Functions with Multivalued Attributes Expressions and Functions Arithmetic Expressions Arithmetic Functions Arithmetic Expressions and Functions in Group Functions Character String Functions Date Functions Chapter 7 Chapter 8 Creating and Querying Views What Is a View? How to Use Views How View Queries Are Processed Creating Views Creating a View from a Single Table Creating a View from Multiple Tables Creating a View Using Expressions Creating a View on a View Querying Views Optimizing Processing on View Queries Dropping Views Creating Reports Understanding UniData SQL Reports Constructing Report Columns Using the COLUMN Command Setting Up Column Headings Justifying Text in a Column Heading Controlling Column Spacing Controlling Spaces between Two Columns Controlling Spaces Between Specific Columns Formatting Report Columns Copying a Format Displaying Long Values Defining Report Titles Turning Titles On or Off Formatting Headers Formatting Footers Including Attribute Values in Headers and Footers Using UniData SQL
9 Organizing Reports by Group Creating Breaks in a Report Performing Computations at Breaks Computing Subtotals Executing Multiple Computations Computing a Grand Total Displaying and Clearing Breaks and Computations Setting the Report Environment Setting Report Parameters Wrapping Text Vertically Displaying Report Environment Parameters Preparing Complex Reports Producing a Complex Report Chapter 9 Chapter 10 Security and Administration UniData SQL Security Viewing Privileges Granting Privileges GRANT Revoking Privileges REVOKE Converting Files for UniData SQL Requirements CONVERT.SQL Converting Demo Tables UniData SQL Transaction Processing Benefits of UniData SQL TP ACID Properties UniData SQL TP and Other UniData Products UniData SQL TP and RFS UniData SQL TP and UniBasic Transaction Semantics Initiation Termination UniData SQL TP Locks Other Types of Locks Transaction Isolation Types of Transaction Errors UniData SQL Isolation Levels Table of Contents 9
10 UniData SQL TP Commands TP Commands Transaction-Initiating Commands Unsupported Commands SET DISPLAY TPMESSAGE SET TRANSACTION COMMIT ROLLBACK AUTO COMMIT LOCK TABLE Examples of UniData SQL TP Example 1 Read Committed vs. Repeatable Read Default Transaction Settings Other UniData SQL TP Considerations System Administration Performance Interaction of UniData SQL with Other Transactional Environments Tips on Transactions Optimizing Performance Limitations Chapter 11 UniData SQL and 1NF Mapping Terminology NF Mapping NF2 Data Model vs. 1NF Data Model What Is a 1NF Mapping View? Subtables Rules for Updating Subtables Primary and Foreign Keys Creating Subtables Creating Keys Examples of Read-Only Mapping Creating a View for Singlevalued Attributes Creating a View for the Multivalued Attribute Creating a View for Multivalued and Multi-Subvalued Attributes Examples of Updatable Mapping Create a Nested Level 0 Subtable Create a Nested Level 1 Subtable Using UniData SQL
11 Create a Nested Level 2 Subtable Updatable Mapping Commands CREATE SUBTABLE NLn_KEY DROP SUBTABLE Chapter 12 Appendix A Appendix B Null and Missing Values What Are Missing Values? What Are Null Values? Effects of Null and Missing Values in UniData SQL Null and Missing Values in ODBC Working with Null Values Points to Remember Examples UniData SQL Reserved Words Using Reserved Words A-2 List of Reserved Words A-3 More Table Joins Tables for Join Examples B-2 Examples of Outer Joins B-3 Full Outer Join B-3 Joining Tables on Attributes of the Same Name B-3 Full Outer Join Combined with WHERE Condition..... B-4 Joining on Multivalued Attributes B-5 Left Outer Join B-6 Left Outer Join Combined with WHERE Condition..... B-6 Right Outer Join B-7 Right Outer Join Combined with WHERE Condition..... B-7 Joining Three Tables B-8 Joining Tables in a Subquery B-8 Sorting Join Results B-9 Combining Results of Queries Containing Joins B-9 Creating a View from Joined Tables B-10 Examples of Inner Joins B-11 Stacking JOIN Clauses B-12 Combining Inner Join Results with UNION B-12 Creating a View from an Inner Join B-13 Table of Contents 11
12 Chapter 1: Introduction to UniData SQL Chapter 1 UniData SQL Commands Reference Additional Reading The UniData RDBMS Elements of the UniData Database UniData Demo Databases Overview of UniData SQL Features of UniData SQL Elements of UniData SQL UniData SQL Tables The SELECT Statement Multivalued Attributes Associations Unnesting Multivalued Attributes The UniData Dictionary Elements of Dictionary Records
13 Using UniData SQL shows you how to use the Rocket UniData implementation of Structured 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 Reference As 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 Reading This 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. on UNIX Platforms and Administering UniData on Windows Platforms. 1-2
14 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 operations on the database, known as the data manipulation language (DML). Elements of the UniData Database The 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 components. The terms for these components are: Record Primary Key Attribute Tuple Table Database 1-3 Using UniData SQL
15 UniData Demo Databases There 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 Classics University 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
16 Overview of UniData SQL UniData SQL is an implementation of SQL. This standard, nonprocedural language enables you to create, access, and manipulate data across relational databases. Features of UniData SQL The 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 ALTER TABLE DROP TABLE CREATE INDEX DROP INDEX GRANT REVOKE 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 INSERT UPDATE 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
17 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
18 Elements of UniData SQL UniData SQL Tables A 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, 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. ROWS (Records, Tuples) Name Harry Smith Bonnie Partner Carrie Fischer Dick Barrie Address 1414 W. 8th 19th & Elm 640 E. Evans 2112 S. Florida City Englewood Golden Arvada Lakewood COLUMNS (Attributes, Fields) Example of a Table Tip: In UniData SQL, the term table is synonymous with the term file. 1-7 Using UniData SQL
19 The SELECT Statement To retrieve data from your database in UniData SQL, you must use SELECT statements. 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; Customer Name Jones, Bob Frobisher, Kamal Steven Spender Jamieson, Dale Chase, 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; Customer Name Barrie, Dick Belafonte, Harry Best, George Boorman, Rick Bowie, David Byles, 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
20 Multivalued Attributes UniData employs a record concept that supports multivalued attributes. A multivalued 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. Associations An 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 Attributes You 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 SQLbased relational databases. 1-9 Using UniData SQL
21 The UniData Dictionary A 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 Records Dictionaries 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 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) Dictionary Attributes 1-10
22 Attribute 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 information that UniData ignores. 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. Dictionary Attributes (continued) See Using UniData for detailed information on setting up and using UniData dictionaries Using UniData SQL
23 Chapter 2: Getting Started Chapter 2 Starting UniData SQL Creating a Table Inserting Data into a Table Updating Data in a Table Deleting Data from a Table Selecting Data from a Table Removing Tables Exporting Selected Data to a Sequential File Exporting Selected Data to a Temporary Table
24 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 ODBCcompliant. Converted files such as these are called base tables. The databases contain the following data tables. Video Classics CUSTOMER TAPES UniVersity STUDENT STAFF 2-2 Using UniData SQL 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, Chapter 1: Introduction to UniData SQL, or see Administering UniData on UNIX and Administering UniData on Windows Platforms. 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. CATEGORIES Insert, update, and delete data in a table. Select data from a table. COURSES Data Tables in Demo Tables
25 Drop a table. Export selected data to a sequential file. Export selected data to a temporary table. End a UniData SQL session. 2-3
26 Starting UniData SQL Before 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 on UNIX or Administering UniData on Windows Platforms. When you are in the demo directory, one of the following prompts appears on your screen. Prompt Description 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: :sql sql> : UniData colon prompt % or $ UNIX shell prompt System Prompts 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, Chapter 9: Security and Administration, for information on properly configuring your system to enable you to access the demo database. Methods for Starting UniData SQL You can enter UniData SQL in any of the following ways: Start from the UniData environment. 2-4 Using UniData SQL
27 Start from the UniData SQL prompt. Code EXECUTESQL statements in UniBasic programs. For further information, 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. Note: ObjectCall is not available beginning at UniData 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
28 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; THEN GO OK <6>:DISPLAY BAD <7>:GO FINI <8>:OK:DISPLAY OK <9>:FINI:DISPLAY END 2-6 Using UniData SQL
29 Creating a Table To 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_EXAM sql> (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/1024 Hash type = 0 Create file ST_EXAM, modulo/1,blocksize/1024 Hash type = 0 Added "@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, 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
30 Inserting Data into a Table To 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, Chapter 5: Manipulating Data. 2-8 Using UniData SQL
31 Updating Data in a Table To 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> = "CS505"; COMMIT complete. 1 record(s) updated. For further information on the UPDATE statement, see Chapter 5, Chapter 5: Manipulating Data. 2-9
32 Deleting Data from a Table To 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 = "CS505"; COMMIT complete. 1 record(s) deleted or updated. For further information on the DELETE statement, see Chapter 5, Chapter 5: Manipulating Data Using UniData SQL
33 Selecting Data from a Table The 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> FROM COURSES; COURSES Course Name Credi Teacher FA120 Finger Painting 5 Fried PY140 Abnornal Psychology 5 Masters PE100 Golf - I 3 Fisher CS105 Database Design 3 Gibson MA101 Math Principals 3 Otis FA231 Photography Practicum 3 Fried PE220 Racquetball 3 Fisher MA221 Calculus - II 5 Otis EG110 Engineering Principles 5 Carnes FA121 Watercorlors 3 Carnes EG140 Fluid Mechanics 3 Aaron CS130 Intro to Operating 5 James Systems HY101 Western Civilization 3 Otis CS100 Intro to Computer Science 3 Gibson 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, Chapter 6: The SELECT Statement. 2-11
34 Removing Tables When 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, 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):y Deleting file D_ST_EXAM. Deleting file ST_EXAM. For further information on removing a table, see Chapter 3, Chapter 3: Creating and Modifying Tables Using UniData SQL
35 Exporting Selected Data to a Sequential File It 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 path 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,PHONE sql>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 path. sql>select NAME,ADDRESS,CITY,STATE,ZIP,PHONE sql>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
36 Exporting Selected Data to a Temporary Table It 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,PHONE sql>from CUSTOMER WHERE CITY = 'Denver' sql>into INTERMEDIATE; 2-14 Using UniData SQL
37 Chapter 3: Creating and Modifying Tables Chapter 3 Creating a New Table Defining Attributes Default Format and Conversion Codes Defining Attribute Name Defining Data Type Defining Virtual Attributes Defining Location Defining Display Name Defining Format Defining Value Type Defining Associations Examining Table Definitions Modifying Table Definitions ALTER TABLE Keywords Adding Attributes Modifying Tables Using the MODIFY Keyword Modifying Association Names Modifying an Association Deleting Attributes Resizing Tables Removing Tables Indexing Tables What Is Indexing? Creating and Dropping Indexes
38 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
39 Creating a New Table The 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 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
40 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. Examples The 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_TAB sql> (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 TYP LOC CONV NAME FORMAT SM ASSOC D 0 NEW_TAB 10L S NUM_FLD D 1 10R S CHAR_FLD D 2 10L S MONEY_FLD D 3 MD2$ 10R S,- 4 records listed 3-4 Using UniData SQL
41 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_TAB sql> (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 TYP LOC CONV NAME FORMAT SM ASSOC D 0 NEW_TAB 10L S NUM_FLD D 1 10R S CHAR_FLD D 2 10L S MONEY_FLD D 3 MD2$ 10R S,- VIRT_FLD V NUM_FLD * MON 10R S EY_FLD 5 records listed 3-5
42 Defining Attributes You 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 description Display name Format Value type specification Association 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
43 Default Format and Conversion Codes When 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. Data Type Default 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 Default Attribute Display Format 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 Name You must assign an attribute name when you define a new attribute. The following restrictions apply to attribute names: 3-7
44 Valid attribute names can contain the following types of characters: Alphabetic characters Numbers Special 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 through ODBC, do not #, 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 Type Data type describes the type of values that the attribute contains. You can specify four data types: CHAR DATE NUMBER LONG 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
45 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, UniData stores time as an integer between 0 and (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/. 3-9
46 Syntax: DATE[( date_conv )] 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. Parameter length n Description Column width. 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. NUMBER Parameters 3-10 Using UniData SQL
47 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. 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 Attributes A 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. 3-11
48 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 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 Location LOC 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 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) 3-12 Using UniData SQL
49 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 Defining Display Name DISP 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 Format FORMAT 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. 3-13
50 Syntax: FORMAT( length[f.char]{l R T C}[n][$][,][Z][mask] ) Display Format Options The following table shows the display format options. Option length f.char L R C T n Description An integer specifying the width of the output value. 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. Specifies left-justification in a column of length spaces. If the text is longer than length, it is broken in length intervals. Specifies right-justification in a column of length spaces. Specifies centered text in the column of length spaces. Specifies text justification. If data must be broken to fit in a column, it is broken between words. 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 mask Suppresses leading zeros. 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. Display Format Options 3-14 Using UniData SQL
51 Sample Display Formats The next table illustrates sample display formats. Value Format Result Harry Miller 15.L Harry Miller... Harry Miller 15*R ***Harry Miller Harry Miller 10T Harry Miller L###-###-#### L##/##/#### 03/03/ R0$ $ R2$ $ R0$, $9, R2$, $9, Sample Display Formats 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
52 Valid types are listed in the following table. Type MV MS S Explanation Multivalued attribute Multi-subvalued attribute Singlevalued attribute (default) Attribute Types Defining Associations The 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
53 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 TYP LOC CONV NAME FORMAT SM ASSOC D 0 PERSON 10L S NAME D 1 Customer Name 25L S SEX D 2 Sex 6L S CITY D 3 City 10L S PHONE_NUMBER D 4 Phone Number 10L S TAPES_RENTED D 5 Rentals 10L MV P_INFO TAPE_NAME D 6 Tape Names 10L MV P_INFO P_INFO 8 records listed PH TAPE_NAME TAP ES_RENTED 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
54 Different attributes at the same location can have different formats and display names. IDESC and VIRTUAL are interchangeable. sql> CREATE TABLE ST_EXAM sql> (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 Using UniData SQL
55 Examining Table Definitions Once 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 UniData SQL creates to serve as the key to each record. The location is 0. You cannot change it; however, you can define an alternative display name or the format for the attribute. 3-19
56 When you insert data into the table, you must supply a unique value for attribute of each record. sql> LISTDICT TYP LOC CONV NAME FORMAT SM ASSOC D 0 ST_EXAM 10L S LNAME D 1 Last Name 15T S FNAME D 2 First Name 15L S MAJOR D 3 Major 4L S MINOR D 4 Minor 4L S ADVISOR D 5 Advisor 8L S SEMESTER D 6 Term 4L MV CGA COURSE_NBR D 7 Crs# 5L MS CGA COURSE_GRD D 8 Grd 3L MS CGA CGA PH TEACHER COURS E_NAME COURSE _HOUR COURSE_ GRD COURSE_NBR COURSE_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 M GPA1 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 Using UniData SQL
57 Modifying Table Definitions UniData 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 Keywords Keywords of the ALTER TABLE statement are listed in the following table. Keyword ADD MODIFY DELETE MODULO Description Add an attribute definition to a table. Change information about an attribute in a table. Delete an attribute from a table. Change the modulo size of a table. ALTER TABLE Keywords Note: Although you can use UniEntry to modify, add, or delete attribute definitions, we recommend 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
58 Adding Attributes The 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):y Deleting file D_ST_EXAM. Deleting file ST_EXAM Using UniData SQL
59 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/1024 Hash type = 0 Create file ST_EXAM, modulo/1,blocksize/1024 Hash type = 0 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 TYP LOC CONV NAME FORMAT SM ASSOC D 0 ST_EXAM 10L S LNAME D 1 Last Name 15T S FNAME D 2 First Name 15L S MAJOR D 3 Major 4L S MINOR D 4 Minor 4L S ADVISOR D 5 Advisor 8L S SEMESTER D 6 Term 4L MV CGA COURSE_NBR D 7 Crs# 5L MS CGA COURSE_GRD D 8 Grd 3L MS CGA CGA PH COURSE_GRD COURSE_NBR SEMESTER 10 records listed 3-23
60 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 TYP LOC CONV NAME FORMAT SM ASSOC D 0 ST_EXAM 10L S LNAME D 1 Last Name 15T S FNAME D 2 First Name 15L S MAJOR D 3 Major 4L S MINOR D 4 Minor 4L S ADVISOR D 5 Advisor 8L S SEMESTER D 6 Term 4L MV CGA COURSE_NBR D 7 Crs# 5L MS CGA COURSE_GRD D 8 Grd 3L MS CGA BIRTHDATE D 9 D4,M Birth Day 10L S DYA3 CGA 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)? y field -- MINOR exists. do you want to replace this column (y/n)? y 2 fields added Using UniData SQL
61 Modifying Tables Use 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 Keyword The 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 Names Remember the following when naming associations: 3-25
62 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 Association The 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) Using UniData SQL
63 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 TYP LOC CONV NAME FORMAT SM ASSOC D 0 ST_EXAM 10L S LNAME D 1 Last Name 15T S FNAME D 2 First Name 15.T S MAJOR D 3 Major 6L S MINOR D 4 Mino 4L S ADVISOR D 5 Tutor Name 12L S SEMESTER D 6 Term 4L MS ST_INFO_2 COURSE_NBR D 7 Crs# 5L MS ST_INFO_2 COURSE_GRD D 8 Grd 3L MS CGA BIRTHDATE D 9 D4,M Birth Day 10L S DYA3 CGA PH COURSE_GRD ST_INFO_2 PH COURSE_NBR SE MESTER 12 records listed 3-27
64 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; CATEGORY: CAT OLD TYP LOC CONV NAME FORMAT SM ASSOC D 0 ST_EXAM 10L S LNAME D 1 Last Name 15T S FNAME D 2 First Name 15.T S MAJOR D 3 Major 6L S MINOR D 4 Minor 4L S ADVISOR D 5 Tutor Name 12L S SEMESTER D 6 Term 4L MV CGA COURSE_NBR D 7 Crs# 5L MS COURSE_GRD D 8 Grd 3L MS CGA BIRTHDATE D 9 D4,M Birth Day 10L S DYA3 CGA PH SEMESTER COUR SE_GRD COURS E_NBR 11 records listed Deleting Attributes You can delete attribute definitions from the dictionary with the DELETE keyword. You cannot use the ALTER TABLE DELETE statement to delete attribute. Syntax: ALTER TABLE table_ name DELETE (attribute_name [, attribute_name,]...) 3-28 Using UniData SQL
65 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. 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 EXAMPLE sql> (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/1024 Hash type = 0 Create file EXAMPLE, modulo/1,blocksize/1024 Hash type = 0 Added "@ID", the default record for UniData to DICT EXAMPLE. 3 fields added. Create file EXAMPLE, modulo/1,blocksize/1024 Create file EXAMPLE, modulo/1,blocksize/1024 sql> LISTDICT TYP LOC CONV NAME FORMAT SM ASSOC D 0 EXAMPLE 10L S A D 1 10R MV P1 B D 2 10R MV P1 C D 3 10R S P1 PH B A 5 records listed 3-29
66 Delete the Attributes Next, when you delete attributes A and B from the table, you can see that the dictionary contains only the UniData 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 TYP LOC CONV NAME FORMAT SM ASSOC D 0 EXAMPLE 10L S C D 3 10R S 2 records listed Resizing Tables When 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 on UNIX or Administering UniData on Windows Platforms for an explanation of how to size the modulo Using UniData SQL
67 Removing Tables When 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):y Deleting 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
68 Indexing Tables UniData 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 Indexes When 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 Using UniData SQL
69 Syntax: CREATE INDEX index_name ON table_name (attribute_name); The key attribute, designated by attribute_name, could be any V- or I-type singlevalued 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 attributes 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): "NAME_NDX" created Building "NAME_NDX" 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
70 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
71 Predicate IN BETWEEN LIKE Description Specifies attribute values within a set of values. Specifies attribute values within a range. Applies conditions that involve a pattern (except when the pattern begins with a wild card). Operators That Use Indexes (continued) 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): "NAME_NDX" created Building "NAME_NDX" 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_RENTED sql> FROM CUSTOMER sql> 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. 3-35
72 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" created One "*" represents 1000 records Building "TAPE_NAME_NDX" 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_PRICE sql> 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
73 Chapter 4: The Command Stack Chapter 4 Introduction to the Command Stack Using the Command Stack Command Stack Operators Appending to an Existing Statement Changing Statements in the Stack Deleting Statements in the Stack Inserting a Statement Line into the Stack Listing Statements in the Stack Recalling a Statement in the Stack Storing Statements for Later Use
74 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
75 Introduction to the Command Stack The 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
76 Using the Command Stack UniData 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 Operators The 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.A#.C#.D#.I# Description Appends text to the end of a statement at the specified line number. Changes one string to another string at the specified line number. Deletes a statement from the stack at the specified line number. 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
77 Operator.S#.X# Description Saves stack lines in the VOC as a name. Executes a statement at the specified line number..? Displays online help, which provides a listing of the above functions. Command Stack Operators (continued) Appending to an Existing Statement Use 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. 4-5
78 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,CITY sql> FROM CUSTOMER WHERE CITY='Denver'; Customer Name City Frobisher, Denver Kamal Steven Spender Denver... sql>.a2,tapes_rented SELECT NAME,CITY,TAPES_RENTED sql>.l2 2* SELECT NAME,CITY,TAPES_RENTED 1 FROM CUSTOMER WHERE CITY='Denver'; Changing Statements in the Stack Use 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 CUSTEOMER sql> WHERE CITY='Denver'; 4-6 Using UniData SQL
79 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/cust SELECT NAME,CITY FROM CUSTOMER sql>.l2 2* SELECT NAME,CITY FROM CUSTOMER 1 WHERE CITY= Denver ; Deleting Statements in the Stack Use 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
80 After making the modifications, the example uses the.l operator to list the stack for the result: sql> SELECT NAME,CITY,TAPES RENTED FROM CUSTOMER sql> UNNEST TAPES_RENTED sql>.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 Stack Use 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_RENTED sql> FROM CUSTOMER sql> WHERE CITY='Denver'; Customer Name City Tapes Frobisher, Denver Kamal Steven Spender Denver V sql>.i2 UNNEST TAPES_RENTED UNNEST TAPES_RENTED sql>.l4 4* SELECT NAME,CITY,TAPES_RENTED 3 FROM CUSTOMER 2 UNNEST TAPES_RENTED 1 WHERE CITY='Denver'; 4-8 Using UniData SQL
81 Listing Statements in the Stack Use 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 Statements for Later Use on page 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,CITY sql> FROM CUSTOMER sql> WHERE CITY='Denver'; Customer Name City Frobisher, Denver Kamal Steven Spender Denver.. sql>.l3 3* SELECT NAME,CITY 2 FROM CUSTOMER 1 WHERE CITY='Denver'; Recalling a Statement in the Stack Use the.r operator to recall the position of a statement in the stack to the first position without executing the command. 4-9
82 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>.r5 UNNEST TAPES_RENTED sql>.l5 5 WHERE CITY='Denver'; 4*SELECT NAME,CITY 3 FROM CUSTOMER 2 WHERE CITY='Denver'; 1*UNNEST TAPES_RENTED Storing Statements for Later Use Use 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
83 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 2 save 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 qcity sql>.r qcity qcity is not a VOC item Executing Statements Use 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
84 The following example reexecutes a statement by first listing the command stack, then reexecuting a statement: sql> SELECT NAME,CITY FROM CUSTOMER sql> WHERE CITY='Denver'; Customer Name City Frobisher, Denver Kamal Steven Spender Denver.. sql>.l2 2*SELECT NAME,CITY FROM CUSTOMER 1 WHERE CITY='Denver'; sql>.x2 Customer Name City Frobisher,Kamal Denver Steven Spender Denver.. Doodle, Polly W. Denver LaRue, Karma Denver Smith, Leif Denver 6 records listed 4-12 Using UniData SQL
85 Chapter 5: Manipulating Data Chapter 5 Inserting Data into a Table The INSERT Command Inserting a Single Record Inserting Data into Specified Attributes Inserting Empty Strings and the Null Value Inserting a Record with Multiple Values Copying Multiple Records from Other Tables Updating Data in a Table The UPDATE Command Updating Specific Attributes Updating Multiple Records Updating Multivalued Attributes Adding Values and Subvalues Deleting Data from a Table The DELETE Command Deleting a Set of Records Deleting All Records in a Table Deleting Data in Multivalued Attributes Restoring the Database
86 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
87 Inserting Data into a Table You 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 Command The 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 into 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
88 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 Record An 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 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 multisubvalued 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 5-4 Using UniData SQL
89 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. 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 Attributes You 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 attributes. 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 , and his major is Computer Science. All other information 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 (" ","Bond","James","CS"); COMMIT complete. 1 record(s) created. attribute must be included in the attribute list, and you must assign a non-null value to attribute in the VALUES clause. Inserting Empty Strings and the Null Value With null value handling on, the null value is considered to be unknown and is represented by the ASCII value selected for your language group. For further information, see Chapter 6, Chapter 6: The SELECT Statement. 5-5
90 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 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". 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 COURSES sql> 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 N sql> SELECT * FROM COURSES = "CS750"; COURSES Course Name Credi Teacher CS750 UniData Model N 1 records listed 5-6 Using UniData SQL
91 Inserting a Record with Multiple Values Insert values by separating them with value marks: }. Associated multivalued attributes 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. For further information on value and subvalue marks, see Chapter 1, Chapter 1: Introduction to UniData SQL. The following example inserts values and subvalues into the STUDENT table: sql> INSERT INTO STUDENT VALUES (" ","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 STUDENT Last Name First Name Majo Mino Advisor Term Crs # GD 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
92 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. 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 VALUES sql> ( ,"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 LIKE "777%" STUDENT Last Name First Name Majo Mino Advisor Term Crs # GD Kline John PY MA Jones SP87 PY100 A CS150 MA200 B 1 records listed Copying Multiple Records from Other Tables UniData 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. 5-8 Using UniData SQL
93 You cannot insert into the table from which you are selecting attributes in the SELECT clause. The SELECT clause can contain any valid query_spec as described in Chapter 6, 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 sql> FROM CUSTOMER WHERE CITY = "Denver"; COMMIT completed. 6 records created. 5-9
94 Updating Data in a Table This section provides examples of the following: Updating specific attributes. Updating multiple records. Updating multivalued attributes. Adding values and subvalues. The UPDATE Command Use the UPDATE statement to modify the contents of a table. You cannot update 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
95 Parameters The following table describes each parameter of the syntax. Parameter table_spec ID_list SET ADD VALUE ADD SUBVALUE Description Name of the table, view, or subtable to be updated. 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. Replaces the values in one or more attributes of records satisfying WHERE search_condition. You cannot include delimiters to set values or subvalues. 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. UPDATE Parameters 5-11
96 Parameter attribute_name expression WHERE search_condition Description 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_name table_label.attribute_name Any combination of attribute names, constants, arithmetic operators, and UniData SQL functions that together return a value that determines the value to store in the attribute. You can set an attribute to the null value like this: attribute_name = NULL. Updates attribute values that meet the criteria specified in search_condition. WHERE evaluates values and multisubvalues as if they have been unnested. search_condition takes the form: attribute_name/expression rel_op attribute_name/expression For 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. UPDATE Parameters (continued) Updating Specific Attributes Use the UPDATE command and the SET keyword to assign one value to a singlevalued, multivalued, or multi-subvalued attribute. The following example raises Otis s salary by $2,000. sql> UPDATE STAFF SET SAL=SAL+2000 sql> WHERE LNAME = "Otis"; COMMIT complete. 1 record(s) updated Using UniData SQL
97 Updating Multiple Records Use 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 sql> WHERE LNAME IN (SELECT ADVISOR FROM STUDENT) sql> AND TITLE!= "Prof"; COMMIT complete. 2 record(s) updated. Updating Multivalued Attributes Use 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" WHERE sql> 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. Adding Values and Subvalues Use 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. 5-13
98 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"; STUDENT Last Name First Name Majo Mino Advisor Term Crs # GD 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 CS326 1 records listed 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 Using UniData SQL
99 This example adds three new courses to the spring 1994 semester record for jojo Smith: sql> UPDATE STUDENT ADD SUBVALUE sql> 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"; STUDENT Last Name First Name Majo Mino Advisor Term Crs # GD Smith jojo CS FA Eades SP94 FA100 B FA101 D FA102 C MA101 I 1 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 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" (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. 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 = NULL sql> WHERE FNAME = "jojo" AND COURSE_NBR = "MA101"; 1 record(s) updated. sql> SELECT * FROM STUDENT WHERE FNAME = "jojo"; STUDENT Last Name First Name Majo Mino Advisor Term Crs # GD Smith jojo CS FA Eades SP94 FA100 B FA101 D FA102 C MA101 N 1 records listed 5-15
100 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 = NULL sql> WHERE LNAME = "Smith" AND FNAME = "jojo"; 1 record(s) updated. sql> SELECT * FROM STUDENT WHERE FNAME = "jojo"; STUDENT Last Name First Name Majo Mino Advisor Term Crs # GD Smith jojo CS FA Eades SP94 FA100 B FA101 D FA102 C MA101 N N 1 records listed 5-16 Using UniData SQL
101 Deleting Data from a Table This section provides examples of the following: Deleting a record Deleting a set of records Deleting all records Deleting data in multivalued attributes The DELETE Command The 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 FROM table_spec Description Specifies the table, subtable, or view from which records are to be deleted. DELETE Parameters 5-17
102 Parameter table_label ID_list WHERE search_condition Description Specifies an alias for a table from which records are to be deleted. 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. 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. DELETE Parameters (continued) Example The next example shows how to delete the CS700 record from the COURSES table: sql> DELETE FROM COURSES COMMIT complete. 1 record(s) deleted or updated Using UniData SQL
103 Deleting a Set of Records Use 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, Chapter 6: The SELECT Statement. Since you cannot recover data once you delete it, we recommend 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" or sql> 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-19
104 3. Finally, select data from the CUSTOMER table to see how the customer data changed: sql> SELECT NAME,CITY,NUM_RENTALS FROM CUSTOMER; Customer Name City RENTALS Jones, Bob Arvada 7 Frobisher, Denver 33 Kamal Steven Spender Denver 3 Jamieson, Dale Seattle 8 Chase, Carl Kenosha 11 Wagner, Pat Denver 4 Wagner, Esther Kenosha 5 Doodle, Polly Denver 3 W.... 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 Table If you do not specify a WHERE clause or a list (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 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 Attributes You 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 Using UniData SQL
105 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_GRD sql> FROM STUDENT sql> WHERE LNAME="Jenral"; Last Name Term Crs # GD Jenral SP86 PY100 A CS101 B FA86 PY200 B CS201 A CS300 C 1 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"; Last Name Term Crs # GD Jenral SP86 PY100 A CS101 B FA86 PY200 B CS300 C 1 records listed 5-21
106 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. 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 STUDENT sql> WHERE LNAME="Jenral"; Last Name Term Crs # GD Jenral FA86 PY200 B CS300 C 1 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 multisubvalued attribute satisfy the condition, the corresponding values of the associated multivalued attributes are also deleted Using UniData SQL
107 Restoring the Database Before 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-2000 sql> 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-3000 sql> WHERE LNAME IN (SELECT ADVISOR sql> FROM STUDENT) AND TITLE!="Prof"; COMMIT complete. 2 record(s) updated. The next example restores the COURSES database: sql> DELETE FROM COURSES = "CS750"; COMMIT complete. 1 record(s) deleted or updated. The next example restores the STUDENT database: sql> DELETE FROM STUDENT = " " sql> = " " = " "; 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 CUSTOMER sql> SELECT * FROM TEMP_CUST; COMMIT complete. 7 record(s) created. 5-23
108 Chapter 6: The SELECT Statement Chapter 6 Retrieving Data with SELECT Separation Characters Writing Simple Queries Selecting Rows from the Result Table Selecting Specific Attributes Selecting All Attributes Selecting or Excluding Duplicate Values Selecting Multivalued Attributes Selecting Multi-Subvalued Attributes Selecting Virtual Attributes Selecting Records by Specifying Record IDs Selecting Tables with FROM Qualifying Attribute Names with Table Labels Joining Tables Types of Joins How to Join Tables Inner Joins Outer Joins Unnesting Query Results with UNNEST How to Unnest Unnesting Multivalued Attributes Unnesting Multi-Subvalued Attributes Unnesting Multivalued and Multi-Subvalued Attributes Selecting Records with WHERE Using Greater Than in a WHERE Clause Combining Selection Criteria with AND Combining Selection Criteria with OR
109 6-2 Using UniData SQL Combining the AND and OR Operators Selecting Values That Do Not Meet Conditions Applying Conditions to Every Value Selecting Records That Match Patterns Searching for Patterns with the LIKE Operator Using Range Specifiers Using Wild Cards in Patterns Dictionary Conversions and the LIKE Operator LIKE Clauses and Strings Incorrect Pattern Specification The IN Operator Selecting Records within a Range Sorting Query Results Sorting in Ascending Order Sorting in Descending Order Sorting by Multiple Attributes Combining Ascending and Descending Operators Sorting Based on Multivalued Attributes Unnesting and Sorting Based on Multivalued Attributes Unnesting an Association and Sorting Sorting and Unnesting Subqueries Combining Multiple Queries into a Single Query Using ANY, ALL, and IN with Subqueries Writing Compound Queries Passing Data from Query to Subquery Group Functions Selecting Summary Information from One Group Multiple Group Functions Correct and Incorrect Group Function Use Using DISTINCT and COUNT with Attributes Writing Column Headings Selecting Summary Information from Multiple Groups Including Multiple Attribute Names in a GROUP BY Clause Specifying a Search Condition for Groups Group Functions with Multivalued Attributes
110 6-3 Using UniData SQL Expressions and Functions Arithmetic Expressions Arithmetic Functions Arithmetic Expressions and Functions in Group Functions Character String Functions Date Functions
111 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
112 Retrieving Data with SELECT The 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 Using UniData SQL
113 Syntax Query 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
114 Separation Characters Separate 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: We recommend that you not enter more characters per line than your screen displays. 6-7 Using UniData SQL
115 Writing Simple Queries This 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 attributes All attributes Distinct values Singlevalued, multivalued, and/or multi-subvalued attributes Virtual attributes Record IDs Selecting Rows from the Result Table The 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 Attributes In Chapter 3, 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
116 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 2 Customer Name Phone Total Re Fellini, J. 14 Hoboken Jones, Freddie (312) Valenzuela, (414) Carmen LaRue, Karma 2 Darrell Corden (415) Smith, Leif (303) Jones, Mable (414) Best, George (555) Barrie, Dick (414) Boorman, Rick (312) Partner, Bonnie (303) Byles, Marcy (913) records listed Selecting All Attributes You 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 Using UniData SQL
117 Selecting Attribute Names The following example uses the first method to display the data from the COURSES table where the attributes Name, Credits, and Teacher: sql> sql> FROM COURSES; COURSES Course Name Credi Teacher FA120 Finger Painting 5 Fried PY140 Abnornal Psychology 5 Masters PE100 Golf - I 3 Fisher CS105 Database Design 3 Gibson MA101 Math Principals 3 Otis FA231 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
118 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; COURSES Course Name Credi Teacher FA120 Finger Painting 5 Fried PY140 Abnornal Psychology 5 Masters PE100 Golf - I 3 Fisher CS105 Database Design 3 Gibson MA101 Math Principals 3 Otis FA231 Photography Practicum 3 Fried PE220 Racquetball 3 Fisher MA221 Calculus - II 5 Otis EG110 Engineering Principles 5 Carnes... Note: An asterisk only selects data attributes and not virtual or phrase attributes. Selecting or Excluding Duplicate Values The 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; City Arvada Denver Denver Seattle Kenosha Denver Kenosha Denver New York Hawthorne records listed 6-11 Using UniData SQL
119 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; City Arvada Boulder Chicago Denver Dodge City El Paso Golden Hawthorne Kenosha Lakewood Los Angele s Milwaukee New York Overton Rutherford San Jose Seattle 17 records listed Selecting Multivalued Attributes The 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
120 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; Customer Name Tapes Date Out Jones, Bob V /24/94 Frobisher, Kamal Steven Spender Jamieson, Dale V /24/94 Chase, Carl V /20/94 V /20/94 V /21/94 Wagner, Pat Wagner, Esther Doodle, Polly W. Fischer, Carrie V110 04/23/94... Byles, Marcy 29 records listed Selecting Multi-Subvalued Attributes The following example demonstrates how UniData SQL selects multisubvalued 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 Using UniData SQL
121 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_GRD sql> FROM STUDENT; Last Name Term Crs # GD Smith FA93 CS130 A CS100 B PY100 B SP94 CS131 B CS101 B PE220 A Smith SP94 FA100 B Martin SP94 PY100 C Offenbach... Muller 6 records listed PE100 C FA93 CS104 D MA101 C FA100 C FA93 FA120 A FA230 C HY101 C SP94 FA121 A FA231 B HY102 I Selecting Virtual Attributes Chapter 3, Chapter 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
122 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; Customer Name Tapes Video Tape Name Jones, Bob V4341 Z Frobisher, Kamal Steven Spender Jamieson, Dale V Chase, Carl V8481 'Round Midnight V1254 Flash Gordon V4951 American Graffiti Wagner, Pat Wagner, Esther Doodle, Polly W.... Page 3 Customer Name Tapes Video Tape Name Byles, Marcy 29 records listed B2297 Love Story Selecting Records by Specifying Record IDs If 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 Using UniData SQL
123 The following example shows you one way to select records with IDs 1 and 11 from the CUSTOMER table: sql> sql> FROM CUSTOMER "1" "11"; Cust Customer Name Tapes Smith, Harry V2001 V5004 V Best, George B records listed The following alternative syntax is equally efficient: or sql> SELECT NAME,TAPES_RENTED FROM CUSTOMER sql> IN ("1", "11"); sql> SELECT NAME,TAPES_RENTED FROM CUSTOMER sql> = "1" = "11"; 6-16
124 Selecting Tables with FROM The FROM clause of the SELECT statement determines the tables accessed. You can select up to eight tables in a single FROM clause. Syntax 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...] ) }...]...] 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 Labels When 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 Using UniData SQL
125 Abbreviating Table Labels Adding qualifying table labels can make statements 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 Y You 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 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.DEPT sql> FROM STAFF X, STAFF Y sql> WHERE X.LNAME = Y.SUPERVISOR; Supervis Dept Employee Dept Fried BUS James PSY Fried BUS Carnes ENG Fried BUS Eades FA Fried BUS Fisher BUS Fried BUS Gibson SPA James PSY Masters PSY James PSY Aaron PSY Eades FA Otis FA 8 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 Tables A 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: 6-18
126 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. 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 Joins You 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 Using UniData SQL
127 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. 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. 6-20
128 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 Tables Joins 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 implementation 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-21 Using UniData SQL
129 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 ORDERS UNNEST PRODUCT_NO WHERE EPRICE < 100; Name Product Nu Company Glen Asakawa Pearl Security Alicia Rodriguez Macro Print Inc, Sharon Guo Spence Design Sharon Guo Ian Samuel records listed Spence Design Wilson Instruments 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-22
130 Operator Description Joins Based on an Equal Condition <= Less than or equal to.!> Not greater than.!< Not less than. Relational Operators (continued) 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 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_price from CUSTOMER a join TAPES b on a.tapes_rented = b.@id unnest a.tapes_rented; select a.@id, a.name, a.tapes_rented, a.tape_cost, b.@id, b.rental_price from CUSTOMER a, TAPES b unnest a.tapes_rented where a.tapes_rented = b.@id; 6-23 Using UniData SQL
131 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_PRICE FROM TAPES X,TAPES Y WHERE X.RENTAL_PRICE >Y.RENTAL_PRICE AND Y.NAME LIKE "Blue..."; select X.NAME, X.RENTAL_PRICE, Y.NAME, Y.RENTAL_PRICE from TAPES X INNER JOIN TAPES Y on X.RENTAL_PRICE > Y.RENTAL_PRICE unnest X.RENTAL_PRICE where 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 Joins Inner 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 Condition Suppose 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-24
132 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.name, a.tapes_rented, a.tape_cost, b.name from CUSTOMER a INNER JOIN TAPES b ON a.tapes_rented = b.@id unnest a.tapes_rented; select a.@id, a.name, a.tapes_rented, a.tape_cost, b.@id, b.name from CUSTOMER a, TAPES b unnest a.tapes_rented where a.tapes_rented = b.@id CUSTOMER Customer Name Tapes Rental C TAPES Tape Name Chase, Carl V8481 $6.75 V8481 'Round Midnight 100 Jones, Samuel V8481 $6.75 V8481 'Round Midnight 11 Best, George B2297 $2.50 B2297 Love Story 2 Partner, Bonnie B2297 $2.50 B2297 Love Story 8 Jones, Mable V4499 $4.54 V4499 Psycho 1 Smith, Harry V8181 $5.50 V8181 Catch 22 5 Barrie, Dick V996 $4.54 V996 Citizen Kane 2 Partner, Bonnie B914 $1.06 B914 Tammy 15 James, Bob V2001 $3.75 V2001 Blue Velvet 1 Smith, Harry V2001 $3.75 V2001 Blue Velvet 1 Smith, Harry V5004 $4.40 V5004 Journey Abroad 10 Faber, Harry V5151 $3.54 V5151 To Kill A Mockingbird 12 Jamieson, Dale V6670 $6.75 V Bowie, David V9961 $5.05 V9961 The Stalker 3 Fischer, Carrie V110 $2.52 V110 Girl Friday 100 Jones, Samuel V1254 $3.15 V1254 Flash Gordon 9 Chase, Carl V1254 $3.15 V1254 Flash Gordon 6 Jones, Bob V4341 $4.54 V4341 Z 9 Chase, Carl V4951 $2.50 V4951 American Graffiti Page 2 CUSTOMER Customer Name Tapes Rental C TAPES Tape Name Jones, Freddie V9431 $4.50 V9431 Help 8 Jones, Mable V1249 $3.54 V1249 Gone With The Wind 21 records listed Inner Joins Based on a Not Equal Condition Inner 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-25 Using UniData SQL
133 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.SAL sql> FROM STAFF X,STAFF Y sql> WHERE Y.SAL >X.SAL AND X.LNAME = "Fisher"; Last Nam Salary Last Nam Salary Fisher 31,200 James 32,500 Fisher 31,200 Masters 35,800 Fisher 31,200 Eades 42,000 Fisher 31,200 Fried 98,000 4 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.name from CUSTOMER a INNER JOIN TAPES b ON a.tapes_rented = b.@id unnest a.tapes_rented order by b.name; CUSTOMER Customer Name Tapes Rental C TAPES Tape Name Jones, Samuel V8481 $6.75 V8481 'Round Midnight 9 Chase, Carl V8481 $6.75 V8481 'Round Midnight 12 Jamieson, Dale V6670 $6.75 V Chase, Carl V4951 $2.50 V4951 American Graffiti 15 James, Bob V2001 $3.75 V2001 Blue Velvet 1 Smith, Harry V2001 $3.75 V2001 Blue Velvet records listed And this statement sorts by customer name: select a.@id, a.name, a.tapes_rented, a.tape_cost, b.@id, b.name from CUSTOMER a INNER JOIN TAPES b ON a.tapes_rented = b.@id unnest a.tapes_rented order by a.name; CUSTOMER Customer Name Tapes Rental C TAPES Tape Name Barrie, Dick V996 $4.54 V996 Citizen Kane 11 Best, George B2297 $2.50 B2297 Love Story 4 Bowie, David V9961 $5.05 V9961 The Stalker 9 Chase, Carl V1254 $3.15 V1254 Flash Gordon 9 Chase, Carl V4951 $2.50 V4951 American Graffiti 9 Chase, Carl V8481 $6.75 V8481 'Round Midnight records listed 6-26
134 Outer Joins You 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 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. 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-27 Using UniData SQL
135 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_price from CUSTOMER a LEFT JOIN TAPES b ON a.tapes_rented = b.@id unnest a.tapes_rented; CUSTOMER Customer Name Tapes Rental C TAPES Retail C 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 B Partner, Bonnie B2297 $2.50 B Partner, Bonnie B914 $1.06 B Fischer, Carrie V110 $2.52 V Page 3 CUSTOMER Customer Name Tapes Rental C TAPES Retail C Darrell Corden V Barrie, Dick V996 $4.54 V Bowie, David V9961 $5.05 V records listed 6-28
136 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 Using UniData SQL
137 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.name from CUSTOMER a right join TAPES b ON a.tapes_rented = b.@id unnest a.tapes_rented; Customer Name Tapes Rental C TAPES Tape Name Best, George B2297 $2.50 B2297 Love Story Partner, Bonnie B2297 $2.50 B2297 Love Story Partner, Bonnie B914 $1.06 B914 Tammy V1077 Sleuth Fischer, Carrie V110 $2.52 V110 Girl Friday V1231 Scaramouche Jones, Mable V1249 $3.54 V1249 Gone With The Wind Chase, Carl V1254 $3.15 V1254 Flash Gordon Jones, Samuel V1254 $3.15 V1254 Flash Gordon James, Bob V2001 $3.75 V2001 Blue Velvet Smith, Harry V2001 $3.75 V2001 Blue Velvet Jones, Bob V4341 $4.54 V4341 Z Jones, Mable V4499 $4.54 V4499 Psycho V4637 If... Chase, Carl V4951 $2.50 V4951 American Graffiti Smith, Harry V5004 $4.40 V5004 Journey Abroad Faber, Harry V5151 $3.54 V5151 To Kill A Mockingbird Jamieson, Dale V6670 $6.75 V V7456 A Clockwork Orange Page 2 Customer Name Tapes Rental C TAPES Tape Name Smith, Harry V8181 $5.50 V8181 Catch 22 Chase, Carl V8481 $6.75 V8481 Round Midnight Jones, Samuel V8481 $6.75 V8481 Round Midnight Jones, Freddie V9431 $4.50 V9431 Help Barrie, Dick V996 $4.54 V996 Citizen Kane Bowie, David V9961 $5.05 V9961 The Stalker 25 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 Join A 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-30
138 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.name, a.tapes_rented, a.tape_cost, b.name from CUSTOMER a FULL JOIN TAPES b ON a.tapes_rented = b.@id unnest a.tapes_rented; CUSTOMER Customer Name Tapes Rental C TAPES Tape Name Darrell Corden 190 Belafonte, Harry 200 Smith, Leif 201 Wagner, Pat 202 Grundy, Robin 203 Boorman, Rick 204 Frobisher, Kamal... Page 2 CUSTOMER Customer Name Tapes Rental C TAPES Tape Name Best, George B2297 $2.50 B2297 Love Story 2 Partner, Bonnie B2297 $2.50 B2297 Love Story... V4637 If... 9 Chase, Carl V4951 $2.50 V4951 American Graffiti 1 Smith, Harry V5004 $4.40 V5004 Journey Abroad 10 Faber, Harry V5151 $3.54 V5151 To Kill A Mockingbird 12 Jamieson, Dale V6670 $6.75 V V7456 A Clockwork Orange Page 3 CUSTOMER Customer Name Tapes Rental C TAPES Tape Name Smith, Harry V8181 $5.50 V8181 Catch Jones, Samuel V8481 $6.75 V8481 'Round Midnight 9 Chase, Carl V8481 $6.75 V8481 'Round Midnight 7 Jones, Freddie V9431 $4.50 V9431 Help 5 Barrie, Dick V996 $4.54 V996 Citizen Kane 4 Bowie, David V9961 $5.05 V9961 The Stalker 40 records listed 6-31 Using UniData SQL
139 Unnesting Query Results with UNNEST Within 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 multivalues), but not unnesting the multivalues. Note: The UNNEST clause can process 10,240 values in a multivalued or multisubvalued attribute, or in all associations for the unnested record. Syntax [UNNEST [NL1 NL2 NL_ALL] {association_name [attribute_name [,attribute_name]]} How to Unnest You 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 Attributes Unnesting Multi-Subvalued Attributes Unnesting Multivalues and Multi-Subvalued Attributes 6-32
140 See the UniData SQL Commands Reference for examples of UNNEST with options NL1, NL2, and NL_ALL. Unnesting Multivalued Attributes Unnesting multivalues results in single values being repeated. If any multisubvalued 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_attribute UNNEST NL1 association UNNEST NL1 mv_attribute UNNEST NL1 ms_attribute UNNEST NL1 mv_attribute, ms_attrib UNNEST NL_ALL mv_attribute 6-33 Using UniData SQL
141 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 and NAME being unnested. sql> sql> FROM STUDENT sql> UNNEST SEMESTER; STUDENT Last Name Term Crs # Smith FA93 CS130 CS100 PY Smith SP94 CS131 CS101 PE Smith SP94 FA Martin SP94 PY100 PE Offenbach FA93 CS104 MA101 FA Offenbach SP94 CS105 MA102 PY Miller FA93 EG110 MA220 PY Miller SP94 EG140 EG240 Page 2 STUDENT Last Name Term Crs # MA Muller FA93 FA120 FA230 HY Muller SP94 FA121 FA231 HY records listed 6-34
142 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,SEMESTER sql> FROM STUDENT sql> UNNEST SEMESTER; Last Name Majo Term Smith CH FA93 Smith CH SP94 Smith CS SP94 Martin PY SP94 Offenbach CS FA93 Offenbach CS SP94 Miller EG FA93 Miller EG SP94 Muller FA FA93 Muller FA SP94 10 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; Last Name Majo Term Smith CH FA93 SP94 Smith CS SP94 Martin PY SP94 Offenbach CS FA93 SP94 Miller EG FA93 SP94 Muller FA FA93 SP94 6 records listed 6-35 Using UniData SQL
143 Unnesting Multi-Subvalued Attributes Unnesting 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: UNNEST ms_attribute UNNEST NL2 association_name UNNEST NL2 ms_attribute UNNEST NL2 mv_attribute, ms_attribute Note: The syntax UNNEST NL2 mv_attribute is invalid. 6-36
144 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 LNAME) are not repeated. sql> sql> FROM STUDENT sql> UNNEST COURSE_NBR; STUDENT Last Name Term Crs # GD Smith FA93 CS130 A FA93 CS100 B FA93 PY100 B SP94 CS131 B SP94 CS101 B SP94 PE220 A Smith SP94 FA100 B Martin SP94 PY100 C SP94 PE100 C Offenbach FA93 CS104 D FA93 MA101 C FA93 FA100 C SP94 CS105 B SP94 MA102 C SP94 PY100 C Miller FA93 EG110 C FA93 MA220 B FA93 PY100 B SP94 EG140 B SP94 EG Muller FA93 FA120 A FA93 FA230 C FA93 HY101 C SP94 FA121 A SP94 FA231 B SP94 HY102 I 6 records listed Unnesting Multivalued and Multi-Subvalued Attributes Unnesting 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_name UNNEST mv_attribute, ms_attribute UNNEST NL_ALL ms_attribute 6-37 Using UniData SQL
145 UNNEST 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 multisubvalued attribute value even though only one of the multi-subvalued attributes is listed in the UNNEST clause. 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; Last Name Term Crs # GD Smith FA93 CS130 A Smith FA93 CS100 B Smith FA93 PY100 B Smith SP94 CS131 B Smith SP94 CS101 B Smith SP94 PE220 A Offenbach FA93 CS104 D Offenbach FA93 MA101 C Offenbach FA93 FA100 C Offenbach SP94 CS105 B Offenbach SP94 MA102 C Offenbach SP94 PY100 C Miller FA93 EG110 C Miller FA93 MA220 B Miller FA93 PY100 B... Muller FA93 FA120 A Muller FA93 FA230 C Muller FA93 HY101 C Muller SP94 FA121 A Muller SP94 FA231 B Muller SP94 HY102 I 29 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-38
146 This example includes an association in an UNNEST clause to unnest the semester (multivalued attribute), course number, and course grade (multisubvalued attributes) for each student (singlevalued attribute). sql> sql> FROM STUDENT sql> UNNEST CGA; STUDENT Last Name Term Crs # GD Smith FA93 CS130 A Smith FA93 CS100 B Smith FA93 PY100 B Smith SP94 CS131 B Smith SP94 CS101 B Smith SP94 PE220 A Smith SP94 FA100 B Martin SP94 PY100 C Martin SP94 PE100 C Offenbach FA93 CS104 D Offenbach FA93 MA101 C Offenbach FA93 FA100 C Offenbach SP94 CS105 B Offenbach SP94 MA102 C Offenbach SP94 PY100 C Miller FA93 EG110 C Miller FA93 MA220 B Miller FA93 PY100 B Miller SP94 EG140 B Miller SP94 EG240 B Muller FA93 FA230 C Muller FA93 HY101 C Muller SP94 FA121 A Muller SP94 FA231 B Muller SP94 HY102 I 27 records listed 6-39 Using UniData SQL
147 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"; Last Name Crs # GD Smith CS130 A Smith PE220 A Muller FA120 A Muller FA121 A 4 records listed 6-40
148 Selecting Records with WHERE Within 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 Types of WHERE Clauses WHERE COUNTRY LIKE "A%" 6-41 Using UniData SQL
149 Type of WHERE Clause Keywords/Operators Notes/Examples 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. Types of WHERE Clauses (continued) Using Greater Than in a WHERE Clause The next example uses the greater than operator to show which customers have rented more than 15 tapes: sql> SELECT NAME,NUM_RENTALS FROM CUSTOMER sql> WHERE NUM_RENTALS >15; Customer Name Total Re Frobisher, 33 Kamal Bowie, David 17 Belafonte, 22 Harry Grundy, Robin 23 Smith, Harry 22 Jones, Mable 19 Partner, Bonnie 19 7 records listed Combining Selection Criteria with AND The 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. 6-42
150 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 CUSTOMER sql> WHERE CITY = "Denver" AND NUM_RENTALS >20; Customer Name City Total Re Frobisher, Denver 33 Kamal 1 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; Customer Name City Total Re Nbr T Jones, Freddie Chicago records listed 6-43 Using UniData SQL
151 Combining Selection Criteria with OR The 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"; Customer Name City Frobisher, Denver Kamal Steven Spender Denver Wagner, Pat Denver Doodle, Polly Denver W. Belafonte, Boulder Harry Smith, Harry Boulder Fellini, J. Chicago Hoboken Jones, Freddie Chicago LaRue, Karma Denver Smith, Leif Denver Boorman, Rick Chicago 11 records listed Combining the AND and OR Operators UniData 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-44
152 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"); Tape 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 TAPES sql> WHERE ACTORS = "Janet Leigh" sql> AND CATEGORIES = "H" OR CATEGORIES = "B"; Tape Name Actors Type of Vide Journey Abroad Cary Grant B Psycho Janet Leigh H 2 records listed Selecting Values That Do Not Meet Conditions Sometimes you need to select data that does not meet certain conditions. There are two ways to accomplish this task: The NOT EQUAL TO operator Using UniData SQL
153 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 CUSTOMER sql> WHERE CITY!= "Denver" AND CITY!= "Chicago"; Customer Name City Jones, Bob Arvada Jamieson, Dale Seattle Chase, Carl Kenosha Wagner, Esther Kenosha Fischer, Carrie New York James, Bob Hawthorne Dillon, Matt Dodge City... Page 2 Customer Name City Partner, Bonnie Lakewood Byles, 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-46
154 6-47 Using UniData SQL Change AND to OR. sql> SELECT NAME,CITY FROM CUSTOMER sql> WHERE NOT (CITY = "Denver" OR CITY = "Chicago"); Customer Name City Jones, Bob Arvada Jamieson, Dale Seattle Chase, Carl Kenosha Wagner, Esther Kenosha Fischer, Carrie New York James, Bob Hawthorne Dillon, Matt Dodge City... Page 2 Customer Name City Partner, Bonnie Lakewood Byles, Marcy Los Angele s 20 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,DEPT sql> FROM STAFF sql> WHERE (TITLE = "Prof" OR TITLE = "AscProf") sql> AND SAL > sql> AND NOT (DEPT = "BUS" OR DEPT = "CS"); Last Nam Title Salary Dept Eades Prof 42,000 FA James AscProf 32,500 PSY Carnes Prof 29,900 ENG Otis AscProf 25,800 FA Gibson Prof 26,800 SPA 5 records listed
155 Applying Conditions to Every Value Before 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"; Last Name GD Smith B Martin C C Offenbach D C C B C C Miller C B B B B B 4 records listed Omitting the EVERY Operator Notice 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-48
156 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"; Last Name GD Smith B B B B Smith B Martin C C Offenbach D C C B C C Miller C B B B B B Muller C Page 2 Last Name GD C B I 6 records listed Selecting Records That Match Patterns Using 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 Using UniData SQL
157 Pattern Specifications The following table describes the UniData SQL pattern specifications to designate variables or unknown contents of a string or pattern. 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 xa xx 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 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. 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. UniData SQL Pattern Specifications 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, Searching for Patterns with the LIKE Operator The 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-50
158 The next SELECT statement displays the customers whose names begin with the letter B : sql> SELECT NAME FROM CUSTOMER sql> WHERE NAME LIKE "B%"; 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..."; Customer Name Belafonte, Harry 1 records listed 6-51 Using UniData SQL
159 Using Range Specifiers The 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 fivecharacter name: sql> FROM TAPES WHERE NAME sql> LIKE "1-5X"; TAPES Tape Name V V9431 Help V4637 If... B914 Tammy V4341 Z 5 records listed 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> FROM TAPES sql> NOT LIKE "V..."; TAPES Tape Name B914 Tammy B2297 Love Story 2 records listed 6-52
160 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..."; Customer Name Frobisher, Kamal Steven Spender Wagner, Pat Wagner, Esther Fischer, Carrie Faber, Harry Partner, Bonnie 7 records listed Using Wild Cards in Patterns Pattern 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. The next example shows the tapes in which the tape name contains the literal string... : sql> FROM TAPES sql> WHERE NAME LIKE "...'...'..."; TAPES Tape Name v4637 If... 1 records listed Dictionary Conversions and the LIKE Operator The 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 Using UniData SQL
161 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"; Last Nam Salary Eades 42,000 Masters 35,800 Aaron 19,900 Fisher 31,200 James 32,500 Carnes 29,900 Otis 25,800 Gibson 26,800 Fried 98,000 9 records listed For further information on conversion functions, see the UniData SQL Commands Reference. LIKE Clauses and Strings The 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. 6-54
162 One of the character strings in the following table. String "%ones, " "...ones,1x3a" Looks For, followed by four characters, 1 character and 3 alphabetic characters "...ones5x" 5 characters What LIKE Clauses Look for in Queries Note: A comma is neither numeric nor alphanumeric, however, it does match X. Incorrect Pattern Specification The 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 CUSTOMER sql> WHERE NAME LIKE "...ones'5x'"; Customer Name No record listed The IN Operator Use 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 Using UniData SQL
163 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"); Last Nam Dept Eades FA Masters PSY Aaron PSY Fisher BUS James PSY Carnes ENG Otis FA Fried BUS 8 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"); Tape Name Type of Vide Scaramouche M Gone With The Wind R Tammy Love Story Flash Gordon 7 records listed R R TJ S K 6-56
164 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,CATEGORIES sql> FROM CUSTOMER C,TAPES T sql> WHERE TAPES_RENTED = T.@ID sql> AND EVERY CATEGORIES NOT IN ("A","B","C","D") sql> ORDER BY C.NAME; Customer Name Tape Name Type of Vide Best, George Love Story R TJ Chase, Carl Flash Gordon S K Jones, Mable Gone With The Wind R Jones, Samuel Flash Gordon S K Partner, Bonnie Love Story R TJ Partner, Bonnie Tammy R 6 records listed Selecting Records within a Range Use 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_OUT sql> FROM CUSTOMER sql> WHERE DATE_OUT BETWEEN "04/19/94" AND "04/22/94"; Customer Name Tapes Date Out Chase, Carl V /20/94 V /20/94 V /21/94 Faber, Harry V /19/94 2 records listed 6-57 Using UniData SQL
165 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 AND 50000; Last Nam Salary Aaron 19,900 Carnes 29,900 Otis 25,800 Gibson 26,800 Fried 98,000 5 records listed 6-58
166 Sorting Query Results Use 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 Order To 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; Last Nam Aaron Carnes Eades Fisher Fried Gibson James Masters Otis 9 records listed 6-59 Using UniData SQL
167 Sorting in Descending Order You 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 CUSTOMER sql> ORDER BY NBR_TAPES DESC; Customer Name Nbr T Chase, Carl 3 Smith, Harry 3 Jones, Mable 2 Jones, Samuel 2 Partner, Bonnie 2 Barrie, Dick 1 Best, George 1 Bowie, David 1 Faber, Harry 1 Fischer, Carrie 1 James, Bob 1... Grundy, Robin 0 LaRue, Karma 0 Smith, Leif 0 Steven Spender 0 Valenzuela, 0 Carmen Wagner, Esther 0 Wagner, Pat 0 29 records listed Sorting by Multiple Attributes UniData 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-60
168 The next example shows how to create a list of staff names ordered alphabetically by department: sql> SELECT LNAME,DEPT FROM STAFF sql> ORDER BY DEPT,LNAME; Last Nam Dept Fisher BUS Fried BUS Carnes ENG Eades FA Otis FA Aaron PSY James PSY Masters PSY Gibson SPA 9 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 Using UniData SQL
169 Combining Ascending and Descending Operators The 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; City Customer Name Seattle Jamieson, Dale San Jose Darrell Corden Rutherford Jones, Samuel Overton Bowie, David New York Fischer, Carrie Milwaukee Faber, Harry Milwaukee Jones, Mable Los Angele Byles, Marcy s Lakewood Partner, Bonnie Kenosha Barrie, Dick... Denver LaRue, Karma Denver Smith, Leif Denver Steven Spender Denver Wagner, Pat Chicago Boorman, Rick Chicago Fellini, J. Hoboken Chicago Jones, Freddie Boulder Belafonte, Harry Boulder Smith, Harry Arvada Jones, Bob 29 records listed Sorting Based on Multivalued Attributes The 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-62
170 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> sql> FROM STUDENT sql> ORDER BY SEMESTER; STUDENT Last Name Term Miller FA93 SP Offenbach FA93 SP Smith FA93 SP Muller FA93 SP Smith SP Martin SP94 6 records listed Unnesting and Sorting Based on Multivalued Attributes The 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> sql> FROM STUDENT sql> UNNEST SEMESTER sql> ORDER BY SEMESTER; STUDENT Last Name Term Miller FA Offenbach FA Smith FA Muller FA Miller SP Smith SP Offenbach SP Martin SP Smith SP Muller SP94 10 records listed 6-63 Using UniData SQL
171 Unnesting an Association and Sorting The next example shows how UNNEST affects the ordering of multivalued and multi-subvalued attributes when you use ASSOCIATION names in the UNNEST statement: sql> sql> FROM STUDENT sql> UNNEST CGA sql> ORDER BY COURSE_GRD; STUDENT Last Name Term Crs # GD Smith FA93 CS130 A Smith SP94 PE220 A Muller FA93 FA120 A Muller SP94 FA121 A Miller FA93 MA220 B Miller FA93 PY100 B Miller SP94 EG140 B Miller SP94 EG240 B Miller SP94 MA221 B Smith SP94 FA100 B Offenbach SP94 CS105 B Smith FA93 CS100 B Offenbach SP94 MA102 C Page 2 STUDENT Last Name Term Crs # GD Offenbach SP94 PY100 C Martin SP94 PE100 C Martin SP94 PY100 C Muller FA93 FA230 C Muller FA93 HY101 C Offenbach FA93 CS104 D Muller SP94 HY102 I 27 records listed Sorting and Unnesting Another 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-64
172 For example, listing student grades from A to I using EXP yields the same result as in the previous example: sql> sql> FROM STUDENT sql> ORDER BY COURSE_GRD EXP; STUDENT Last Name Term Crs # GD Smith FA93 CS130 A Smith SP94 PE220 A Muller FA93 FA120 A Muller SP94 FA121 A Miller FA93 MA220 B Miller FA93 PY100 B Miller SP94 EG140 B Miller SP94 EG240 B Miller SP94 MA221 B Smith SP94 FA100 B Offenbach SP94 CS105 B Smith FA93 CS100 B Offenbach SP94 MA102 C Page 2 STUDENT Last Name Term Crs # GD Offenbach SP94 PY100 C Martin SP94 PE100 C Martin SP94 PY100 C Muller FA93 FA230 C Muller FA93 HY101 C Offenbach FA93 CS104 D Muller SP94 HY102 I 27 records listed 6-65 Using UniData SQL
173 Subqueries Subqueries 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 Query The 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"; Last Nam Dept Otis FA 1 records listed 6-66
174 The second example lists all the employees of the FA department where professor Otis works: sql> SELECT LNAME,DEPT FROM STAFF WHERE DEPT = "FA"; Last Nam Dept Eades FA Otis FA 2 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 STAFF sql> WHERE DEPT = (SELECT DEPT sql> FROM STAFF WHERE LNAME = "Otis"); Last Nam Dept Eades FA Otis FA 2 records listed Note: You must enclose subqueries in parentheses. Using ANY, ALL, and IN with Subqueries Part 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 Using UniData SQL
175 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,DEPT sql> FROM STAFF sql> WHERE SAL >ANY (SELECT SAL sql> FROM STAFF WHERE DEPT = "PSY") sql> AND DEPT!= "PSY"; Last Nam Title Salary Dept Eades Prof 42,000 FA Fisher Prof 31,200 BUS Carnes Prof 29,900 ENG Otis AscProf 25,800 FA Gibson Prof 26,800 SPA Fried Dean 98,000 BUS 6 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 STAFF sql> WHERE SAL >ALL (SELECT SAL sql> FROM STAFF WHERE DEPT = "PSY") sql> AND DEPT!="PSY"; Last Nam Title Salary Dept Eades Prof 42,000 FA Fried Dean 98,000 BUS 2 records listed 6-68
176 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_NBR sql> FROM STUDENT sql> WHERE MAJOR!= "PY" sql> AND COURSE_NBR IN (SELECT COURSE_NBR sql> FROM STUDENT WHERE MAJOR = "PY"); Last Name Majo Crs # Smith CH PY100 Offenbach CS PY100 Miller EG PY100 3 records listed Writing Compound Queries UniData 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 UniData SQL 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.
177 The second part includes those tapes with category H. 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> FROM TAPES sql> IN (SELECT T.@ID FROM CUSTOMER C, sql> TAPES T WHERE ((C.NAME = "Chase, Carl" AND sql> EVERY CATEGORIES!= "C") OR (C.NAME LIKE sql> "...Jones..." AND EVERY CATEGORIES!= "R")) sql> AND T.@ID = TAPES_RENTED) sql> OR CATEGORIES = "H"; TAPES Tape Name Type of Vide V9431 Help K C M V4499 Psycho H D V8481 'Round Midnight M D V1254 Flash Gordon S K V2001 Blue Velvet H V4341 Z P D V996 Citizen Kane H V5151 To Kill A H Mockingbird 8 records listed 6-70
178 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 attributes 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,CREDITS sql> FROM STUDENT,COURSES sql> WHERE (COURSE_GRD = "A" sql> AND COURSE_NBR IN FROM COURSES sql> WHERE CREDITS = 5)) sql> AND COURSE_NBR = COURSES.@ID; Last Name Crs # GD Credi Muller FA120 A 5 Smith CS130 A 5 2 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.NAME sql> FROM CUSTOMER CST,TAPES T,CATEGORIES C sql> WHERE EVERY TAPES_RENTED NOT IN FROM TAPES sql> WHERE CATEGORIES IN FROM CATEGORIES sql> WHERE NAME = "Horror" OR NAME = "Drama")) sql> AND TAPES_RENTED = T.@ID AND CATEGORIES = C.@ID sql> ORDER BY CST.NAME; Customer Name Tapes Type of Vide Category Type Best, George B2297 R Romance Best, George B2297 TJ Tear Jerker Bowie, David V9961 A Avant Garde Bowie, David V9961 S Science Fiction Fischer, Carrie V110 C Comedy Fischer, Carrie V110 O Old Classic Jones, Freddie V9431 C Comedy Jones, Freddie V9431 K Childrens Movie Jones, Freddie V9431 M Musical Partner, Bonnie B2297 R Romance Partner, Bonnie B2297 TJ Tear Jerker Partner, Bonnie B914 R Romance 12 records listed 6-71 Using UniData SQL
179 Passing Data from Query to Subquery You 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 X sql> WHERE SAL <=ALL(SELECT SAL FROM sql> STAFF WHERE X.DEPT=DEPT); Dept Last Nam Salary Title PSY Aaron 19,900 Counsel or BUS Fisher 31,200 Prof ENG Carnes 29,900 Prof FA Otis 25,800 AscProf SPA Gibson 26,800 Prof 5 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-72
180 Group Functions In 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. Function AVG SUM MIN MAX COUNT COUNT(*) NUMBER STD VARIANCE Description Computes the average value. Computes the total value. Returns the minimum value. Returns the maximum value. Counts the number of values. Counts the number of rows. Counts the number of records in a table. Computes standard deviation. Computes the square of the standard deviation. Group Functions Selecting Summary Information from One Group This section shows you how to use group functions to compute summary information from just one group Using UniData SQL
181 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,CATEGORIES sql> FROM TAPES X sql> UNNEST CATEGORIES sql> WHERE INCOME > (SELECT AVG(INCOME) sql> FROM TAPES Y sql> WHERE X.CATEGORIES = Y.CATEGORIES); Tape Name Retail C Tape Rev Type of Vide S D Citizen Kane O Round Midnight M Round Midnight D American Graffiti K Sleuth D Z P Psycho H Catch C Catch A Gone With The Wind R 12 records listed 6-74
182 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; SUM(N 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; MIN(Tota 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; MAX(Tota record(s) calculated 6-75 Using UniData SQL
183 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 STAFF sql> WHERE SAL >30000; CNT(Last 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 STAFF sql> WHERE SAL >30000; COUNT(*) record(s) calculated 6-76
184 Multiple Group Functions The 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 STAFF sql> WHERE DEPT = "PSY"; MAX(Sal MIN(Sal AVG(Sal SUM(Sal ,800 19,900 29,400 88,200 3 record(s) calculated Correct and Incorrect Group Function Use The 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 STAFF sql> WHERE SAL = (SELECT MAX(SAL) sql> FROM STAFF); Last Nam Dept Salary Fried BUS 98,000 1 records listed 6-77 Using UniData SQL
185 Using DISTINCT and COUNT with Attributes The next example uses DISTINCT to show the different majors the students have chosen: sql> SELECT DISTINCT MAJOR FROM STUDENT; Majo ---- CH CS EG FA PY 5 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; CNT(DT M record(s) calculated Writing Column Headings In 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; Sum Rent record(s) calculated 6-78
186 Selecting Summary Information from Multiple Groups The 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 TAPES sql> GROUP BY CATEGORIES; Type of Vide Total A 3 B 1 C 4 D 10 H 4 K 3 M 3 O 2 P 2 R 3 S 4 TJ 1 ======== 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 Using UniData SQL
187 Including Multiple Attribute Names in a GROUP BY Clause The 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 STAFF sql> GROUP BY DEPT,TITLE sql> ORDER BY DEPT; Dept Title Avg.Sal BUS Dean 98,000 BUS Prof 31,200 ENG Prof 29,900 FA AssProf 25,800 FA Prof 42,000 PSY AscProf 32,500 PSY Assprof 35,800 PSY Counsel 19,900 or SPA Prof 26,800 ======= 37,989 9 records listed Specifying a Search Condition for Groups UniData 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-80
188 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 TAPES sql> GROUP BY CATEGORIES sql> HAVING COUNT(*) >1; Type of Vide COUNT(*) A 3 C 4 D 10 H 4 K 3 M 3 O 2 P 2 R 3 S 4 ======== 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 Using UniData SQL
189 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 TAPES sql> GROUP BY CATEGORIES sql> HAVING AVG(RENTAL_PRICE) > sql> (SELECT AVG(RENTAL_PRICE) FROM TAPES); Type of Vide AVG(Reta A 4.77 B 4.40 C 3.76 D 4.60 H 4.09 M 5.01 P 4.04 S 4.75 ======== 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-82
190 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 STAFF sql> WHERE TITLE = "Prof" sql> GROUP BY DEPT sql> HAVING COUNT(*) >= 1; Dept COUNT(*) BUS 1 ENG 1 FA 1 SPA 1 ======== 4 4 records listed Group Functions with Multivalued Attributes When 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; CNT(Crs record(s) calculated 6-83 Using UniData SQL
191 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; CNT(Crs record(s) calculated 6-84
192 Expressions and Functions To 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: Arithmetic Character Date 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 Expressions An arithmetic expression is made up of an attribute name or constant values connected by any of the following arithmetic operators. Operator Function + Addition - Subtraction * Multiplication / Division Arithmetic Operators 6-85 Using UniData SQL
193 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 CUSTOMER sql> WHERE NUM_RENTALS < 5; Customer Name Total Re CUR_BALANCE James, Bob Faber, Harry Jones, Freddie records listed 6-86
194 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_RENTALS sql> FROM CUSTOMER sql> WHERE CUR_BALANCE>0 AND NUM_RENTALS!= 0 sql> ORDER BY 4 DESC; Customer Name Total Re Currentl CUR_BALANCE/NUM_RENTALS James, Bob Jones, Samuel Faber, Harry Chase, Carl Jones, Freddie Jamieson, Dale Jones, Bob Smith, Harry Jones, Mable Barrie, Dick Bowie, David Fischer, Carrie Partner, Bonnie Best, George 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 STAFF sql> WHERE SAL <20000; Last Nam New Pay Aaron records listed 6-87 Using UniData SQL
195 Arithmetic Functions In 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 CUSTOMER sql> WHERE NAME = "Wagner, Pat"; Customer Name POWER(NUM_RENTALS,2) Wagner, Pat 16 1 records listed Arithmetic Function ABS (nvalue) ACOS (nvalue) ASIN (nvalue) ATAN (nvalue) COS (nvalue) EXP (nvalue) Description Absolute value of 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. 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. Trigonometric arc-tangent of nvalue. Cosine of nvalue. nvalue is expressed as degree. 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-88
196 Arithmetic Function ROUND(nvalue, e) SIGN(nvalue) SIN (nvalue) Description Rounds the nvalue to the number of decimal places specified by e. 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. Sine of nvalue. nvalue is expressed as degree. SQRT (nvalue) Square root of nvalue; if nvalue is 0, returns 0. TAN (nvalue) TRUNC(nvalue{,d}) Tangent of nvalue. nvalue is expressed as degree. Truncates the nvalue to ddigits right of the decimal place. The default is 0. Arithmetic Functions (continued) 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) BALANCE sql> FROM CUSTOMER sql> WHERE NUM_RENTALS <14; Customer Name Total Re Balance Jones, Bob Steven Spender Jamieson, Dale Chase, Carl Wagner, Pat Wagner, Esther Doodle, Polly W.... Boorman, Rick Byles, Marcy records listed Carmen 19 records listed 6-89 Using UniData SQL
197 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 CUSTOMER sql> WHERE CUR_BALANCE> 0.00; Customer Name Cur Bal Jones, Bob 4 Jamieson, Dale 6 Chase, Carl 12 Fischer, Carrie 2 James, Bob 3 Bowie, David 5 Jones, Samuel 9 Smith, Harry 13 Faber, Harry 3 Jones, Freddie 4 Jones, Mable 8 Best, George 2 Barrie, Dick 4 Partner, Bonnie 3 7 records listed 6-90
198 To display one decimal place, use the following TRUNC function: sql> SELECT NAME,TRUNC(CUR_BALANCE,1) "Cur Bal" sql> FROM CUSTOMER sql> WHERE CUR_BALANCE > 0.00; Customer Name Cur Bal Jones, Bob 4.5 Jamieson, Dale 6.7 Chase, Carl 12.4 Fischer, Carrie 2.5 James, Bob 3.7 Bowie, David 5.0 Jones, Samuel 9.9 Smith, Harry 13.6 Faber, Harry 3.5 Jones, Freddie 4.5 Jones, Mable 8.0 Best, George 2.5 Barrie, Dick 4.5 Partner, Bonnie records listed 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 Using UniData SQL
199 -1 if the value is less than zero. sql> SELECT NAME,SIGN(CUR_BALANCE) sql> FROM CUSTOMER; Customer Name SIGN(CUR_BALANCE) Jones, Bob +1 Frobisher, 0 Kamal Steven Spender 0 Jamieson, Dale +1 Chase, Carl +1 Wagner, Pat 0 Wagner, Esther 0 Doodle, Polly 0 W. Fischer, Carrie +1 James, Bob +1 Fischer, Carrie +1 James, Bob +1 Dillon, Matt 0 Bowie, David +1 Jones, Samuel Partner, Bonnie +1 Byles, Marcy 0 29 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 multivalued attribute STD_NO. 6-92
200 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 STAFF sql> WHERE STD_NO <> ""; Last Nam Old No New No Eades Fisher Otis 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 multivalued attribute, the query uses the REUSE function. sql> SELECT LNAME,STD_NO "Old No",STD_NO + REUSE(10) "New No" sql> FROM STAFF sql> WHERE STD_NO <> ""; Last Nam Old No New No Eades Fisher Otis records listed 6-93 Using UniData SQL
201 Arithmetic Expressions and Functions in Group Functions You 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 ), sql> SUM(SAL ),COUNT(*) sql> FROM STAFF sql> GROUP BY DEPT; Dept AVG(Sal AVG(SAL+ SUM(SAL+ COUNT(*) BUS 64, ENG 29, FA 33, PSY 29, SPA 26, ======= ======== ======== ======== 37, 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; Teacher AVG(POWER(CREDIT Aaron Carnes Fisher Fried Gibson James Masters Otis ================ records listed 6-94
202 Character String Functions Character 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 Function ASCII (char) CHAR (x) DECODE(...) DOWNCASE ICONV INITCAP(string) INSTR OCONV string1 string2 NVL Description Converts EBCDIC to ASCII. Converts number to ASCII value. Translates the values in a column to a set of constants or values in other columns. Changes all uppercase characters to (string) lowercase. Converts string or numeric data to internal (str.expr, representation 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. Capitalizes the first initial of a string. 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. Converts string or numeric data from internal (str.expr, representation format to output format based conv.code.expr) on conversion codes. For details, see Developing UniBasic Applications or the UniBasic Commands Reference manual. Concatenates string1 with string2. Converts the null value to another string. String Functions The Concatenation Function Use the concatenation function ( ) to combine several columns and/or constant values into a single display column Using UniData SQL
203 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; Student, Major Smith,CH Smith,CS Martin,PY Offenbach,CS Miller,EG Muller,FA 6 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; Tape Name Name Length A Clockwork Orange 18 American Graffiti 18 The Stalker 11 Scaramouche 11 Gone With The Wind 18 Girl Friday Catch 22 8 To Kill A 21 Mockingbird 0 23 records listed 6-96
204 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)Initials sql> FROM STUDENT; First Name Last Name Initials Harry Smith HS jojo Smith js Sally Martin SM Karl Offenbach KO Susan Miller SM Gerhardt Muller GM 6 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 Using UniData SQL
205 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; Last Nam s Position Eades 5 Masters 3 Aaron 0 Fisher 3 James 5 Carnes 6 Otis 4 Gibson 4 Fried 0 9 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 STAFF sql> WHERE LNAME = "Masters"; Last Nam First s Second s Masters records listed 6-98
206 The UPCASE and DOWNCASE Functions To 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; UPNAME LOTITLE EADES prof MASTERS ascprof AARON counselor FISHER prof JAMES ascprof CARNES prof OTIS ascprof GIBSON prof FRIED dean 9 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 STUDENT sql> WHERE INITCAP(FNAME) = "Jojo"; INITCAP(FNAME) INITCAP(LNAME) Jojo Smith 1 records listed The LPAD and RPAD Functions LPAD 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 Using UniData SQL
207 The next example shows how to use RPAD: sql> SELECT RPAD(NAME,30-LENGTH(NAME),"-") "Name", sql> TAPES_RENTED sql> FROM CUSTOMER sql> WHERE TAPES_RENTED BETWEEN "V2000" AND "V6000"; Name Tapes Jones, Bob V4341 Chase, Carl V4951 James, Bob V2001 Smith, Harry V2001 V5004 Faber, Harry V5151 Jones, Mable V 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; Last Name Crs # TRANSLATE(COURSE_GRD,"A,B,C,D,F Smith CS130 4 CS100 3 PY100 3 CS131 3 CS101 3 PE220 4 Smith FA100 3 Martin PY100 2 PE100 2 Offenbach CS104 1 MA Muller FA120 4 FA230 2 HY101 2 FA121 4 FA231 3 HY records listed 6-100
208 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","Associate sql> Professor", "Administrative Staff") "Full Title" sql> FROM STAFF; Last Nam Full Title Eades Professor Masters Administrative Staff Aaron Administrative Staff Fisher Professor James Associate Professor Carnes Professor Otis Associate Professor Gibson Professor Fried Administrative Staff Using UniData SQL
209 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; Last Nam Title Salary Eades Teacher 42,000 Masters Teacher 35,800 Aaron Counselor 19,900 Fisher Teacher 31,200 James Teacher 32,500 Carnes Teacher 29,900 Otis Teacher 25,800 Gibson Teacher 26,800 Fried Dean 98,000 9 records listed Date Functions UniData 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; Customer Name MOS Steven Spender 2 2 Partner, Bonnie records listed 6-102
210 Chapter 7: Creating and Querying Views Chapter 7 What Is a View? How to Use Views How View Queries Are Processed Creating Views Creating a View from a Single Table Creating a View from Multiple Tables Creating a View Using Expressions Creating a View on a View Querying Views Optimizing Processing on View Queries Dropping Views
211 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
212 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 Views Once you create a view, you can: Query it as you would a base table. Use it to create other views. How View Queries Are Processed UniData 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
213 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
214 Creating Views This section provides examples of the following: Syntax: 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. CREATE VIEW view_name [(attribute_name [{,attribute_name}...])] AS SELECT statement Creating a View from a Single Table The 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
215 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'; NAME TITLE Dept COURSES TUTEE BOSS Masters Assprof PSY James Aaron Counsel PSY James James AscProf PSY Fried 3 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 Tables You 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, Chapter 6: The SELECT Statement. 7-6
216 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 RENTALS sql> WHERE TAPE = "Catch 22"; CUSTOMER TAPE OUT CHARGE Smith, Harry Catch 22 04/24/ records listed Creating a View Using Expressions You 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 arithmetic, 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; NAME CURRSAL NEWSAL Eades 42, Masters 35, Aaron 19, Fisher 31, James 32, Carnes 29, Otis 28, Gibson 26, Fried 101, records listed 7-7 Using UniData SQL
217 Creating a View on a View You 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; NAME CURRSAL NEWSAL Fried 101, records listed Note: Views and base tables can be used together to define new views. 7-8
218 Querying Views After 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; Customer Name City Tapes Date Out Frobisher, Denver Kamal Steven Spender Denver Wagner, Pat Denver Doodle, Polly Denver W. LaRue, Karma Denver Smith, Leif Denver 6 records listed Optimizing Processing on View Queries UniData 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. 7-9 Using UniData SQL
219 The SELECT statement in the view definition cannot contain the DISTINCT keyword. 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 LNAME, TITLE, and SAL. The second statement creates another view called V2 from data found in the first view. sql> CREATE VIEW V1 AS FROM STAFF; View V1 created. sql> CREATE VIEW V2 AS 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; STAFF Last Nam Title Eades Prof 6 Masters Ascprof 9 Aaron Counsel or 1 Fisher Prof 4 James AscProf 7 Carnes Prof 2 Otis AscProf 5 Gibson Prof 8 Fried Dean 9 records listed 7-10
220 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 FROM sql> STAFF,COURSES WHERE COURSES = COURSES.@ID; View V3 created. sql> CREATE VIEW V4 (DEPT,SALARY) AS SELECT DEPT,SUM(SAL) FROM sql> 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; DEPT SALARY BUS 129,200 ENG 29,900 FA 67,800 PSY 88,200 SPA 26,800 5 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 Using UniData SQL
221 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"; STAFF Last Nam Title Salary Fried Dean 98,000 1 records listed The query from the previous example transforms into the following: sql> FROM STAFF sql> WHERE LNAME="Fried"; STAFF Last Nam Title Salary Fried Dean 98,000 1 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
222 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; Last Nam Courses Tu Eades FA230 Eades FA231 Masters Aaron Fisher FA100 James Carnes Otis PY100 Gibson Fried 10 records listed Note: UniData SQL automatically optimizes joins of views that are based on the same table and joined on the record ID Using UniData SQL
223 Dropping Views When you no longer need a view, you can use a DROP VIEW statement to delete it. Syntax DROP 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
224 Chapter 8: Creating Reports Chapter 8 Understanding UniData SQL Reports Constructing Report Columns Using the COLUMN Command Setting Up Column Headings Justifying Text in a Column Heading Controlling Column Spacing Controlling Spaces between Two Columns Controlling Spaces Between Specific Columns Formatting Report Columns Copying a Format Displaying Long Values Defining Report Titles Turning Titles On or Off Formatting Headers Formatting Footers Including Attribute Values in Headers and Footers Organizing Reports by Group Creating Breaks in a Report Performing Computations at Breaks Computing Subtotals Executing Multiple Computations Computing a Grand Total Displaying and Clearing Breaks and Computations Setting the Report Environment Setting Report Parameters Wrapping Text Vertically Displaying Report Environment Parameters
225 8-2 Using UniData SQL Preparing Complex Reports Producing a Complex Report
226 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
227 Understanding UniData SQL Reports A 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 TAPES sql> UNNEST CATEGORIES WHERE CATEGORIES IN sql> ("C","R","S") ORDER BY CATEGORIES; Type of Vide Tape Name Tape Rev C American Graffiti C Catch C Girl Friday C Help R Gone With The Wind R Love Story R Tammy 3.18 S S A Clockwork Orange S Flash Gordon S The Stalker 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
228 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 PERCENT NAME NAME INCOME STORE Comedy American Graffiti $ Catch 22 $ Girl Friday $ Help $ $1, Romance Gone With The Wind $ Love Story $ Tammy $ $ Science Fi 2001 $ A Clockwork Orange $ Flash Gordon $ The Stalker $ $1, FISCAL YEAR Using UniData SQL
229 Constructing Report Columns The 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 Command In 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
230 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
231 COLUMN Command Options The following table lists the options for the COLUMN command. Parameter attribute_name expression ALIAS alias CLEAR DEFAULT FORMAT column_format HEADING "text" JUSTIFY Description Specifies the attribute to format. Any combination of attribute names, constants, arithmetic operators, and UniData SQL functions that together select attributes 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. 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. Removes the column definition for expression or attribute_spec. Resets the column definition to default settings, including PRINT ON and WRAP ON. Formats values displayed in this column. For further information, see Formatting Report Columns on page 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. 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. COLUMN Parameters 8-8
232 Parameter LIKE expression LIKE attribute_label NEWLINE NEW_VALUE new_val NOPRINT PRINT NULL "text" OFF ON OLD_VALUE old_val SPACE n WRAPPED WORD_WRAPPED TRUNCATED attribute_name_ expression no option Description Copies the COLUMN specification of another column. With SET WRAP HORI, starts a new line before displaying the value of a column. With SET WRAP DEF, switches to vertical format. Saves the current value of an attribute for use in TTITLE statements to print a header that reflects current attribute values. Turns on or off printing column text. The default is PRINT. Replaces null values with text in reports. Turns COLUMN settings off or on without affecting the settings. The default is ON. Saves the current value of an attribute for use in BTITILE statements to print a footer that reflects current attribute values. 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). 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. Displays current column definitions. COLUMN Parameters (continued) 8-9 Using UniData SQL
233 Setting Up Column Headings When 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. 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 CATEGORIES sql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES; CATEGORY VIDEO TAPE ANNUAL CODE NAME INCOME C American Graffiti C Catch C Girl Friday C Help R Gone With The Wind R Love Story R Tammy 3.18 S S A Clockwork Orange S Flash Gordon S The Stalker 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, Chapter 5: Manipulating Data. 8-10
234 Justifying Text in a Column Heading The 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 CATEGORIES sql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES; CATEGORY VIDEO TAPE ANNUAL CODE NAME INCOME C American Graffiti C Catch C Girl Friday C Help R Gone With The Wind R Love Story R Tammy 3.18 S S A Clockwork Orange S Flash Gordon S The Stalker records listed Controlling Column Spacing Unless 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 Using UniData SQL
235 Controlling Spaces between Two Columns The 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 CATEGORIES sql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES; CATEGORY VIDEO TAPE ANNUAL CODE NAME INCOME C American Graffiti C Catch C Girl Friday C Help R Gone With The Wind R Love Story R Tammy 3.18 S S A Clockwork Orange S Flash Gordon S The Stalker records listed 8-12
236 Controlling Spaces Between Specific Columns The 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 CATEGORIES sql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES; CATEGORY VIDEO TAPE ANNUAL CODE NAME INCOME C American Graffiti C Catch C Girl Friday C Help R Gone With The Wind R Love Story R Tammy 3.18 S S A Clockwork Orange S Flash Gordon S The Stalker records listed 8-13 Using UniData SQL
237 Formatting Report Columns To define the display format of data within a column, use a COLUMN statement with a FORMAT clause. Syntax COLUMN 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 attributes; 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 Display leading zeros $ 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 column_format Numeric Options 8-14
238 Option Explanation Example of Mask, 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). column_format Numeric Options (continued) 9.99EEEE Example In 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 CATEGORIES sql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES; CATEGORY VIDEO TAPE ANNUAL CODE NAME INCOME C American Graffiti $ C Catch 22 $ C Girl Friday $22.68 C Help $ R Gone With The Wind $ R Love Story $47.50 R Tammy $3.18 S 2001 $ S A Clockwork Orange $52.52 S Flash Gordon $ S The Stalker $ records listed 8-15 Using UniData SQL
239 Copying a Format If 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 CATEGORIES sql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES; CATEGORY VIDEO TAPE ANNUAL UNIT CODE NAME INCOME PRICE C American Graffiti $ $45.00 C Catch 22 $ $45.00 C Girl Friday $22.68 $22.50 C Help $ $23.50 R Gone With The Wind $ $78.00 R Love Story $47.50 $25.00 R Tammy $3.18 $9.99 S 2001 $ $45.00 S A Clockwork Orange $52.52 $77.00 S Flash Gordon $ $23.50 S The Stalker $20.20 $ records listed Displaying Long Values If 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
240 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 CATEGORIES sql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES; CATEGORY VIDEO TAPE ANNUAL UNIT CODE NAME INCOME PRICE C American G $ $45.00 raffiti C Catch 22 $ $45.00 C Girl Frida $22.68 $22.50 y C Help $ $23.50 R Gone With $ $78.00 The Wind R Love Story $47.50 $25.00 R Tammy $3.18 $9.99 S 2001 $ $45.00 S A Clockwor $52.52 $77.00 k Orange S Flash Gord $ $23.50 on S The Stalke $20.20 $35.00 r 11 records listed 8-17 Using UniData SQL
241 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 CATEGORIES sql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES; CATEGORY VIDEO TAPE ANNUAL UNIT CODE NAME INCOME PRICE C American $ $45.00 Graffiti C Catch 22 $ $45.00 C Girl $22.68 $22.50 Friday C Help $ $23.50 R Gone With $ $78.00 The Wind R Love Story $47.50 $25.00 R Tammy $3.18 $9.99 S 2001 $ $45.00 S A $52.52 $77.00 Clockwork Orange S Flash $ $23.50 Gordon S The $20.20 $35.00 Stalker 11 records listed 8-18
242 Defining Report Titles In 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 Headers TTITLE 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] 8-19 Using UniData SQL
243 print_clause syntax: [SKIP [n] ] [COL [n] LEFT CENTER RIGHT] [ text ] [FORMAT format [TAB [n] ] [new_val] ]... 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. Parameter print_clause ON OFF Description 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. Turns the header or footer on, causing "text" to be printed. 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. BTITLE/TTITLE Parameters 8-20
244 print_clause Parameters The following table describes each parameter of print_clause. Clause COL n Description 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 FORMAT format 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. 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
245 Clause old_val new_val text TAB n Description 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. 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. Skips to the nth column from the current position. Print Clause Parameters (continued) 8-22
246 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 " " 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 TAPES sql> UNNEST CATEGORIES sql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES; OLD CLASSIC INCOME ANALYSIS CATEGORY C R S CATEGORY VIDEO TAPE ANNUAL UNIT CODE NAME INCOME PRICE C American Graffiti $ $45.00 C Catch 22 $ $45.00 C Girl Friday $22.68 $22.50 C Help $ $23.50 R Gone With The Wind $ $78.00 R Love Story $47.50 $25.00 R Tammy $3.18 $9.99 S 2001 $ $45.00 S A Clockwork Orange $52.52 $77.00 S Flash Gordon $ $23.50 S The Stalker $20.20 $35.00 Tip: With UniData SQL, you can position parts of a title independently by using separate formatting clauses. Formatting Footers BTITLE 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 Using UniData SQL
247 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
248 Example In the next example, the BTITLE statement adds FISCAL YEAR 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 " " SKIP 2 COL 9 "CATEGORY C R S" SKIP; sql> BTITLE ON; sql> BTITLE SKIP CENTER "FISCAL YEAR "; 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 CATEGORIES sql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES; OLD CLASSIC INCOME ANALYSIS CATEGORY C R S CATEGORY VIDEOTAPE ANNUAL UNIT CODE NAME INCOME PRICE C American Graffiti $ $45.00 C Catch 22 $ $45.00 C Girl Friday $22.68 $22.50 R Gone With The Wind $ $78.00 R Love Story $47.50 $25.00 R Tammy $3.18 $9.99 S 2001 $ $45.00 S A Clockwork Orange $52.52 $77.00 S Flash Gordon $ $23.50 S The Stalker $20.20 $35.00 FISCAL YEAR Note: Always enclose options in single quotation marks within a heading string that is enclosed in double quotation marks Using UniData SQL Including Attribute Values in Headers and Footers In 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.
249 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
250 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 "; 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 CATEGORIES sql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES; OLD CLASSIC CATEGORY: C CATEGORY VIDEO TAPE ANNUAL UNIT CODE NAME INCOME PRICE C American Graffiti $ $45.00 C Catch 22 $ $45.00 C Girl Friday $22.68 $22.50 C Help $ $23.50 R Gone With The Wind $ $78.00 R Love Story $47.50 $25.00 R Tammy $3.18 $9.99 S 2001 $ $45.00 S A Clockwork Orange $52.52 $77.00 C American Graffiti $ $45.00 C Catch 22 $ $45.00 C Girl Friday $22.68 $22.50 C Help $ $23.50 R Gone With The Wind $ $78.00 R Love Story $47.50 $25.00 R Tammy $3.18 $9.99 S 2001 $ $45.00 S A Clockwork Orange $52.52 $77.00 S Flash Gordon $ $23.50 S The Stalker $20.20 $35.00 FISCAL YEAR Using UniData SQL
251 Organizing Reports by Group You 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: Sum Average Maximum Minimum Count 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 Report A 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. Syntax BREAK ON event [text] [SKIP n] [option] 8-28
252 Valid break events are described in the following table. Event attribute ROW REPORT Description Whenever the specified attribute changes. Breaks at each row. Breaks at the end of the report. BREAK Events The skip actions include: Option BSKIP n SKIP n SKIP PAGE Description Skip n lines before any other action takes place. After print/display action, skip n lines. After print/display action, skip to a new page. SKIP Options 8-29 Using UniData SQL
253 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 TAPES sql> UNNEST CATEGORIES sql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES; INCOME ANALYSIS REPORT CATEGORY VIDEO TAPE ANNUAL CODE NAME INCOME C American Graffiti $ Catch 22 $ Girl Friday $22.68 Help $ R Gone With The Wind $ Love Story $47.50 Tammy $3.18 S 2001 $ A Clockwork Orange $52.52 Flash Gordon $ The Stalker $
254 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 TAPES sql> UNNEST CATEGORIES sql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES; INCOME REPORT CODE C VIDEO TAPE ANNUAL NAME INCOME American Graffiti $ Catch 22 $ Girl Friday $22.68 Help $ Enter <New line> to continue... INCOME REPORT CODE R VIDEO TAPE ANNUAL NAME INCOME Gone With The Wind $ Love Story $47.50 Tammy $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 Using UniData SQL
255 Performing Computations at Breaks You can perform various computations at breaks. The COMPUTE statement enables you to specify which computation to perform and on which attribute. Syntax COMPUTE computation OF attribute, attribute,... ON break_attribute The following table lists all the computations. Option SUM AVG MAX MIN COUNT NUMBER STD VAR Explanation Sum of the attribute values in a group. Average of the attribute values in a group. Maximum value of the attributes in a group. Minimum value of the attributes of a group. Number of values in a group. Number of items in a group. Standard deviation of the attributes of a group. Variance of the attribute values in a group. COMPUTE Options 8-32
256 Computing Subtotals You 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 TAPES sql> UNNEST CATEGORIES sql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES; INCOME ANALYSIS REPORT CATEGORY VIDEO TAPE ANNUAL CODE NAME INCOME C American Graffiti $ Catch 22 $ Girl Friday $22.68 Help $ ********** sum $1, R Gone With The Wind $ Love Story $47.50 Tammy $3.18 ********** sum $ S 2001 $ A Clockwork Orange $52.52 Flash Gordon $ INCOME ANALYSIS REPORT CATEGORY VIDEO TAPE ANNUAL CODE NAME INCOME The Stalker $20.20 ********** sum $1, Note: Remember to restore the proper column definition for CATEGORIES in the tape income analysis report Using UniData SQL
257 Executing Multiple Computations You 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 TAPES sql> UNNEST CATEGORIES sql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES; INCOME ANALYSIS REPORT CATEGORY VIDEO TAPE ANNUAL CODE NAME INCOME C American Graffiti $ Catch 22 $ Girl Friday $22.68 Help $ ********** avg $ Note: The SUM and AVG options can also be issued in separate COMPUTE statements to obtain the same results. 8-34
258 Computing a Grand Total The 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 CATEGORIES sql> WHERE CATEGORIES IN ("C","R","S") ORDER BY CATEGORIES; INCOME ANALYSIS REPORT CATEGORY VIDEO TAPE CODE NAME Tape Reven C American Graffiti $ Catch 22 $ Girl Friday $22.68 Help $ ********** avg $ sum $1, R Gone With The Wind $ Love Story $47.50 Tammy $3.18 ********** avg $ sum $1, R Gone With The Wind $ Love Story $47.50 Tammy $3.18 ********** avg $ sum $ S 2001 $ INCOME ANALYSIS REPORT CATEGORY VIDEO TAPE ANNUAL CODE NAME INCOME A Clockwork Orange $52.52 Flash Gordon $ The Stalker $20.20 ********** Using UniData SQL
259 avg $ sum $1, Displaying and Clearing Breaks and Computations When 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
260 Setting the Report Environment When 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. Syntax SET {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 HEADING ON HEADING OFF Description 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 NEWPAGE n NULL text Sets the left margin of the display or report and enables you to align the display. The default is 1. 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. Assigns text to replace the null value in display or print. SET Parameters 8-37 Using UniData SQL
261 Parameter PAGESIZE n PAUSE ON OFF SPACE WRAP UNDERLINE char ON OFF Description 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. 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. Sets the number of spaces between the columns in a report. The default is 1. 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. Sets the character used to underline headings. Standard characters are '-' and '='. SET Parameters (continued) 8-38
262 Setting Report Parameters The 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 TAPE CODE NAME Tape Reven C American Graffiti $ Catch 22 $ Girl Friday $22.68 Help $ ********** avg $ sum $1, R Gone With The Wind $ Love Story $47.50 Tammy $3.18 ********** avg $ sum $ Using UniData SQL
263 Wrapping Text Vertically The 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 WHERE sql> CATEGORIES IN ("C","R","S") sql> ORDER BY CATEGORIES; OLD CLASSIC VIDEO STORE ANNUAL INCOME ANALYSIS REPORT CATEGORY: C Type of Vide C VIDEO TAPE NAME American Graffiti ANNUAL INCOME Type of Vide VIDEO TAPE NAME Catch 22 ANNUAL INCOME Type of Vide VIDEO TAPE NAME Girl Friday ANNUAL INCOME Type of Vide VIDEO TAPE NAME Help ANNUAL INCOME OLD CLASSIC VIDEO STORE ANNUAL INCOME ANALYSIS REPORT CATEGORY: C ********** Start break line ********** ANNUAL INCOME s sum ANNUAL INCOME s avg ********** Finish of Break **********... CATEGORY: S OLD CLASSIC VIDEO STORE ANNUAL INCOME ANALYSIS REPORT ********** Start break line ********** ANNUAL INCOME s sum ANNUAL INCOME s avg ********** Finish of Break ********** 8-40
264 Displaying Report Environment Parameters To 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 23 sql> SHOW NEWPAGE; Newpage is Using UniData SQL
265 Preparing Complex Reports This 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 PERCENT NAME NAME INCOME STORE C American Graffiti $ Catch 22 $ Girl Friday $ Help $ $1, R Gone With The Wind $ Love Story $ Tammy $ $ Producing a Complex Report Complete 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
266 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 TAPES sql> UNNEST CATEGORIES sql> WHERE CATEGORIES IN ("C","R","S"); SUM(Tape record(s) calculated 8-43 Using UniData SQL
267 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/ *100 sql> FROM CATEGORIES X,TAPES Y sql> UNNEST CATEGORIES sql> WHERE CATEGORIES IN ("C","R","S") sql> AND X.@ID = Y.CATEGORIES sql> ORDER BY CATEGORIES; Category Type Tape Tape Rev INCOME/ * Comedy American Graffiti Comedy Catch Comedy Girl Friday Comedy Help Romance Gone With The Wind Romance Love Story Romance Tammy Science Fiction Science Fiction A Clockwork Orange Science Fiction Flash Gordon Science Fiction The Stalker 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
268 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" SKIP sql> CENTER "ANNUAL INCOME ANALYSIS REPORT" SKIP; sql> BTITLE ON; sql> BTITLE SKIP 2 CENTER "FISCAL YEAR "; sql> SELECT X.NAME CNAME,Y.NAME TNAME, sql> INCOME,INCOME/ *100 PS sql> FROM CATEGORIES X,TAPES Y sql> UNNEST CATEGORIES WHERE CATEGORIES IN ("C","R","S") sql> AND X.@ID = Y.CATEGORIES ORDER BY CATEGORIES; 8-45 Using UniData SQL
269 The output looks like this: OLD CLASSIC VIDEO STORE ANNUAL INCOME ANALYSIS REPORT CATEGORY VIDEO TAPE ANNUAL PERCENT NAME NAME INCOME STORE Comedy American Graffiti $ Catch 22 $ Girl Friday $ Help $ ********** sum $1, Romance Gone With The Wind $ Love Story $ Tammy $ ********** sum $ Science Fi 2001 $ FISCAL YEAR OLD CLASSIC VIDEO STORE ANNUAL INCOME ANALYSIS REPORT CATEGORY VIDEO TAPE ANNUAL PERCENT NAME NAME INCOME STORE A Clockwork Orange $ Flash Gordon $ The Stalker $ ********** sum $1, FISCAL YEAR Finalizing the Report You 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
270 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" SKIP sql> CENTER "ANNUAL INCOME ANALYSIS REPORT" SKIP; sql> BTITLE ON; sql> BTITLE SKIP 2 CENTER "FISCAL YEAR "; sql> SELECT X.NAME DUMMY,X.NAME CNAME,Y.NAME TNAME, sql> INCOME,INCOME/ *100 PS sql> FROM CATEGORIES X,TAPES Y sql> 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 Using UniData SQL
271 The output looks like this: OLD CLASSIC VIDEO STORE ANNUAL INCOME ANALYSIS REPORT CATEGORY VIDEO TAPE ANNUAL PERCENT NAME NAME INCOME STORE Comedy American Graffiti $ Catch 22 $ Girl Friday $ Help $ $1, Romance Gone With The Wind $ Love Story $ Tammy $ $ Science Fi 2001 $ FISCAL YEAR
272 Chapter 9: Security and Administration Chapter 9 UniData SQL Security Viewing Privileges Granting Privileges GRANT Revoking Privileges REVOKE Converting Files for UniData SQL Requirements CONVERT.SQL Converting Demo Tables
273 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
274 UniData SQL Security When 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, 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
275 Viewing Privileges UniData 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
276 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 Administrator instead of root. sql> SELECT * FROM privilege; privilege access field grant_op grantor grantee *CATEGORIES ALL 1 root PUBLIC 0*ENGLISH.MSG ALL 1 root PUBLIC PUBLIC*CTLGTB SELECT 0 root INSERT 0 root DELETE 0 root UPDATE ALL 0 root 1210*sysobjects OWNER PUBLIC PUBLIC*syscolumns SELECT 0 user INSERT 0 user DELETE 0 user UPDATE ALL 0 user 0*CUSTOMER ALL 1 root PUBLIC 1210*INVENTORY_LINE_ITEM_M OWNER V_SUB SELECT 0 root INSERT 0 root DELETE 0 root UPDATE ALL 0 root 1210*SQLTables OWNER PUBLIC 0*_REPORT_ ALL 1 root PUBLIC 1210*INVENTORY_NF_SUB OWNER SELECT 0 root INSERT 0 root DELETE 0 root UPDATE ALL 0 root PUBLIC*CLIENTS SELECT 0 root INSERT 0 root DELETE 0 root UPDATE ALL 0 root 1210*sysalternates OWNER PUBLIC 0*CTLGTB ALL 1 root PUBLIC 0*_SCREEN_ ALL 1 root PUBLIC 0* V VIEW ALL 1 root 9-5 Using UniData SQL
277 PUBLIC 1210*INVENTORY_NF *INVENTORY_Accounting OWNER OWNER SELECT 0 root INSERT 0 root DELETE 0 root UPDATE ALL 0 root SELECT *SQLColumns OWNER PUBLIC 0*&MAP& ALL 1 root PUBLIC PUBLIC*SQLStatistics SELECT 0 user INSERT 0 user DELETE 0 user UPDATE ALL 0 user PUBLIC*STAFF SELECT 0 root INSERT 0 root DELETE 0 root UPDATE ALL 0 root 74 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
278 Granting Privileges Initially, 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! GRANT Use 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
279 Parameters The following table describes each parameter of the syntax. Privilege ALL PRIVILEGES privilege ON table_spec TO PUBLIC TO user_name WITH GRANT OPTION Description 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. 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. Specifies the table, subtable, or view on which to grant privileges. Grants privilege to all users who have access to the server machine. Grants access to the user specified by user_name. Gives the recipient(s) permission to grant the privileges they acquired on this table, subtable, or view. GRANT Parameters 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; 9-8
280 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. 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, 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
281 Revoking Privileges UniData 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. REVOKE Use 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
282 Examples of Granting and Revoking Privileges GRANT Sam: GRANT SELECT ON TABLE1 TO Sarah; TABLE1 owner: Sam TABLE1 owner: Sam Sarah s privileges: select Sarah: CREATE VIEW V1 ON TABLE1; TABLE1 owner: Sam Sarah s privileges: select V1 owner: Sarah privileges: select Sam: GRANT UPDATE ON TABLE1 TO Sarah; TABLE1 V1 owner: Sam Sarah s privileges: select update owner: Sarah privileges: select update 9-11 Using UniData SQL
283 REVOKE Sam: GRANT SELECT ON TABLE1 TO Sarah; TABLE1 owner: Sam TABLE1 owner: Sam Sarah s privileges: select Sarah: CREATE VIEW V1 ON TABLE1; TABLE1 V1 owner: Sam Sarah s privileges: select owner: Sarah Sarah s privileges: select Sam: REVOKE SELECT ON TABLE1 FROM Sarah; TABLE1 owner: Sam (view has been dropped) 9-12
284 GRANT ase 1 Sam: GRANT ALL PRIVILEGES ON TABLE1 TO Sarah; TABLE1 owner: Sam ase 2 TABLE1 owner: Sam Sarah s privileges: select delete update insert Sam: GRANT SELECT, DELETE ON TABLE1 TO Sarah WITH GRANT OPTIO Sam: GRANT UPDATE ON TABLE 1 TO Sarah; TABLE1 owner: Sam TABLE1 owner: Sam Sarah s privileges: select with grant option delete with grant option update Sam: GRANT UPDATE ON TABLE 1 TO SARAH; TABLE1 owner: Sam Sarah s privileges: select with grant option delete with grant option update Tom s privileges: select delete 9-13 Using UniData SQL
285 Converting Files for UniData SQL UniData 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 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
286 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 information 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. Requirements You 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 Requirements For 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 characters Numbers Special characters: #, and $ The first character of the name must be an alphabetic character, underscore (_), or at symbol (@) Using UniData SQL
287 Note: If you plan to access the data in a table, subtable, or view through ODBC, do not #, 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.SQL Use the CONVERT.SQL ECL command to convert files for UniData SQL. Syntax CONVERT.SQL [filename] [length] [CHECKONLY FORCE] [PUBLIC [privilege]] 9-16
288 Parameters The following table describes the parameters for this command. Parameter filename Description 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. length Specifies the length of the input file name (maximum is 30 characters). CHECKONLY FORCE PUBLIC privilege 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. 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. CONVERT.SQL Parameters 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 Using UniData SQL
289 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 used checking file 'test.example'... missing or illegal S_M spec for field UP_NAME enter [S/MV/MS/M]S S_M spec of field 'UP_NAME' has been changed to 'S' invalid FMT ''in field 'ACT' enter new FMT [number[r8r FMT spec of field 'ACT' has been changed to '8R' 2 conversions have been made to dictionary file name 'test.example' will be changed to 'test_example' enter <CR> to accept, or enter your own synonym name: INVENTORY file name 'test.example' will be changed to 'INVENTORY' file synonym 'INVENTORY' has been added to VOC 1 file has been converted Converting Demo Tables When 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 privileges. 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: CUSTOMER TAPES CATEGORIES STUDENT 9-18
290 STAFF COURSES CLIENTS ORDERS INVENTORY 9-19 Using UniData SQL
291 Chapter 10: UniData SQL Transaction Processing Chapter 10 Benefits of UniData SQL TP ACID Properties UniData SQL TP and Other UniData Products UniData SQL TP and RFS UniData SQL TP and UniBasic Transaction Semantics Initiation Termination UniData SQL TP Locks Other Types of Locks Transaction Isolation Types of Transaction Errors UniData SQL Isolation Levels UniData SQL TP Commands TP Commands Transaction-Initiating Commands Unsupported Commands SET DISPLAY TPMESSAGE SET TRANSACTION COMMIT ROLLBACK AUTO COMMIT LOCK TABLE Examples of UniData SQL TP Example 1 Read Committed vs. Repeatable Read Default Transaction Settings Other UniData SQL TP Considerations
292 10-2 Using UniData SQL System Administration Performance Interaction of UniData SQL with Other Transactional Environments Tips on Transactions Optimizing Performance Limitations
293 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
294 Benefits of UniData SQL TP You 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 Properties UniData SQL TP provides ACID properties: atomicity, consistency, isolation, and durability. See Administering the Recoverable File System for a description of each of these properties Using UniData SQL
295 UniData SQL TP and Other UniData Products The ability of UniData SQL to perform transaction processing is dependent on your use of other UniData products. UniData SQL TP and RFS UniData 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 UniBasic UniData 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: We recommend 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
296 Transaction Semantics Initiation A transaction is initiated when UniData SQL encounters the first transactioninitiating statement after a user logs into UniData SQL or after a previous transaction terminates. Termination A 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 terminates abnormally. Note: You cannot turn off UniData SQL TP Using UniData SQL
297 UniData SQL TP Locks UniData SQL TP uses an automatic locking mechanism to implement different isolation schemes. UniData SQL employs a record-locking mechanism and two lock modes: Shared Exclusive 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 Locks To 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
298 Transaction Isolation Ideally, the execution of concurrent transactions produces the same effect as if these transactions were executed serially. This highest level of isolation is called serializable. 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 Errors ANSI 92 defines the levels of isolation in terms of the types of violations of serializability 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 Using UniData SQL
299 Example of a Dirty Read In this example, transaction 2 retrieves a value that no longer exists after the rollback. Transaction 1 Transaction 2 attr 1 Value SELECT attr1 FROM T WHERE ID=123 UPDATE T SET attr1=2 WHERE ID= SELECT attr1 FROM T WHERE ID=123 2 ROLLBACK 1 Dirty Read Example Example of an Unrepeatable Read In this example, transaction 2 retrieves an attribute twice, obtaining two different values. Transaction 1 Transaction 2 attr 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 Unrepeatable Read Example
300 Example of a Phantom In this example, transaction 1 executes the same query twice, but obtains an additional value in the second result set. Transaction 1 Transaction 2 Values Retrieved SELECT attr1 FROM T WHERE attr2="a" attr1=1 attr1=2 SELECT attr1 FROM T WHERE attr2="a" INSERT INTO T(id,attr1,attr2) values(1,3,"a") COMMIT Phantom Example attr1=1 attr1=2 attr1=3 UniData SQL Isolation Levels For 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 committed or aborted Using UniData SQL
301 Summary of Isolation Levels The table below summarizes the application of isolation levels in UniData SQL. 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) Summary of Isolation Levels 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
302 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. 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 readonly 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 Using UniData SQL
303 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: If UniData SQL can access a record directly, as in a case where the target 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
304 This transaction locks only two records, since UniData SQL performs query optimization 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, Chapter 7: Creating and Querying Views. sql> SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; sql> SELECT * FROM ORDERS WHERE ID='912' OR ID='913'; Transaction started. Order Order Order Client Number Date Time Number Product Nu Color Qty Price /13/ :30PM N/A 6 $ /13/ :36PM Gray 5 $ records listed sql> DELETE FROM ORDERS '913'; 1 record(s) deleted or updated. sql> COMMIT; Transaction committed. 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. Order Order Order Client Number Date Time Number Product Nu Color Qty Price /13/ :30PM N/A 6 $ 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 Using UniData SQL
305 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
306 UniData SQL TP Commands TP Commands UniData SQL TP consists of the following commands: SET DISPLAY SET DISPLAY TPMESSAGE COMMIT ROLLBACK AUTO COMMIT LOCK TABLE Transaction-Initiating Commands The following commands initiate transactions: SELECT INSERT UPDATE DELETE LOCK TABLE Unsupported Commands An 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 TABLE GRANT REVOKE Using UniData SQL
307 ! (shell escape) SET TRANSACTION AUTO COMMIT {ON OFF} 10-17
308 SET DISPLAY TPMESSAGE Syntax SET DISPLAY TPMESSAGE [ON OFF] Description The SET command option DISPLAY TPMESSAGE turns on or off display of transaction 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 Examples The following example demonstrates turning on display of transaction start and transaction commit messages: sql> SET DISPLAY TPMESSAGE ON; Using UniData SQL
309 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, , 10); Transaction started. 1 record(s) created. Transaction committed. sql> SELECT * FROM INVENTORY WHERE ID = "99999"; Transaction started. INVENTORY Inventory Date Inventory Time Product Name Features 133 MHz CPU, 25-in. SVGA Monitor, Keyboard, Mouse,Microsoft Office Color Quanti Price Reorde Black 50 $1, records listed Transaction committed
310 SET TRANSACTION Syntax SET TRANSACTION [READ ONLY READ WRITE] ISOLATION LEVEL{READ UNCOMMITTED READ COMMITTED REPEATABLE READ SERIALIZABLE} Description The 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 Administering UniData. Note: SET TRANSACTION is included in the SET section of the UniData SQL Commands Reference Using UniData SQL
311 Parameters The following table describes each parameter of the syntax. Parameter READ ONLY READ WRITE ISOLATION LEVEL Description Specifies that the next transaction is read-only. Specifies that the next transaction is read-write. Select one of the following four isolation levels: READ UNCOMMITTED READ COMMITTED REPEATABLE READ SERIALIZABLE For details on isolation levels, see UniData SQL Isolation Levels on page SET TRANSACTION Parameters Example The 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-21
312 COMMIT Syntax COMMIT [WORK] Description The 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 Using UniData SQL
313 ROLLBACK Syntax ROLLBACK [WORK] Description The 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
314 AUTO COMMIT Syntax AUTO COMMIT [ ON OFF ] Description AUTO COMMIT ON causes each statement to immediately commit. Parameters The following table describes each parameter of the syntax. Parameter ON OFF no option Description Each UniData SQL statement is immediately committed, releasing all locks. The default is interactive mode Several statements can be combined into one transaction. Set AUTO COMMIT OFF to be able to commit or roll back a set of statements as a single unit. Displays the current setting of AUTO COMMIT. AUTO COMMIT Parameters 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 Using UniData SQL
315 Example The 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
316 LOCK TABLE Syntax LOCK TABLE table_name [,table_name...] IN {SHARE EXCLUSIVE} MODE [NOWAIT] Description LOCK 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 Using UniData SQL
317 Parameters The following table describes each parameter of the syntax. Parameter table_name IN SHARE MODE IN EXCLUSIVE MODE NOWAIT Description Specifies the table to be locked. Indicates that a shared lock is to be placed on the table. Indicates that an exclusive lock is to be placed on the table. 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. LOCK TABLE Parameters 10-27
318 Examples of UniData SQL TP The following examples illustrate how different locking schemes affect isolation levels with the ORDERS database file. ID F1 F2 2 4 a 8 3 a 1 3 b 3 2 c 5 3 d 6 1 b 7 4 a Attributes in ORDERS Database Example 1 Read Committed vs. Repeatable Read This example demonstrates a nonrepeatable read: different results are obtained from the same SELECT statement in steps 1 and 4. 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 ) Read Committed Isolation Level Using UniData SQL
319 In the next example, transaction 1 is executing with the isolation level RR (Repeatable Read), thus preventing nonrepeatable reads by either transaction. 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; Repeatable Read Isolation Level 10-29
320 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) 2 INSERT INTO ORDERS VALUES (4,4, b ) 3 COMMIT; 4 SELECT F1 FROM ORDERS WHERE F1= 4 (result records 2,4,7) Repeatable Read Isolation Level Using UniData SQL
321 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. Order Order Order Client Number Date Time Number Product Nu Color Qty Price /28/ :34PM Gray 1 $1, 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: You can override the default AUTO COMMIT option default (ON). In this example, AUTO COMMIT is OFF for all subsequent UniData SQL transactions 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
322 After you turn AUTO COMMIT OFF, you must execute the COMMIT command to terminate the transaction. :SQL sql> SET DISPLAY TPMESSAGE ON; sql> AUTO COMMIT OFF; sql> SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; sql> SELECT * FROM ORDERS WHERE ID='970'; Transaction started. Order Order Order Client Number Date Time Number Product Nu Color Qty Price /15/ :00AM Gray 5 $ records listed sql> UPDATE ORDERS SET QTY='10'WHERE ID='970'; 1 record(s) updated. sql> COMMIT; Transaction committed. sql> QUIT : 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; Order Order Order Client Number Date Time Number Product Nu Color Qty Price /13/ :30PM N/A 6 $ /28/ :34PM Gray 1 $1, /14/ :00PM Gray 10 $1, Using UniData SQL
323 .. sql> DELETE FROM ORDERS WHERE ID='970'; 1 record(s) deleted or updated. Transaction committed. sql> QUIT : Example 4 Immediately Committing 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; Order Order Order Client Number Date Time Number Product Nu Color Qty Price /13/ :30PM N/A 6 $ /28/ :34PM Gray 1 $1, :SQL UPDATE ORDERS SET QTY='1' WHERE ID='970'; 1 record(s) updated
324 Other UniData SQL TP Considerations This section outlines various parts of the UniData system impacted by UniData SQL TP. These areas are: System Administration Performance Interaction 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/ud73/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 Level An environment variable specifies the default isolation level for this installation (the default is READ COMMITTED if this variable is not specified). DEFAULT_ISO_LEVEL Using UniData SQL
325 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. Performance Since 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 performance. To reduce the number of lock requests, we recommend 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 applications 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 Deadlocks In 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
326 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. Step Transaction 1 Transaction 2 1 lock record1 update record1 2 lock record2 update record2 3 lock record2 4 lock record1 Deadlock Example Interaction of UniData SQL with Other Transactional Environments Although nested transactions are not supported in UniData and UniData SQL transaction 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 TRANSACTION COMMIT or TRANSACTION ABORT, are allowed within the subroutine Using UniData SQL
327 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. 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
328 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. 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 Using UniData SQL
329 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. 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 subsequent 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
330 Tips on Transactions Optimizing Performance The 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 Using UniData SQL
331 Warning: If users are mixing RFS and non-rfs files in a single transaction, full ACID properties are not guaranteed. Statements Excluded from Transaction Processing Currently, UniData SQL transaction processing does not support SQL DDL statements. 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: GRANT REVOKE SET 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)
332 Chapter 11: UniData SQL and 1NF Mapping Chapter 11 Terminology NF Mapping NF2 Data Model vs. 1NF Data Model What Is a 1NF Mapping View? Subtables Rules for Updating Subtables Primary and Foreign Keys Creating Subtables Creating Keys Examples of Read-Only Mapping Creating a View for Singlevalued Attributes Creating a View for the Multivalued Attribute Creating a View for Multivalued and Multi-Subvalued Attributes Examples of Updatable Mapping Create a Nested Level 0 Subtable Create a Nested Level 1 Subtable Create a Nested Level 2 Subtable Updatable Mapping Commands CREATE SUBTABLE NLn_KEY DROP SUBTABLE
333 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. We recommend that you perform a backup of your system before upgrading. This chapter includes the following sections: Terminology 1NF Mapping Subtables Examples of Read-Only Mapping Examples of Updatable Mapping Updatable Mapping Commands 11-2
334 11-3 Using UniData SQL Terminology It 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.
335 Record ID Commonly known in UniData terms as 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 multisubvalued 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 multi-subvalued attributes are nested subrelations. Within each association, multivalued and multisubvalued 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 multi-subvalued 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 information 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
336 1NF Mapping 1NF mapping enables ODBC-compliant applications to access data stored in UniData (1NF) tables. The following definitions will help you understand the differences between the 1NF format and the UniData Nested Relational (NF2) data structure. NF2 Data Model vs. 1NF Data Model Before 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, multivalued, 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 Using UniData SQL
337 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_TIME sql> 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_ITEMS sql> AS SELECT ID, PRODUCT_NO, COLOR, QTY, PRICE sql> 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_ADDRESS sql> AS SELECT ID, ADDRESS sql> FROM ORDERS sql> UNNEST ADDRESS; View ORDER_ADDRESS created 11-6
338 Subtables A 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 unassociated multi-subvalued attributes. These subtables are linked through primary and foreign keys. Rules for Updating Subtables The 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 Using UniData SQL
339 Primary and Foreign Keys To 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. 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 Primary and Foreign Keys for Subtables 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
340 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 information 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 attributes, not the order in which they are stored. In a UniData table though, the order in which values of a multivalued or a multisubvalued 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 Using UniData SQL
341 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_TIME sql> FROM ORDERS sql> PRIMARY KEY ID; 11-10
342 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_NL1 sql> AS SELECT ID, PRODUCT_NO, PROD_NAME sql> FROM ORDERS sql> UNNEST PRODUCT_NO, PROD_NAME sql> PRIMARY KEY ID, PRODUCT_NO sql> 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 Using UniData SQL
343 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 multi-subvalued attributes are unnested. By including the primary key attributes 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 subordinate 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_NL2 sql>as SELECT ID, PRODUCT_NO, COLOR, QTY, PRICE sql>from ORDERS sql>unnest PRODUCT_NO, COLOR, QTY, PRICE sql>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 ORDERS sql>unnest PRODUCT_NO, COLOR, QTY, PRICE sql>primary KEY ID, PRODUCT_NO, DETAIL sql>foreign KEY ID, PRODUCT_NO REFERENCES ORDER_NL1; Creating Keys While 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
344 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 identifying 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_NL1 sql> AS SELECT ID, PRODUCT_NO, PROD_NAME sql> FROM ORDERS sql> UNNEST PRODUCT_NO, PROD_NAME sql> PRIMARY KEY ID, PRODUCT_NO sql> 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 multivalued attribute exists that can serve as a unique key, the generated key technique must be used Using UniData SQL
345 Generated Keys A 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_NO sql>from ORDERS sql>unnest PRODUCT_NO sql>primary KEY ID, PROD_ID sql>foreign KEY ID REFERENCES ORDER_NL0; 11-14
346 Examples of Read-Only Mapping This 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 TYP LOC CONV NAME FORMAT SM ASSOC D 0 ORDERS 10R S ID D 0 Order Number 10R S ORD_DATE D 1 D4/ Order Date 10R S ORD_TIME D 2 MTH Order Time 7R S CLIENT_NO D 3 Client Number 10R S PRODUCT_NO D 4 Product Number 10R MV LINE_ITEMS COLOR D 5 Color 10T MS LINE_ITEMS QTY D 6 Qty 6R MS LINE_ITEMS PRICE D 7 MD2, Price 10R MS LINE_ITEMS... LINE_ITEMS PH PRODUCT_NO PR records listed Using UniData SQL
347 Creating a View for Singlevalued Attributes This 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; Order Order Order Client Number Date Time Number /24/ :30PM /13/ :34PM /24/ :00PM /14/ :11AM /25/ :09PM /20/ :45AM /25/ :27PM /20/ :51PM /25/ :00PM /24/ :00PM Order Order Order Client Number Date Time Number /24/ :39AM /13/ :10PM records listed Creating a View for the Multivalued Attribute This example creates and uses a view for the table s multivalued attribute. It includes: ID Multivalued attribute CREATE VIEW ORDERS_MV1_VIEW AS SELECT ID, PRODUCT_NO FROM ORDERS UNNEST PRODUCT_NO WHERE ID BETWEEN 810 AND 815; View ORDERS_MV1_VIEW created
348 SELECT * FROM ORDERS_MV1_VIEW; Order Number Product Nu records listed Creating a View for Multivalued and Multi-Subvalued Attributes This view selects all multivalued and multi-subvalued attributes. All of these attributes belong to the same association. This view contains: Record ID Using UniData SQL
349 Unnested multivalued and multi-subvalued attributes CREATE VIEW ORDERS_SMV_VIEW AS SELECT ID, PRODUCT_NO, COLOR, QTY, PRICE FROM ORDERS UNNEST PRODUCT_NO, COLOR, QTY, PRICE WHERE ID BETWEEN 810 AND 815; View ORDERS_SMV_VIEW created. SELECT * FROM ORDERS_SMV_VIEW; Order Number Product Nu Color Qty Price Black 1 $ Oak grain 1 $ Black 1 $ White 2 $ Silver 1 $ Gray 2 $ Gray 1 $1, Black 3 $ N/A 1 $1, Cherry 1 $ Black 1 $ N/A 6 $ N/A 1 $ N/A 6 $ records listed 11-18
350 Examples of Updatable Mapping This 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 singlevalued 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 Subtable This first subtable combines the Record ID and selected singlevalued attributes into a updatable subtable. It contains: Record ID. Singlevalued attributes Using UniData SQL
351 Primary key to enable referencing by the NL1 subtable. CREATE SUBTABLE ORDER_NL0 AS SELECT ID, CLIENT_NO, ORD_DATE, ORD_TIME FROM ORDERS PRIMARY KEY ID; Subtable ORDER_NL0 created. SELECT * FROM ORDER_NL0 WHERE ID BETWEEN 810 AND 815; Order Client Order Order Number Number Date Time /10/ :00PM /10/ :55AM /11/ :00PM /13/ :10PM 4 records listed Create a Nested Level 1 Subtable This next subtable represents the base table s multivalued attribute. It contains: Record ID. Unnested multivalued attribute. Foreign key that references the NL0 subtable
352 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_NO FOREIGN KEY ID REFERENCES ORDER_NL0; Subtable ORDER_NL1 created. SELECT * FROM ORDER_NL1 WHERE ID BETWEEN 810 AND 815; Order Number Product Nu Product Na CD System Speaker TV Telephone Telephone Hard Drive Computer Memory Monitor CD System Printer Adapter Adapter Modem 14 records listed Create a Nested Level 2 Subtable The 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 Using UniData SQL
353 A unique key to uniquely identify rows to be updated or deleted. CREATE SUBTABLE ORDER_NL2 AS SELECT ID, PRODUCT_NO, COLOR, QTY, PRICE FROM ORDERS UNNEST PRODUCT_NO, COLOR, QTY, PRICE FOREIGN KEY ID, PRODUCT_NO REFERENCES ORDER_NL1; Subtable ORDER_NL2 created. SELECT * FROM ORDER_NL2 WHERE ID BETWEEN 810 AND 815; Order Number Product Nu Color Qty Price Black 1 $ Oak grain 1 $ Black 1 $ White 2 $ Silver 1 $ Gray 2 $ Gray 1 $1, Black 3 $ N/A 1 $1, Cherry 1 $ Black 1 $ N/A 6 $ N/A 1 $ N/A 6 $ records listed 11-22
354 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 Using UniData SQL
355 Parameters The following table describes each parameter of the syntax. Parameter subtable_name attribute_subtable_name AS SELECT query_spec PRIMARY KEY attribute_name FOREIGN KEY attribute_name REFERENCES subtable_name Description 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. 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 attributes when a generated key is used. 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). 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. 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. 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. CREATE SUBTABLE Parameters 11-24
356 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_TIME sql> FROM ORDERS sql> PRIMARY KEY ID; Subtable ORDER_NL0 created. And the following SELECT statement lists the contents of this new subtable: sql> SELECT * FROM ORDER_NL0; Order Client Order Order Number Number Date Time /13/ :30PM /28/ :34PM /14/ :00PM /05/ :11AM /24/ :09PM /15/ :00AM /04/ :45AM /24/ :27PM /13/ :39AM /02/ :10PM 193 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_NL1 sql> AS SELECT ID, PRODUCT_NO, PROD_NAME sql> FROM ORDERS sql> UNNEST PRODUCT_NO, PROD_NAME sql> PRIMARY KEY ID, PRODUCT_NO sql> FOREIGN KEY ID REFERENCES ORDER_NL0; Using UniData SQL
357 The following SELECT statement displays the (unnested) multivalued table, ORDER_NL1: sql> SELECT * FROM ORDER_NL1; Order Number Product Nu Product Na Printer Cartridge Computer Computer Memory Memory Memory Hard Drive Hard Drive Hard Drive Hard Drive Hard Drive Disk Drive... Page 32 Order Number Product Nu Product Na Adapter Modem 487 records listed The next example creates the NL2 subtable, which unnests the multisubvalued attributes. 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_NL2 AS SELECT ID, PRODUCT_NO, COLOR, QTY, PRICE, EPRICE FROM ORDERS UNNEST PRODUCT_NO, COLOR, QTY, PRICE FOREIGN KEY ID, PRODUCT_NO REFERENCES ORDER_NL1; Subtable ORDER_NL2 created
358 This final example displays a portion of the NL2 subtable: sql> SELECT * FROM ORDER_NL2; Order Number Product Nu Color Qty Price Extended Pri N/A 6 $ $ Gray 1 $1, $1, Gray 10 $1, $13, Gray 5 $ $ Standard 25 $ $10, Yellow 13 $29.97 $ Silver 15 $48.82 $ Silver 999 $34.97 $34, 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 Using UniData SQL
359 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 incremented for the COLOR attribute value Green, even though no value is present in the QTY attribute: sql> SELECT * FROM ORDERS; ORDER_NUM CLIENT PRODUCT_NO COLOR QTY CNT 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 ORDERS sql> UNNEST PRODUCT_NO; ORDER_NUM ODATE TIME CLIENT CNT /13/ :30PM /28/ :34PM /14/ :00PM /05/ :11AM /05/ :11AM /05/ :11AM /05/ :11AM /05/ :11AM /24/ :09PM /24/ :09PM /24/ :09PM /24/ :09PM /24/ :09PM /02/ :10PM records listed 11-28
360 NL2_KEY The following SELECT statement includes a counter for the multi-subvalued attributes COLOR and QTY: sql> SELECT ID, CLIENT_NO, PRODUCT_NO, sql> COLOR, QTY, NL2_KEY(COLOR, QTY) sql> FROM ORDERS; ORDER_NUM CLIENT PRODUCT_NO COLOR QTY CNT N/A Gray Gray Almond Gray White 60 1 Almond Gray Black 50 1 Red 50 2 Blue Red 3 1 Blue 3 2 Gray Red 3 1 Blue 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 Using UniData SQL
361 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 AS sql> SELECT ID, ORD_DATE, ORD_TIME, CLIENT_NO sql> FROM ORDERS sql> PRIMARY KEY ID; Subtable ORDERS_TST created. sql> DROP SUBTABLE ORDERS_TST; Subtable ORDERS_TST has been dropped
362 Chapter 12: Null and Missing Values Chapter 12 What Are Missing Values? What Are Null Values? Effects of Null and Missing Values in UniData SQL Null and Missing Values in ODBC Working with Null Values Points to Remember Examples
363 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, we recommend 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 attribute In 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 Using UniData SQL
364 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. Example The following example demonstrates the results obtained by unnesting associated multivalued attributes. Attributes A and B are associated. Multivalued attribute A: 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. 12-3
365 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. 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 Using UniData SQL
366 Effects of Null and Missing Values in UniData SQL The 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 WHERE (retrieves rows based on values in a particular attribute) Aggregation: MIN, MAX, SUM, AVG, COUNT COUNT(*) Off IS NULL selects rows containing missing values. IS NOT NULL excludes rows containing missing values. Missing values are included in calculations. Missing values are included in count. On IS NULL retrieves rows containing null values. IS NOT NULL excludes rows containing null values. Missing values are included in calculations. Null values are excluded from calculations. 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 < 0 If index is used: missing is smaller than any other number. Null and Missing Values in UniData SQL 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. 12-5
367 UniData SQL Operation Null Value Handling UPDATE TABLE ORDERS SET X = NULL INSERT INTO TABLE ORDERS (ID, ATTR1, ATTR2) VALUES(1, NULL, "X") Changes X to a missing value. Inserts a missing value into ATTR1. Changes X to the null value. Inserts the null value into ATTR1. INSERT INTO TABLE ORDERS (ID,ATTR2) VALUES(1,"X") Inserts a missing value into ATTR1. Null and Missing Values in UniData SQL (continued) Inserts a missing value into ATTR Using UniData SQL
368 Null and Missing Values in ODBC UniData 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 WHERE (retrieves rows based on values in a particular attribute) Aggregation: MIN, MAX, SUM, AVG, COUNT Off IS NULL retrieves rows containing missing values. IS NOT NULL excludes rows containing missing values. Missing values are included in calculations. This does not conform to ANSI standards. On IS NULL retrieves rows containing null and missing values. IS NOT NULL excludes rows containing null and missing values. Null and missing values are excluded from calculations. COUNT(*) Missing values are included in count. Null and Missing Values through ODBC Null and missing values are included in count. 12-7
369 ODBC Operation Null Value Handling ORDER BY UPDATE TABLE ORDERS SET X = NULL INSERT INTO TABLE ORDERS (ID, ATTR1, ATTR2) VALUES(1, NULL, "X") 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 < 0 If index is used: missing is smaller than any other number. This does not fully comply with ANSI standards. Changes X to a missing value. Inserts a missing value into ATTR1. Null and missing values are all sorted as nulls: the lowest. They are sorted first in an ascending sort. Changes X to the null value. Inserts the null value into ATTR1. INSERT INTO TABLE ORDERS (ID,ATTR2) VALUES(1,"X") Inserts a missing value into ATTR1. Null and Missing Values through ODBC (continued) Inserts a missing value into ATTR1. This does not fully comply with ANSI standards Using UniData SQL
370 Working with Null Values With 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 configuration 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 manipulate 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
371 Examples This section provides examples of null value handling in UniData SQL with null value handling ON (udtconfig 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 STAFF sql> WHERE LNAME IS NULL; STAFF NVL(LNAME,"NULL") Dept Title NULL PSY AscProf 1 records listed Using UniData SQL
372 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 ORDERS sql> UNNEST PRODUCT_NO sql> WHERE PRODUCT_NO BETWEEN AND ORDER BY PRODUCT_NO; Product Na Product Nu Price Camcorder N N N N $ $ $ $ ********** cnt 4 max $ min $ std $0.00 sum $ var $ 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(*)
373 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; STAFF Last Nam Eades 6 Masters 4 8 Fried 4 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 STAFF WHERE SAL > 30000; CNT(Last 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 STAFF WHERE SAL > 30000; COUNT(*) record(s) calculated Using UniData SQL
374 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; STAFF NVL(LNAME,"Unknown") Dept Title Eades FA Prof 6 Masters PSY Ascprof 9 Aaron PSY Counsel or 1 Fisher BUS Prof 4 Unknown PSY AscProf 7 Carnes ENG Prof 2 Otis FA AscProf 5 Gibson SPA Prof 8 Fried BUS Dean 9 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 < sql> NAME, ZIP FROM CUSTOMER WHERE ZIP < 10050; Cust Customer Name Zip C Jones, Samuel records listed 12-13
375 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> LNAME, SAL, SAL +(SAL/20) "New Pay" sql> FROM STAFF; STAFF Last Nam Salary New Pay Eades 42, Masters 35, Aaron 19, Fisher N N 4 James 32, Carnes 29, Otis 25, Gibson 26, Fried 98, records listed Using UniData SQL
376 Appendix A: UniData SQL Reserved Words Appendix A 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 statements, your statement or program could result in an error.
377 Using Reserved Words The 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 Using UniData SQL
378 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
379 Reserved Words UPDATE VALUE VALUES VARIANCE VIEW WHEN WHERE WITH YEAR UniData SQL Reserved Words (continued) A-4 Using UniData SQL
380 Appendix B: More Table Joins Appendix B 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, 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.
381 Tables for Join Examples Let 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/1024 create 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; TABLE_AB attrib_num attrib_char aaa 2 2 bbb 2 records listed select * from TABLE_CD; TABLE_CD attrib_num attrib_char ccc 3 10 ddd 2 records listed B-2 Using UniData SQL
382 Examples of Outer Joins Full Outer Join A 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; TABLE_AB attrib_num TABLE_CD attrib_num records listed Joining Tables on Attributes of the Same Name This 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 table1.fieldname = table2.fieldname using(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); TABLE_AB attrib_num TABLE_CD attrib_num records listed ON B-3
383 Full Outer Join Combined with WHERE Condition You 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_num where TABLE_AB.@ID > 1; TABLE_AB attrib_num TABLE_CD attrib_num records listed B-4 Using UniData SQL
384 Joining on Multivalued Attributes You 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_price from CUSTOMER a FULL JOIN TAPES b ON a.tapes_rented = b.@id unnest a.tapes_rented; CUSTOMER Customer Name Tapes Rental C TAPES Retail C 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 B Partner, Bonnie B2297 $2.50 B Partner, Bonnie B914 $1.06 B V Page 2 CUSTOMER Customer Name Tapes Rental C TAPES Retail C Fischer, Carrie V110 $2.52 V Belafonte, V1234 Harry 8 Jones, Mable V1249 $3.54 V Jones, Samuel V1254 $3.15 V Chase, Carl V1254 $3.15 V James, Bob V2001 $3.75 V Smith, Harry V2001 $3.75 V Steven Spender V Steven Spender V Jones, Samuel V Jones, Bob V4341 $4.54 V Jones, Mable V4499 $4.54 V Chase, Carl V4951 $2.50 V Smith, Harry V5004 $4.40 V Faber, Harry V5151 $3.54 V Jamieson, Dale V6670 $6.75 V B-5
385 V Smith, Harry V8181 $5.50 V Jones, Samuel V8481 $6.75 V Page 3 CUSTOMER Customer Name Tapes Rental C TAPES Retail C Chase, Carl V8481 $6.75 V Jones, Freddie V9431 $4.50 V Darrell Corden V Barrie, Dick V996 $4.54 V Bowie, David V9961 $5.05 V v v records listed Left Outer Join A 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; TABLE_AB attrib_num TABLE_CD attrib_num records listed Left Outer Join Combined with WHERE Condition You 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_num where TABLE_AB.attrib_num = 2; TABLE_AB attrib_num TABLE_CD attrib_num records listed B-6 Using UniData SQL
386 Right Outer Join A 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; TABLE_AB attrib_num TABLE_CD attrib_num records listed Right Outer Join Combined with WHERE Condition You 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_num from TABLE_AB right outer join TABLE_CD on TABLE_AB.attrib_num = TABLE_CD.attrib_num where TABLE_CD.attrib_num!= 3; TABLE_AB attrib_num TABLE_CD attrib_num records listed B-7
387 Joining Three Tables You 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_num from 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.@id where t3.@id > 1; TABLE_AB attrib_num TABLE_CD attrib_num TABLE_CD attrib_num records listed select TABLE_AB.@ID, TABLE_AB.attrib_num, t2.@id, t2.attrib_num, t3.@id, t3.attrib_num from TABLE_AB full outer join TABLE_CD t2 using (attrib_num) full outer join TABLE_CD t3 using (@ID) where t3.@id > 1; TABLE_AB attrib_num TABLE_CD attrib_num TABLE_CD attrib_num records listed Joining Tables in a Subquery You 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); TABLE_AB attrib_num attrib_char aaa 1 records listed B-8 Using UniData SQL
388 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 Results You 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_num order by TABLE_AB.attrib_num; TABLE_AB attrib_num TABLE_CD attrib_num 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_num from TABLE_AB full outer join TABLE_CD using (attrib_num) order by TABLE_CD.@ID; TABLE_AB attrib_num TABLE_CD attrib_num records listed Combining Results of Queries Containing Joins You can combine multiple queries, each of which join tables, subtables, or views by using the keyword UNION. B-9
389 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_num from TABLE_AB left outer join TABLE_CD using (@ID) union select TABLE_CD.@ID, TABLE_CD.attrib_num, TABLE_AB.@ID, TABLE_AB.attrib_num from TABLE_CD right outer join TABLE_AB using (attrib_num); TABLE_AB attrib_num TABLE_CD attrib_num records listed Creating a View from Joined Tables This 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; v1 v2 v3 v records listed B-10 Using UniData SQL
390 Examples of Inner Joins This 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.attrib_num, TABLE_CD.attrib_num from TABLE_AB join TABLE_CD on TABLE_AB.attrib_num = TABLE_CD.attrib_num; TABLE_AB attrib_num TABLE_CD attrib_num 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_num from TABLE_AB inner join TABLE_CD on TABLE_AB.attrib_num = TABLE_CD.attrib_num; TABLE_AB attrib_num TABLE_CD attrib_num records listed select TABLE_AB.@ID, TABLE_AB.attrib_num, TABLE_CD.@ID, TABLE_CD.attrib_num from TABLE_AB inner join TABLE_CD using(attrib_num); TABLE_AB attrib_num TABLE_CD attrib_num records listed B-11
391 Stacking JOIN Clauses The 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_num from 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; TABLE_AB attrib_num TABLE_CD attrib_num TABLE_CD attrib_num 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_num from TABLE_AB inner join TABLE_CD t2 using (attrib_num) inner join TABLE_CD t3 using (@ID); TABLE_AB attrib_num TABLE_CD attrib_num TABLE_CD attrib_num records listed Combining Inner Join Results with UNION The following two statements each join the same two tables: select TABLE_AB.@ID, TABLE_AB.attrib_num, TABLE_CD.@ID, TABLE_CD.attrib_num from TABLE_AB inner join TABLE_CD using (@ID); TABLE_AB attrib_num TABLE_CD attrib_num records listed select TABLE_CD.@ID, TABLE_CD.attrib_num, TABLE_AB.@ID, TABLE_AB.attrib_num from TABLE_CD inner join TABLE_AB using (attrib_num); TABLE_CD attrib_num TABLE_AB attrib_num records listed B-12 Using UniData SQL
392 Creating a View from an Inner Join This 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) correspond 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; v1 v2 v3 v records listed B-13
Oracle Database: SQL and PL/SQL Fundamentals
Oracle University Contact Us: 1.800.529.0165 Oracle Database: SQL and PL/SQL Fundamentals Duration: 5 Days What you will learn This course is designed to deliver the fundamentals of SQL and PL/SQL along
Oracle 10g PL/SQL Training
Oracle 10g PL/SQL Training Course Number: ORCL PS01 Length: 3 Day(s) Certification Exam This course will help you prepare for the following exams: 1Z0 042 1Z0 043 Course Overview PL/SQL is Oracle's Procedural
Oracle Database: SQL and PL/SQL Fundamentals NEW
Oracle University Contact Us: + 38516306373 Oracle Database: SQL and PL/SQL Fundamentals NEW Duration: 5 Days What you will learn This Oracle Database: SQL and PL/SQL Fundamentals training delivers the
Rocket UniVerse. External Database Access (EDA) Version 11.2.5. July2015 UNV-1125-EDA-1
Rocket UniVerse External Database Access (EDA) Version 11.2.5 July2015 UNV-1125-EDA-1 Notices Edition Publication date: July2015 Book number: UNV-1125-EDA-1 Product version: Rocket UniVerse V11.2.5 Copyright
Oracle SQL. Course Summary. Duration. Objectives
Oracle SQL Course Summary Identify the major structural components of the Oracle Database 11g Create reports of aggregated data Write SELECT statements that include queries Retrieve row and column data
Oracle Database 12c: Introduction to SQL Ed 1.1
Oracle University Contact Us: 1.800.529.0165 Oracle Database 12c: Introduction to SQL Ed 1.1 Duration: 5 Days What you will learn This Oracle Database: Introduction to SQL training helps you write subqueries,
Oracle Database: SQL and PL/SQL Fundamentals
Oracle University Contact Us: +966 12 739 894 Oracle Database: SQL and PL/SQL Fundamentals Duration: 5 Days What you will learn This Oracle Database: SQL and PL/SQL Fundamentals training is designed to
Oracle Database 10g: Introduction to SQL
Oracle University Contact Us: 1.800.529.0165 Oracle Database 10g: Introduction to SQL Duration: 5 Days What you will learn This course offers students an introduction to Oracle Database 10g database technology.
BCA. Database Management System
BCA IV Sem Database Management System Multiple choice questions 1. A Database Management System (DBMS) is A. Collection of interrelated data B. Collection of programs to access data C. Collection of data
Information Systems SQL. Nikolaj Popov
Information Systems SQL Nikolaj Popov Research Institute for Symbolic Computation Johannes Kepler University of Linz, Austria [email protected] Outline SQL Table Creation Populating and Modifying
Oracle Database 11g SQL
AO3 - Version: 2 19 June 2016 Oracle Database 11g SQL Oracle Database 11g SQL AO3 - Version: 2 3 days Course Description: This course provides the essential SQL skills that allow developers to write queries
Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff
D80198GC10 Oracle Database 12c SQL and Fundamentals Summary Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff Level Professional Delivery Method Instructor-led
Oracle Database: SQL and PL/SQL Fundamentals NEW
Oracle University Contact Us: 001-855-844-3881 & 001-800-514-06-97 Oracle Database: SQL and PL/SQL Fundamentals NEW Duration: 5 Days What you will learn This Oracle Database: SQL and PL/SQL Fundamentals
Instant SQL Programming
Instant SQL Programming Joe Celko Wrox Press Ltd. INSTANT Table of Contents Introduction 1 What Can SQL Do for Me? 2 Who Should Use This Book? 2 How To Use This Book 3 What You Should Know 3 Conventions
Oracle Database: Introduction to SQL
Oracle University Contact Us: 1.800.529.0165 Oracle Database: Introduction to SQL Duration: 5 Days What you will learn View a newer version of this course This Oracle Database: Introduction to SQL training
D61830GC30. MySQL for Developers. Summary. Introduction. Prerequisites. At Course completion After completing this course, students will be able to:
D61830GC30 for Developers Summary Duration Vendor Audience 5 Days Oracle Database Administrators, Developers, Web Administrators Level Technology Professional Oracle 5.6 Delivery Method Instructor-led
COMP 5138 Relational Database Management Systems. Week 5 : Basic SQL. Today s Agenda. Overview. Basic SQL Queries. Joins Queries
COMP 5138 Relational Database Management Systems Week 5 : Basic COMP5138 "Relational Database Managment Systems" J. Davis 2006 5-1 Today s Agenda Overview Basic Queries Joins Queries Aggregate Functions
Retrieving Data Using the SQL SELECT Statement. Copyright 2006, Oracle. All rights reserved.
Retrieving Data Using the SQL SELECT Statement Objectives After completing this lesson, you should be able to do the following: List the capabilities of SQL SELECT statements Execute a basic SELECT statement
KB_SQL SQL Reference Guide Version 4
KB_SQL SQL Reference Guide Version 4 1995, 1999 by KB Systems, Inc. All rights reserved. KB Systems, Inc., Herndon, Virginia, USA. Printed in the United States of America. No part of this manual may be
Oracle Database: Introduction to SQL
Oracle University Contact Us: +381 11 2016811 Oracle Database: Introduction to SQL Duration: 5 Days What you will learn Understanding the basic concepts of relational databases ensure refined code by developers.
3.GETTING STARTED WITH ORACLE8i
Oracle For Beginners Page : 1 3.GETTING STARTED WITH ORACLE8i Creating a table Datatypes Displaying table definition using DESCRIBE Inserting rows into a table Selecting rows from a table Editing SQL buffer
Rocket UniData. U2 Data Replication. Version 8.1.0. February 2015 UDT-810-UREP-1
Rocket UniData U2 Data Replication Version 8.1.0 February 2015 UDT-810-UREP-1 Notices Edition Publication date: February 2015 Book number: UDT-810-UREP-1 Product version: Rocket UniData 8.1.0 Copyright
Database Administration with MySQL
Database Administration with MySQL Suitable For: Database administrators and system administrators who need to manage MySQL based services. Prerequisites: Practical knowledge of SQL Some knowledge of relational
SQL Server. 1. What is RDBMS?
SQL Server 1. What is RDBMS? Relational Data Base Management Systems (RDBMS) are database management systems that maintain data records and indices in tables. Relationships may be created and maintained
Setting Up ALERE with Client/Server Data
Setting Up ALERE with Client/Server Data TIW Technology, Inc. November 2014 ALERE is a registered trademark of TIW Technology, Inc. The following are registered trademarks or trademarks: FoxPro, SQL Server,
Choosing a Data Model for Your Database
In This Chapter This chapter describes several issues that a database administrator (DBA) must understand to effectively plan for a database. It discusses the following topics: Choosing a data model for
Oracle Database: Introduction to SQL
Oracle University Contact Us: 1.800.529.0165 Oracle Database: Introduction to SQL Duration: 5 Days What you will learn This Oracle Database: Introduction to SQL training teaches you how to write subqueries,
SQL Server. 2012 for developers. murach's TRAINING & REFERENCE. Bryan Syverson. Mike Murach & Associates, Inc. Joel Murach
TRAINING & REFERENCE murach's SQL Server 2012 for developers Bryan Syverson Joel Murach Mike Murach & Associates, Inc. 4340 N. Knoll Ave. Fresno, CA 93722 www.murach.com [email protected] Expanded
Participant Guide RP301: Ad Hoc Business Intelligence Reporting
RP301: Ad Hoc Business Intelligence Reporting State of Kansas As of April 28, 2010 Final TABLE OF CONTENTS Course Overview... 4 Course Objectives... 4 Agenda... 4 Lesson 1: Reviewing the Data Warehouse...
2874CD1EssentialSQL.qxd 6/25/01 3:06 PM Page 1 Essential SQL Copyright 2001 SYBEX, Inc., Alameda, CA www.sybex.com
Essential SQL 2 Essential SQL This bonus chapter is provided with Mastering Delphi 6. It is a basic introduction to SQL to accompany Chapter 14, Client/Server Programming. RDBMS packages are generally
MySQL for Beginners Ed 3
Oracle University Contact Us: 1.800.529.0165 MySQL for Beginners Ed 3 Duration: 4 Days What you will learn The MySQL for Beginners course helps you learn about the world's most popular open source database.
CHAPTER 2 DATABASE MANAGEMENT SYSTEM AND SECURITY
CHAPTER 2 DATABASE MANAGEMENT SYSTEM AND SECURITY 2.1 Introduction In this chapter, I am going to introduce Database Management Systems (DBMS) and the Structured Query Language (SQL), its syntax and usage.
Rocket U2 Web Development Environment
Rocket U2 Web Development Environment Web Designer User s Guide Version 5.2.0 July 2015 WDE-520-ALL-UG-01 Notices Edition Publication date: July 2015 Book number: WDE-520-ALL-UG-01 Product version: Version
Microsoft Dynamics GP. Extender User s Guide
Microsoft Dynamics GP Extender User s Guide Copyright Copyright 2010 Microsoft. All rights reserved. Limitation of liability This document is provided as-is. Information and views expressed in this document,
Database Programming with PL/SQL: Learning Objectives
Database Programming with PL/SQL: Learning Objectives This course covers PL/SQL, a procedural language extension to SQL. Through an innovative project-based approach, students learn procedural logic constructs
Rocket U2 Web Development Environment
Rocket U2 Web Development Environment Web Designer User s Guide Version 5.2. October 205 WDE-52-ALL-UG-0 Notices Edition Publication date: October 205 Book number: WDE-52-ALL-UG-0 Product version: Version
How To Write Tvalue Amortization Software
TimeValue Software Amortization Software Version 5 User s Guide s o f t w a r e User's Guide TimeValue Software Amortization Software Version 5 ii s o f t w a r e ii TValue Amortization Software, Version
Database 10g Edition: All possible 10g features, either bundled or available at additional cost.
Concepts Oracle Corporation offers a wide variety of products. The Oracle Database 10g, the product this exam focuses on, is the centerpiece of the Oracle product set. The "g" in "10g" stands for the Grid
Microsoft Access 3: Understanding and Creating Queries
Microsoft Access 3: Understanding and Creating Queries In Access Level 2, we learned how to perform basic data retrievals by using Search & Replace functions and Sort & Filter functions. For more complex
Oracle. Brief Course Content This course can be done in modular form as per the detail below. ORA-1 Oracle Database 10g: SQL 4 Weeks 4000/-
Oracle Objective: Oracle has many advantages and features that makes it popular and thereby makes it as the world's largest enterprise software company. Oracle is used for almost all large application
IT2305 Database Systems I (Compulsory)
Database Systems I (Compulsory) INTRODUCTION This is one of the 4 modules designed for Semester 2 of Bachelor of Information Technology Degree program. CREDITS: 04 LEARNING OUTCOMES On completion of this
Using SQL Queries in Crystal Reports
PPENDIX Using SQL Queries in Crystal Reports In this appendix Review of SQL Commands PDF 924 n Introduction to SQL PDF 924 PDF 924 ppendix Using SQL Queries in Crystal Reports The SQL Commands feature
Introduction to SQL and SQL in R. LISA Short Courses Xinran Hu
Introduction to SQL and SQL in R LISA Short Courses Xinran Hu 1 Laboratory for Interdisciplinary Statistical Analysis LISA helps VT researchers benefit from the use of Statistics Collaboration: Visit our
IT2304: Database Systems 1 (DBS 1)
: Database Systems 1 (DBS 1) (Compulsory) 1. OUTLINE OF SYLLABUS Topic Minimum number of hours Introduction to DBMS 07 Relational Data Model 03 Data manipulation using Relational Algebra 06 Data manipulation
Microsoft Access Basics
Microsoft Access Basics 2006 ipic Development Group, LLC Authored by James D Ballotti Microsoft, Access, Excel, Word, and Office are registered trademarks of the Microsoft Corporation Version 1 - Revision
Data Tool Platform SQL Development Tools
Data Tool Platform SQL Development Tools ekapner Contents Setting SQL Development Preferences...5 Execution Plan View Options Preferences...5 General Preferences...5 Label Decorations Preferences...6
DBF Chapter. Note to UNIX and OS/390 Users. Import/Export Facility CHAPTER 7
97 CHAPTER 7 DBF Chapter Note to UNIX and OS/390 Users 97 Import/Export Facility 97 Understanding DBF Essentials 98 DBF Files 98 DBF File Naming Conventions 99 DBF File Data Types 99 ACCESS Procedure Data
Guide to SQL Programming: SQL:1999 and Oracle Rdb V7.1
Guide to SQL Programming: SQL:1999 and Oracle Rdb V7.1 A feature of Oracle Rdb By Ian Smith Oracle Rdb Relational Technology Group Oracle Corporation 1 Oracle Rdb Journal SQL:1999 and Oracle Rdb V7.1 The
DBMS Questions. 3.) For which two constraints are indexes created when the constraint is added?
DBMS Questions 1.) Which type of file is part of the Oracle database? A.) B.) C.) D.) Control file Password file Parameter files Archived log files 2.) Which statements are use to UNLOCK the user? A.)
Teach Yourself InterBase
Teach Yourself InterBase This tutorial takes you step-by-step through the process of creating and using a database using the InterBase Windows ISQL dialog. You learn to create data structures that enforce
PowerSchool Parent Portal User Guide. PowerSchool 7.x Student Information System
PowerSchool 7.x Student Information System Released December 2011 Document Owner: Documentation Services This edition applies to Release 7.1 of the [product name] software and to all subsequent releases
FileMaker 12. ODBC and JDBC Guide
FileMaker 12 ODBC and JDBC Guide 2004 2012 FileMaker, Inc. All Rights Reserved. FileMaker, Inc. 5201 Patrick Henry Drive Santa Clara, California 95054 FileMaker and Bento are trademarks of FileMaker, Inc.
Access Queries (Office 2003)
Access Queries (Office 2003) Technical Support Services Office of Information Technology, West Virginia University OIT Help Desk 293-4444 x 1 oit.wvu.edu/support/training/classmat/db/ Instructor: Kathy
How To Import A File Into The Raise S Edge
Import Guide 021312 2009 Blackbaud, Inc. This publication, or any part thereof, may not be reproduced or transmitted in any form or by any means, electronic, or mechanical, including photocopying, recording,
Business Insight Report Authoring Getting Started Guide
Business Insight Report Authoring Getting Started Guide Version: 6.6 Written by: Product Documentation, R&D Date: February 2011 ImageNow and CaptureNow are registered trademarks of Perceptive Software,
9.1 SAS. SQL Query Window. User s Guide
SAS 9.1 SQL Query Window User s Guide The correct bibliographic citation for this manual is as follows: SAS Institute Inc. 2004. SAS 9.1 SQL Query Window User s Guide. Cary, NC: SAS Institute Inc. SAS
A Comparison of Database Query Languages: SQL, SPARQL, CQL, DMX
ISSN: 2393-8528 Contents lists available at www.ijicse.in International Journal of Innovative Computer Science & Engineering Volume 3 Issue 2; March-April-2016; Page No. 09-13 A Comparison of Database
www.gr8ambitionz.com
Data Base Management Systems (DBMS) Study Material (Objective Type questions with Answers) Shared by Akhil Arora Powered by www. your A to Z competitive exam guide Database Objective type questions Q.1
4. The Third Stage In Designing A Database Is When We Analyze Our Tables More Closely And Create A Between Tables
1. What Are The Different Views To Display A Table A) Datasheet View B) Design View C) Pivote Table & Pivot Chart View D) All Of Above 2. Which Of The Following Creates A Drop Down List Of Values To Choose
DBMS / Business Intelligence, SQL Server
DBMS / Business Intelligence, SQL Server Orsys, with 30 years of experience, is providing high quality, independant State of the Art seminars and hands-on courses corresponding to the needs of IT professionals.
Client Management WalkThrough
PRACTICE CS Client Management WalkThrough version 2014.x.x TL 27716a (1/16/15) Copyright Information Text copyright 2004-2015 by Thomson Reuters. All rights reserved. Video display images copyright 2004-2015
Paper 70-27 An Introduction to SAS PROC SQL Timothy J Harrington, Venturi Partners Consulting, Waukegan, Illinois
Paper 70-27 An Introduction to SAS PROC SQL Timothy J Harrington, Venturi Partners Consulting, Waukegan, Illinois Abstract This paper introduces SAS users with at least a basic understanding of SAS data
Inquiry Formulas. student guide
Inquiry Formulas student guide NOTICE This documentation and the Axium software programs may only be used in accordance with the accompanying Ajera License Agreement. You may not use, copy, modify, or
DATABASE DESIGN AND IMPLEMENTATION II SAULT COLLEGE OF APPLIED ARTS AND TECHNOLOGY SAULT STE. MARIE, ONTARIO. Sault College
-1- SAULT COLLEGE OF APPLIED ARTS AND TECHNOLOGY SAULT STE. MARIE, ONTARIO Sault College COURSE OUTLINE COURSE TITLE: CODE NO. : SEMESTER: 4 PROGRAM: PROGRAMMER (2090)/PROGRAMMER ANALYST (2091) AUTHOR:
DIRECTV Rio Track 2 Dispatch 3 rd Party QA Truck Roll Activities Instructor Guide
Rio Track 2 Dispatch 3 rd Party QA Truck Roll Activities Table of Contents Introduction...1 Course Outline...2 Siebel (Rio) Benefits...3 Getting Started...4 Logging Onto the etrust Identity Manager...5
Structured Query Language (SQL)
Objectives of SQL Structured Query Language (SQL) o Ideally, database language should allow user to: create the database and relation structures; perform insertion, modification, deletion of data from
MOC 20461C: Querying Microsoft SQL Server. Course Overview
MOC 20461C: Querying Microsoft SQL Server Course Overview This course provides students with the knowledge and skills to query Microsoft SQL Server. Students will learn about T-SQL querying, SQL Server
Teradata SQL Assistant Version 13.0 (.Net) Enhancements and Differences. Mike Dempsey
Teradata SQL Assistant Version 13.0 (.Net) Enhancements and Differences by Mike Dempsey Overview SQL Assistant 13.0 is an entirely new application that has been re-designed from the ground up. It has been
COGNOS Query Studio Ad Hoc Reporting
COGNOS Query Studio Ad Hoc Reporting Copyright 2008, the California Institute of Technology. All rights reserved. This documentation contains proprietary information of the California Institute of Technology
Advanced Query for Query Developers
for Developers This is a training guide to step you through the advanced functions of in NUFinancials. is an ad-hoc reporting tool that allows you to retrieve data that is stored in the NUFinancials application.
Using Temporary Tables to Improve Performance for SQL Data Services
Using Temporary Tables to Improve Performance for SQL Data Services 2014- Informatica Corporation. No part of this document may be reproduced or transmitted in any form, by any means (electronic, photocopying,
Database Query 1: SQL Basics
Database Query 1: SQL Basics CIS 3730 Designing and Managing Data J.G. Zheng Fall 2010 1 Overview Using Structured Query Language (SQL) to get the data you want from relational databases Learning basic
Querying Microsoft SQL Server
Course 20461C: Querying Microsoft SQL Server Module 1: Introduction to Microsoft SQL Server 2014 This module introduces the SQL Server platform and major tools. It discusses editions, versions, tools used
ICAB4136B Use structured query language to create database structures and manipulate data
ICAB4136B Use structured query language to create database structures and manipulate data Release: 1 ICAB4136B Use structured query language to create database structures and manipulate data Modification
Performance Tuning for the Teradata Database
Performance Tuning for the Teradata Database Matthew W Froemsdorf Teradata Partner Engineering and Technical Consulting - i - Document Changes Rev. Date Section Comment 1.0 2010-10-26 All Initial document
FileMaker Server 9. Custom Web Publishing with PHP
FileMaker Server 9 Custom Web Publishing with PHP 2007 FileMaker, Inc. All Rights Reserved. FileMaker, Inc. 5201 Patrick Henry Drive Santa Clara, California 95054 FileMaker is a trademark of FileMaker,
Course ID#: 1401-801-14-W 35 Hrs. Course Content
Course Content Course Description: This 5-day instructor led course provides students with the technical skills required to write basic Transact- SQL queries for Microsoft SQL Server 2014. This course
Driver for JDBC Implementation Guide
www.novell.com/documentation Driver for JDBC Implementation Guide Identity Manager 4.0.2 January 2014 Legal Notices Novell, Inc. makes no representations or warranties with respect to the contents or use
FileMaker 11. ODBC and JDBC Guide
FileMaker 11 ODBC and JDBC Guide 2004 2010 FileMaker, Inc. All Rights Reserved. FileMaker, Inc. 5201 Patrick Henry Drive Santa Clara, California 95054 FileMaker is a trademark of FileMaker, Inc. registered
FileMaker Server 13. Custom Web Publishing with PHP
FileMaker Server 13 Custom Web Publishing with PHP 2007 2013 FileMaker, Inc. All Rights Reserved. FileMaker, Inc. 5201 Patrick Henry Drive Santa Clara, California 95054 FileMaker and Bento are trademarks
Backing up and restoring HP Systems Insight Manager 6.0 or greater data files in a Windows environment
Technical white paper Backing up and restoring HP Systems Insight Manager 6.0 or greater data files in a Windows environment Table of contents Abstract 2 Introduction 2 Saving and restoring data files
MyOra 3.0. User Guide. SQL Tool for Oracle. Jayam Systems, LLC
MyOra 3.0 SQL Tool for Oracle User Guide Jayam Systems, LLC Contents Features... 4 Connecting to the Database... 5 Login... 5 Login History... 6 Connection Indicator... 6 Closing the Connection... 7 SQL
Chapter 1: Introduction. Database Management System (DBMS) University Database Example
This image cannot currently be displayed. Chapter 1: Introduction Database System Concepts, 6 th Ed. See www.db-book.com for conditions on re-use Database Management System (DBMS) DBMS contains information
Querying Microsoft SQL Server 20461C; 5 days
Lincoln Land Community College Capital City Training Center 130 West Mason Springfield, IL 62702 217-782-7436 www.llcc.edu/cctc Querying Microsoft SQL Server 20461C; 5 days Course Description This 5-day
Microsoft Query, the helper application included with Microsoft Office, allows
3 RETRIEVING ISERIES DATA WITH MICROSOFT QUERY Microsoft Query, the helper application included with Microsoft Office, allows Office applications such as Word and Excel to read data from ODBC data sources.
5. CHANGING STRUCTURE AND DATA
Oracle For Beginners Page : 1 5. CHANGING STRUCTURE AND DATA Altering the structure of a table Dropping a table Manipulating data Transaction Locking Read Consistency Summary Exercises Altering the structure
SQL Server An Overview
SQL Server An Overview SQL Server Microsoft SQL Server is designed to work effectively in a number of environments: As a two-tier or multi-tier client/server database system As a desktop database system
Micro Focus Database Connectors
data sheet Database Connectors Executive Overview Database Connectors are designed to bridge the worlds of COBOL and Structured Query Language (SQL). There are three Database Connector interfaces: Database
ICE for Eclipse. Release 9.0.1
ICE for Eclipse Release 9.0.1 Disclaimer This document is for informational purposes only and is subject to change without notice. This document and its contents, including the viewpoints, dates and functional
Chapter 1: Introduction
Chapter 1: Introduction Database System Concepts, 5th Ed. See www.db book.com for conditions on re use Chapter 1: Introduction Purpose of Database Systems View of Data Database Languages Relational Databases
ACCELL/SQL: Creating Reports with RPT Report Writer
ACCELL/SQL: Creating Reports with RPT Report Writer 2 3 4 5 6 7 8 This manual, Creating Reports With RPT Report Writer, tells you how to develop an application report using Report Writer and gives complete
Time & Expense Entry WalkThrough
PRACTICE CS Time & Expense Entry WalkThrough Version 2014.x.x TL 27573a (01/16/2015) Copyright Information Text copyright 2004-2015 by Thomson Reuters. All rights reserved. Video display images copyright
White Paper. Blindfolded SQL Injection
White Paper In the past few years, SQL Injection attacks have been on the rise. The increase in the number of Database based applications, combined with various publications that explain the problem and
InterBase 6. Embedded SQL Guide. Borland/INPRISE. 100 Enterprise Way, Scotts Valley, CA 95066 http://www.interbase.com
InterBase 6 Embedded SQL Guide Borland/INPRISE 100 Enterprise Way, Scotts Valley, CA 95066 http://www.interbase.com Inprise/Borland may have patents and/or pending patent applications covering subject
CSC 443 Data Base Management Systems. Basic SQL
CSC 443 Data Base Management Systems Lecture 6 SQL As A Data Definition Language Basic SQL SQL language Considered one of the major reasons for the commercial success of relational databases SQL Structured
Unit 10: Microsoft Access Queries
Microsoft Access Queries Unit 10: Microsoft Access Queries Introduction Queries are a fundamental means of accessing and displaying data from tables. Queries used to view, update, and analyze data in different
New Features... 1 Installation... 3 Upgrade Changes... 3 Fixed Limitations... 4 Known Limitations... 5 Informatica Global Customer Support...
Informatica Corporation B2B Data Exchange Version 9.5.0 Release Notes June 2012 Copyright (c) 2006-2012 Informatica Corporation. All rights reserved. Contents New Features... 1 Installation... 3 Upgrade
Accounts Receivable WalkThrough
PRACTICE CS Accounts Receivable WalkThrough Version 2014.x.x TL 27675a 1/16/15 Copyright Information Text copyright 2004-2015 by Thomson Reuters. All rights reserved. Video display images copyright 2004-2015
