SQL Syntax
SQL Syntax
Syntax
December 1999
Part No. 000-6527
Published by Informix Press Informix Corporation
4100 Bohannon Drive
Menlo Park, CA 94025-1032
© 1999 Informix Corporation. All rights reserved. The following are trademarks of Informix Corporation
or its affiliates, one or more of which may be registered in the United States or other jurisdictions:
Answers OnLineTM; C-ISAM; Client SDKTM; DataBlade; Data DirectorTM; Decision FrontierTM;
Dynamic Scalable ArchitectureTM; Dynamic ServerTM; Dynamic ServerTM, Developer EditionTM;
Dynamic ServerTM with Advanced Decision Support OptionTM; Dynamic ServerTM with Extended
Parallel OptionTM; Dynamic ServerTM with MetaCube; Dynamic ServerTM with Universal Data OptionTM;
Dynamic ServerTM with Web Integration OptionTM; Dynamic ServerTM, Workgroup EditionTM;
Dynamic Virtual MachineTM; Extended Parallel ServerTM; FormationTM; Formation ArchitectTM;
Formation Flow EngineTM; Gold Mine Data Access; IIF.2000TM; i.ReachTM; i.SellTM; Illustra; Informix;
Informix 4GL; Informix InquireSM; Informix Internet Foundation.2000TM; InformixLink;
Informix Red Brick Decision ServerTM; Informix Session ProxyTM; Informix VistaTM; InfoShelfTM;
InterforumTM; I-SpyTM; MediazationTM; MetaCube; NewEraTM; ON-BarTM; OnLine Dynamic ServerTM;
OnLine/Secure Dynamic ServerTM; OpenCase; OrcaTM; PaVERTM; Red Brick and Design;
Red Brick Data MineTM; Red Brick Mine BuilderTM; Red Brick DecisionscapeTM; Red Brick ReadyTM;
Red Brick Systems; Regency Support; Rely on Red BrickSM; RISQL; Solution DesignSM; STARindexTM;
STARjoinTM; SuperView; TARGETindexTM; TARGETjoinTM; The Data Warehouse Company;
The one with the smartest data wins.TM; The world is being digitized. We’re indexing it.SM;
Universal Data Warehouse BlueprintTM; Universal Database ComponentsTM; Universal Web ConnectTM;
ViewPoint; VisionaryTM; Web Integration SuiteTM. The Informix logo is registered with the United States
Patent and Trademark Office. The DataBlade logo is registered with the United States Patent and
Trademark Office.
Documentation Team: Linda Briscoe, Evelyn Eldridge, Kathy Schaefer Francis, Mary Kraemer,
Barbara Nomiyama, Tom Noronha, Elaina Von Haas, Richelle White
Software and documentation acquired by or for the US Government are provided with rights as follows:
(1) if for civilian agency use, with rights as restricted by vendor’s standard license, as prescribed in FAR 12.212;
(2) if for Dept. of Defense use, with rights as restricted by vendor’s standard license, unless superseded by a
negotiated vendor license, as prescribed in DFARS 227.7202. Any whole or partial reproduction of software or
documentation marked with this legend must reproduce this legend.
Table of Contents
Introduction
In This Introduction . . . . . . . . . . . . . . . . . 3
About This Manual . . . . . . . . . . . . . . . . . . 3
Types of Users . . . . . . . . . . . . . . . . . . 3
Software Dependencies . . . . . . . . . . . . . . . 4
Assumptions About Your Locale. . . . . . . . . . . . 4
Demonstration Databases . . . . . . . . . . . . . . 5
New Features . . . . . . . . . . . . . . . . . . . . 6
New Features in Version 8.3 . . . . . . . . . . . . . 6
New Features in Version 9.2 . . . . . . . . . . . . . 8
Documentation Conventions . . . . . . . . . . . . . . 10
Typographical Conventions . . . . . . . . . . . . . 11
Icon Conventions . . . . . . . . . . . . . . . . . 12
Syntax Conventions . . . . . . . . . . . . . . . . 14
Sample-Code Conventions . . . . . . . . . . . . . . 19
Additional Documentation . . . . . . . . . . . . . . . 19
On-Line Manuals . . . . . . . . . . . . . . . . . 20
Printed Manuals . . . . . . . . . . . . . . . . . 20
On-Line Help . . . . . . . . . . . . . . . . . . 20
Error Message Documentation . . . . . . . . . . . . 20
Documentation Notes, Release Notes, Machine Notes . . . . 21
Related Reading . . . . . . . . . . . . . . . . . 22
Compliance with Industry Standards . . . . . . . . . . . 22
Informix Welcomes Your Comments . . . . . . . . . . . . 23
Table of Contents v
SELECT . . . . . . . . . . . . . . . . . . . . 2-634
SET AUTOFREE . . . . . . . . . . . . . . . . . 2-691
SET CONNECTION. . . . . . . . . . . . . . . . 2-694
SET Database Object Mode . . . . . . . . . . . . . 2-700
SET DATASKIP . . . . . . . . . . . . . . . . . 2-709
SET DEBUG FILE TO . . . . . . . . . . . . . . . 2-712
SET DEFERRED_PREPARE . . . . . . . . . . . . . 2-715
SET DESCRIPTOR . . . . . . . . . . . . . . . . 2-719
SET EXPLAIN . . . . . . . . . . . . . . . . . . 2-730
SET ISOLATION . . . . . . . . . . . . . . . . . 2-736
SET LOCK MODE . . . . . . . . . . . . . . . . 2-742
SET LOG . . . . . . . . . . . . . . . . . . . 2-745
SET OPTIMIZATION . . . . . . . . . . . . . . . 2-747
SET PDQPRIORITY . . . . . . . . . . . . . . . . 2-751
SET PLOAD FILE . . . . . . . . . . . . . . . . 2-755
SET Residency. . . . . . . . . . . . . . . . . . 2-756
SET ROLE . . . . . . . . . . . . . . . . . . . 2-758
SET SCHEDULE LEVEL . . . . . . . . . . . . . . 2-760
SET SESSION AUTHORIZATION . . . . . . . . . . . 2-761
SET STATEMENT CACHE . . . . . . . . . . . . . 2-764
SET TRANSACTION . . . . . . . . . . . . . . . 2-768
SET Transaction Mode . . . . . . . . . . . . . . . 2-774
START VIOLATIONS TABLE . . . . . . . . . . . . 2-778
STOP VIOLATIONS TABLE . . . . . . . . . . . . . 2-800
TRUNCATE . . . . . . . . . . . . . . . . . . 2-802
UNLOAD . . . . . . . . . . . . . . . . . . . 2-805
UNLOCK TABLE . . . . . . . . . . . . . . . . 2-813
UPDATE . . . . . . . . . . . . . . . . . . . 2-815
UPDATE STATISTICS . . . . . . . . . . . . . . . 2-835
WHENEVER . . . . . . . . . . . . . . . . . . 2-848
Chapter 4 Segments
In This Chapter . . . . . . . . . . . . . . . . . . 4-3
Argument. . . . . . . . . . . . . . . . . . . 4-6
Collection Derived Table . . . . . . . . . . . . . 4-9
Condition . . . . . . . . . . . . . . . . . . 4-27
Database Name . . . . . . . . . . . . . . . . . 4-47
Database Object Name . . . . . . . . . . . . . . 4-50
Data Type . . . . . . . . . . . . . . . . . . . 4-53
DATETIME Field Qualifier . . . . . . . . . . . . . 4-71
Expression . . . . . . . . . . . . . . . . . . 4-73
External Routine Reference . . . . . . . . . . . . . 4-202
Identifier . . . . . . . . . . . . . . . . . . . 4-205
INTERVAL Field Qualifier . . . . . . . . . . . . . 4-223
Jar Name . . . . . . . . . . . . . . . . . . . 4-226
Literal Collection . . . . . . . . . . . . . . . . 4-227
Literal DATETIME. . . . . . . . . . . . . . . . 4-231
Literal INTERVAL . . . . . . . . . . . . . . . . 4-234
Literal Number . . . . . . . . . . . . . . . . . 4-237
Literal Row . . . . . . . . . . . . . . . . . . 4-239
Optimizer Directives . . . . . . . . . . . . . . . 4-244
Owner Name . . . . . . . . . . . . . . . . . 4-257
Quoted String . . . . . . . . . . . . . . . . . 4-260
Relational Operator . . . . . . . . . . . . . . . 4-265
Return Clause . . . . . . . . . . . . . . . . . 4-270
Routine Modifier . . . . . . . . . . . . . . . . 4-274
Routine Parameter List . . . . . . . . . . . . . . 4-286
Shared-Object Filename . . . . . . . . . . . . . . 4-292
Specific Name . . . . . . . . . . . . . . . . . 4-296
Statement Block. . . . . . . . . . . . . . . . . 4-298
Index
Introduction
In This Introduction . . . . . . . . . . . . . . . . . . 3
About This Manual . . . . . . . . . . . . . . . . . . . 3
Types of Users . . . . . . . . . . . . . . . . . . . 3
Software Dependencies . . . . . . . . . . . . . . . . 4
Assumptions About Your Locale . . . . . . . . . . . . . 4
Demonstration Databases . . . . . . . . . . . . . . . 5
New Features . . . . . . . . . . . . . . . . . . . . . 6
New Features in Version 8.3 . . . . . . . . . . . . . . 6
Performance Enhancements . . . . . . . . . . . . . 6
New SQL Functionality . . . . . . . . . . . . . . 6
Version 8.3 Features from Version 7.30 . . . . . . . . . 7
New Features in Version 9.2 . . . . . . . . . . . . . . 8
Extensibility Enhancements . . . . . . . . . . . . . 8
Performance Improvements . . . . . . . . . . . . . 9
Special Features . . . . . . . . . . . . . . . . . 9
Version 9.2 Features from Dynamic Server 7.30 . . . . . . 9
Documentation Conventions . . . . . . . . . . . . . . . 10
Typographical Conventions . . . . . . . . . . . . . . 11
Icon Conventions . . . . . . . . . . . . . . . . . . 12
Comment Icons . . . . . . . . . . . . . . . . . 12
Feature, Product, and Platform Icons . . . . . . . . . . 12
Compliance Icons . . . . . . . . . . . . . . . . 14
Syntax Conventions . . . . . . . . . . . . . . . . . 14
Elements That Can Appear on the Path . . . . . . . . . 15
How to Read a Syntax Diagram . . . . . . . . . . . . 18
Sample-Code Conventions . . . . . . . . . . . . . . . 19
Additional Documentation . . . . . . . . . . . . . . . . 19
On-Line Manuals . . . . . . . . . . . . . . . . . . 20
Printed Manuals . . . . . . . . . . . . . . . . . . 20
On-Line Help . . . . . . . . . . . . . . . . . . . 20
Error Message Documentation . . . . . . . . . . . . . 20
Documentation Notes, Release Notes, Machine Notes . . . . . 21
Related Reading . . . . . . . . . . . . . . . . . . 22
Types of Users
This manual is written for the following users:
■ Database users
■ Database administrators
■ Database-application programmers
Introduction 3
Software Dependencies
Software Dependencies
This manual assumes that you are using one of the following database
servers:
This manual assumes that you use the U.S. 8859-1 English locale as the
default locale. The default is en_us.8859-1 (ISO 8859-1) on UNIX platforms or
en_us.1252 (Microsoft 1252) for Windows NT environments. This locale
supports U.S. English format conventions for dates, times, and currency, and
also supports the ISO 8859-1 or Microsoft 1252 code set, which includes the
ASCII code set plus many 8-bit characters such as é, è, and ñ.
If you plan to use nondefault characters in your data or your SQL identifiers,
or if you want to conform to the nondefault collation rules of character data,
you need to specify the appropriate nondefault locale.
Demonstration Databases
The DB-Access utility, which is provided with your Informix database server
products, includes one or more of the following demonstration databases:
The scripts that you use to install the demonstration databases reside in the
$INFORMIXDIR/bin directory on UNIX platforms and in the
%INFORMIXDIR%\bin directory in Windows environments.
Introduction 5
New Features
New Features
For a comprehensive list of new database server features, see the release
notes. This section lists new features relevant to this manual.
Performance Enhancements
This manual describes the following performance enhancements to
Version 8.3 of Extended Parallel Server:
■ MIDDLE function
■ Referential integrity for globally detached indexes
■ TRUNCATE statement
Introduction 7
New Features in Version 9.2
■ Extensibility enhancements
■ Performance improvements
■ Special features
■ Version 9.2 features from Version 7.30 of Dynamic Server
Extensibility Enhancements
This manual describes the following extensibility enhancements to
Version 9.2 of Dynamic Server:
Performance Improvements
This manual describes the following performance improvements to
Version 9.2 of Dynamic Server:
■ For SQL:
❑ Parallel statement-local variables (SLVs)
❑ SQL statement cache
■ For UDRs:
❑ Expensive-function optimization
❑ Parallel UDRs
❑ User-defined statistics routines
Special Features
This manual describes the following special features of Version 9.2 of
Dynamic Server:
■ Long identifiers:
❑ 128-character identifier
❑ 32-character user names
■ Ability to retain update locks
Introduction 9
Documentation Conventions
■ Application migration:
❑ UPPER, LOWER, and INITCAP functions for case-insensitive
search (for built-in types)
❑ REPLACE, SUBSTR, LPAD, and RPAD functions for string manip-
ulation (for built-in types)
❑ UNION operator in CREATE VIEW statement
❑ CASE expression
❑ NVL and DECODE functions
❑ TO_CHAR and TO_DATE date-conversion functions (for built-in
types)
❑ EXECUTE PROCEDURE syntax to update triggering columns
❑ New arguments to the dbinfo() function to obtain the hostname
and version of the database server
Documentation Conventions
This section describes the conventions that this manual uses. These
conventions make it easier to gather information from this and other volumes
in the documentation set.
■ Typographical conventions
■ Icon conventions
■ Syntax conventions
■ Sample-code conventions
Typographical Conventions
This manual uses the following conventions to introduce new terms,
illustrate screen displays, describe command syntax, and so forth.
Convention Meaning
italics Within text, new terms and emphasized words appear in italics.
italics Within syntax and code examples, variable values that you are
italics to specify appear in italics.
monospace Information that the product displays and information that you
monospace enter appear in a monospace typeface.
KEYSTROKE Keys that you are to press appear in uppercase letters in a sans
serif font.
Introduction 11
Icon Conventions
Icon Conventions
Throughout the documentation, you will find text that is identified by several
different types of icons. This section describes these icons.
Comment Icons
Comment icons identify three types of information, as the following table
describes. This information always appears in italics.
Icon Description
C
Identifies information that is specific to C user-defined
routines (UDRs)
DB
Identifies information that is specific to DB-Access
E/C
Identifies information that is specific to Informix ESQL/C
(1 of 2)
Icon Description
Ext
Identifies information that is specific to external routines,
that is, UDRs written in both C and Java.
GLS
Identifies information that relates to the Informix Global
Language Support (GLS) feature
IDS
Identifies information that is specific to Informix Dynamic
Server 2000
Java
Identifies information that is specific to UDRs written in
Java
SQLE
Identifies information that is specific to SQL Editor, which
is a component of Informix Enterprise Command Center
for Dynamic Server
UNIX
Identifies information that is specific to UNIX platforms
WIN NT
Identifies information that is specific to the Windows NT
environment
XPS
Identifies information or syntax that is specific to Informix
Extended Parallel Server
(2 of 2)
These icons can apply to an entire section or to one or more paragraphs
within a section. If an icon appears next to a section heading, the information
that applies to the indicated feature, product, or platform ends at the next
heading at the same or higher level. A ♦ symbol indicates the end of feature-,
product-, or platform-specific information that appears in one or more
paragraphs within a section.
Introduction 13
Syntax Conventions
Compliance Icons
Compliance icons indicate paragraphs that provide guidelines for complying
with a standard.
Icon Description
ANSI
Identifies information that is specific to an ANSI-compliant
database
X/O
Identifies functionality that conforms to X/Open
+
Identifies information or syntax that is an Informix
extension to ANSI SQL-92 entry-level standard SQL
Syntax Conventions
This section describes conventions for syntax diagrams. Each diagram
displays the sequences of required and optional keywords, terms, and
symbols that are valid in a given statement or segment, as Figure 1 shows.
Figure 1
Example of a Simple Syntax Diagram
SET LOG
BUFFERED
Each syntax diagram begins at the upper-left corner and ends at the upper-
right corner with a vertical terminator. Between these points, any path that
does not stop or reverse direction describes a possible form of the statement.
Element Description
' ' Single quotes are literal symbols that you must enter
as shown.
Introduction 15
Syntax Conventions
Element Description
Element Description
ALL
A shaded option is the default action.
WARNING
Introduction 17
Syntax Conventions
To use this diagram to construct a statement, start at the top left with the
keyword DELETE FROM. Follow the diagram to the right, proceeding through
the options that you want.
Sample-Code Conventions
Examples of SQL code occur throughout this manual. Except where noted,
the code is not specific to any single Informix application development tool.
If only SQL statements are listed in the example, they are not delimited by
semicolons. For instance, you might see the code in the following example:
CONNECT TO stores_demo
...
COMMIT WORK
DISCONNECT CURRENT
To use this SQL code for a specific product, you must apply the syntax rules
for that product. For example, if you are using DB-Access, you must delimit
multiple statements with semicolons. If you are using an SQL API, you must
use EXEC SQL at the start of each statement and a semicolon (or other appro-
priate delimiter) at the end of the statement.
Tip: Ellipsis points in a code example indicate that more code would be added in a
full application, but it is not necessary to show it to describe the concept being
discussed.
Additional Documentation
For additional information, you might want to refer to the following types of
documentation:
■ On-line manuals
■ Printed manuals
■ On-line help
■ Error message documentation
■ Documentation notes, release notes, and machine notes
■ Related reading
Introduction 19
On-Line Manuals
On-Line Manuals
An Answers OnLine CD that contains Informix manuals in electronic format
is provided with your Informix products. You can install the documentation
or access it directly from the CD. For information about how to install, read,
and print on-line manuals, see the installation insert that accompanies
Answers OnLine.
Informix on-line manuals are also available on the following Web site:
www.informix.com/answers
Printed Manuals
To order printed manuals, call 1-800-331-1763 or send email to
[email protected]. Please provide the following information when
you place your order:
UNIX To read error messages and corrective actions on UNIX, use one of the
following utilities.
Utility Description
WIN NT To read error messages and corrective actions in Windows environments, use
the Informix Find Error utility. To display this utility, choose
Start➞Programs➞Informix from the Task Bar. ♦
Instructions for using the preceding utilities are available in Answers
OnLine. Answers OnLine also provides a listing of error messages and
corrective actions in HTML format.
IDS_9.2 or The machine-notes file describes any special actions that you
XPS_x.y must take to configure and use Informix products on your
computer. Machine notes are named for the product described.
Introduction 21
Related Reading
WIN NT The following items appear in the Informix folder. To display this folder,
choose Start➞Programs➞Informix from the Task Bar.
Related Reading
For a list of publications that provide an introduction to database servers and
operating-system platforms, refer to your Getting Started manual.
■ The name and version of the manual that you are using
■ Any comments that you have about the manual
■ Your name, address, and phone number
The doc alias is reserved exclusively for reporting errors and omissions in our
documentation.
Introduction 23
Chapter
The Syntax Conventions section explains the elements that can appear in a
syntax diagram and the paths that connect the elements to each other. This
section also includes a sample syntax diagram that illustrates the major
elements of all syntax diagrams. The narrative that follows the sample
diagram shows how to read the diagram in order to enter the statement
successfully.
Using Examples
To understand the main syntax diagram and subdiagrams for a statement,
study the examples of syntax that appear in the rules of usage for each
statement. These examples have two purposes:
This section points to related information in this manual and other manuals
that helps you to understand the statement in question. The section provides
some or all of the following information:
■ The names of related statements that might contain a fuller
discussion of topics in this statement
■ The titles of other manuals that provide extended discussions of
topics in this statement
Tip: If you do not have extensive knowledge and experience with SQL, the “Informix
Guide to SQL: Tutorial” gives you the basic SQL knowledge that you need to under-
stand and use the statement descriptions in this manual.
Your comments can help you or others to understand the role of the
statement within a program, SPL routine, or command file. The code
examples in this manual sometimes include comments that clarify the role of
an SQL statement within the code.
The following table shows the SQL comment symbols that you can enter in
your code. A Y in a column signifies that you can use the symbol with the
product or database type named in the column heading. An N in a column
signifies that you cannot use the symbol with the product or database type
that the column heading names.
Databases
ANSI- That Are
Comment SPL Compliant Not ANSI
Symbol ESQL/C Routine DB-Access Databases Compliant Description
ANSI If the product that you are using supports both comment symbols, your
choice of a comment symbol depends on your requirements for ANSI
compliance:
■ The double dash (--) complies with the ANSI SQL standard.
■ Braces ({}) are an Informix extension to the standard.
DB In DB-Access, you can use either comment symbol when you enter SQL state-
ments with the SQL editor and when you create SQL command files with the
SQL editor or a system editor. An SQL command file is an operating-system
file that contains one or more SQL statements. Command files are also known
as command scripts. For more information about command files, see the
discussion of command scripts in the Informix Guide to SQL: Tutorial. For
information on how to create and modify command files with the SQL editor
or a system editor in DB-Access, see the DB-Access User’s Manual. ♦
SPL You can use either comment symbol in any line of an SPL routine. See the
discussion of how to comment and document an SPL routine in the Informix
Guide to SQL: Tutorial. ♦
E/C
In ESQL/C, you can use the double dash (--) to comment SQL statements. For
further information on the use of SQL comment symbols and language-
specific comment symbols in ESQL/C programs, see the Informix ESQL/C
Programmer’s Manual. ♦
In the following example, the user enters the same SQL statement and the
same comment as in the preceding example, but the user places the comment
on a line by itself:
SELECT * FROM customer
-- Selects all columns and rows
In the following example, the user enters the same SQL statement as in the
preceding example but now enters a multiple-line comment:
SELECT * FROM customer
-- Selects all columns and rows
-- from the customer table
In the following example, the user enters the same SQL statement and the
same comment as in the preceding example but places the comment on a line
by itself:
SELECT * FROM customer
{Selects all columns and rows}
In the following example, the user enters the same SQL statement as in the
preceding example but enters a multiple-line comment:
SELECT * FROM customer
{Selects all columns and rows
from the customer table}
Optimization Statements
SET EXPLAIN SET SCHEDULE LEVEL
SET OPTIMIZATION SET STATEMENT CACHE
SET PDQPRIORITY UPDATE STATISTICS
SET RESIDENCY
Auxiliary Statements
INFO SET DATASKIP
OUTPUT WHENEVER
GET DIAGNOSTICS
Important: Optical Subsystem statements are described in the “Guide to the Optical
Subsystem.”
ANSI-Compliant Statements
CLOSE SET SESSION AUTHORIZATION
COMMIT WORK SET TRANSACTION
ROLLBACK WORK
SQL Statements
2
In This Chapter . . . . . . . . . . . . . . . . . . . . 2-5
ALLOCATE COLLECTION . . . . . . . . . . . . . . 2-6
ALLOCATE DESCRIPTOR . . . . . . . . . . . . . . . 2-8
ALLOCATE ROW . . . . . . . . . . . . . . . . . . 2-10
ALTER FRAGMENT . . . . . . . . . . . . . . . . . 2-12
ALTER FUNCTION . . . . . . . . . . . . . . . . . 2-41
ALTER INDEX . . . . . . . . . . . . . . . . . . . 2-44
ALTER PROCEDURE . . . . . . . . . . . . . . . . 2-48
ALTER ROUTINE . . . . . . . . . . . . . . . . . . 2-51
ALTER TABLE . . . . . . . . . . . . . . . . . . . 2-55
BEGIN WORK . . . . . . . . . . . . . . . . . . . 2-91
CLOSE. . . . . . . . . . . . . . . . . . . . . . 2-94
CLOSE DATABASE . . . . . . . . . . . . . . . . . 2-98
COMMIT WORK . . . . . . . . . . . . . . . . . . 2-100
CONNECT . . . . . . . . . . . . . . . . . . . . 2-103
CREATE AGGREGATE . . . . . . . . . . . . . . . . 2-115
CREATE CAST . . . . . . . . . . . . . . . . . . . 2-119
CREATE DATABASE. . . . . . . . . . . . . . . . . 2-124
CREATE DISTINCT TYPE . . . . . . . . . . . . . . . 2-127
CREATE EXTERNAL TABLE . . . . . . . . . . . . . . 2-131
CREATE FUNCTION . . . . . . . . . . . . . . . . 2-146
CREATE FUNCTION FROM . . . . . . . . . . . . . . 2-155
CREATE INDEX . . . . . . . . . . . . . . . . . . 2-157
CREATE OPAQUE TYPE . . . . . . . . . . . . . . . 2-186
CREATE OPCLASS . . . . . . . . . . . . . . . . . 2-193
CREATE PROCEDURE . . . . . . . . . . . . . . . . 2-199
CREATE PROCEDURE FROM . . . . . . . . . . . . . 2-209
CREATE ROLE . . . . . . . . . . . . . . . . . . . 2-212
CREATE ROUTINE FROM . . . . . . . . . . . . . . . 2-214
CREATE ROW TYPE . . . . . . . . . . . . . . . . . 2-216
CREATE SCHEMA . . . . . . . . . . . . . . . . . 2-222
CREATE SYNONYM . . . . . . . . . . . . . . . . . 2-226
CREATE TABLE . . . . . . . . . . . . . . . . . . 2-230
CREATE Temporary TABLE . . . . . . . . . . . . . . 2-286
CREATE TRIGGER . . . . . . . . . . . . . . . . . 2-296
CREATE VIEW . . . . . . . . . . . . . . . . . . . 2-334
DATABASE . . . . . . . . . . . . . . . . . . . . 2-341
DEALLOCATE COLLECTION . . . . . . . . . . . . . 2-343
DEALLOCATE DESCRIPTOR . . . . . . . . . . . . . . 2-345
DEALLOCATE ROW . . . . . . . . . . . . . . . . . 2-347
DECLARE . . . . . . . . . . . . . . . . . . . . 2-349
DELETE . . . . . . . . . . . . . . . . . . . . . 2-373
DESCRIBE . . . . . . . . . . . . . . . . . . . . 2-382
DISCONNECT . . . . . . . . . . . . . . . . . . . 2-389
DROP AGGREGATE . . . . . . . . . . . . . . . . . 2-393
DROP CAST . . . . . . . . . . . . . . . . . . . . 2-395
DROP DATABASE. . . . . . . . . . . . . . . . . . 2-397
DROP FUNCTION . . . . . . . . . . . . . . . . . 2-399
DROP INDEX . . . . . . . . . . . . . . . . . . . 2-401
DROP OPCLASS . . . . . . . . . . . . . . . . . . 2-403
DROP PROCEDURE . . . . . . . . . . . . . . . . . 2-404
DROP ROLE . . . . . . . . . . . . . . . . . . . . 2-407
DROP ROUTINE . . . . . . . . . . . . . . . . . . 2-408
DROP ROW TYPE . . . . . . . . . . . . . . . . . . 2-410
DROP SYNONYM . . . . . . . . . . . . . . . . . . 2-412
DROP TABLE . . . . . . . . . . . . . . . . . . . 2-413
DROP TRIGGER . . . . . . . . . . . . . . . . . . 2-417
DROP TYPE . . . . . . . . . . . . . . . . . . . . 2-418
DROP VIEW . . . . . . . . . . . . . . . . . . . . 2-420
EXECUTE . . . . . . . . . . . . . . . . . . . . . 2-422
EXECUTE FUNCTION . . . . . . . . . . . . . . . . 2-434
EXECUTE IMMEDIATE . . . . . . . . . . . . . . . . 2-441
EXECUTE PROCEDURE . . . . . . . . . . . . . . . 2-444
+ ALLOCATE COLLECTION
IDS
Use the ALLOCATE COLLECTION statement to allocate memory for a
E/C collection variable.
Syntax
Usage
The ALLOCATE COLLECTION statement allocates memory for a variable that
stores collection data. To create a collection variable for an ESQL/C program,
perform the following steps:
Examples
The following example shows how to allocate resources with the ALLOCATE
COLLECTION statement for the untyped collection variable, a_set:
Related Information
Related examples: Refer to the collection variable example in PUT
+ ALLOCATE DESCRIPTOR
E/C
Use the ALLOCATE DESCRIPTOR statement to allocate memory for a system-
descriptor area. This statement creates a place in memory to hold information
that a DESCRIBE statement obtains or to hold information about the WHERE
clause of a statement.
Syntax
items_var
Usage
The ALLOCATE DESCRIPTOR statement creates a system-descriptor area. A
system-descriptor area contains one or more fields called item descriptors.
Each item descriptor holds a data value that the database server can receive
or send. The item descriptors also contain information about the data such as
type, length, scale, precision, and nullability.
If the name that you assign to a system-descriptor area matches the name of
an existing system-descriptor area, the database server returns an error. If
you free the descriptor with the DEALLOCATE DESCRIPTOR statement, you
can reuse the descriptor.
A system-descriptor area holds information that a DESCRIBE...USING SQL
DESCRIPTOR statement obtains or it holds information about the WHERE
clause of a dynamically executed statement.
Related Information
Related statements: DEALLOCATE DESCRIPTOR, DECLARE, DESCRIBE,
EXECUTE, FETCH, GET DESCRIPTOR, OPEN, PREPARE, PUT, and SET
DESCRIPTOR
+ ALLOCATE ROW
IDS
Use the ALLOCATE ROW statement to allocate memory for a row variable.
E/C
Use this statement with ESQL/C.
Syntax
Usage
The ALLOCATE ROW statement allocates memory for a variable that stores
row-type data. To create a row variable, perform the following steps in your
ESQL/C program:
You must explicitly release memory with the DEALLOCATE ROW statement.
Once you free the row variable with the DEALLOCATE ROW statement, you
can reuse the row variable.
Tip: The ALLOCATE ROW statement allocates memory for an ESQL/C row variable
only. To allocate memory for an ESQL/C collection variable, use the ALLOCATE
COLLECTION statement.
When you use the same row variable in multiple calls without deallocating
it, a memory leak on the client computer results. Because there is no way to
determine if a pointer is valid when it is passed, ESQL/C assumes that it is not
valid and assigns it to a new memory location.
Example
The following example shows how to allocate resources with the ALLOCATE
ROW statement for the typed row variable, a_row:
Related Information
Related statements: ALLOCATE COLLECTION and DEALLOCATE ROW
+
ALTER FRAGMENT
Use the ALTER FRAGMENT statement to alter the distribution strategy or
storage location of an existing table or index.
Syntax
ATTACH
ALTER FRAGMENT ON TABLE surviving_table Clause
p. 2-15
IDS DETACH
Clause
p. 2-25
INDEX surviving_index
INIT
Clause
p. 2-27
IDS
ADD
Clause
p. 2-35
DROP
Clause
p. 2-37
MODIFY
Clause
p. 2-38
Usage
The clauses of the ALTER FRAGMENT statement let you perform the
following tasks.
Clause Purpose
ATTACH Combines tables that contain identical table structures into a single
fragmented table.
Warning: This statement can cause indexes to be dropped and rebuilt. Before under-
taking alter operations, check corresponding sections in your “Performance Guide”
to review effects and strategies
General Privileges
You must have the Alter or the DBA privilege to change the fragmentation
strategy of a table. You must have the Index or the DBA privilege to alter the
fragmentation strategy of an index.
If your table or index is not already fragmented, the only clauses available to
you are INIT and ATTACH.
IDS You cannot use ALTER FRAGMENT on a typed table that is part of a table
hierarchy. ♦
XPS You cannot use the ALTER FRAGMENT statement on a generalized-key (GK)
index. Also, you cannot use the ALTER FRAGMENT statement on any table
that has a dependent GK index defined on it. In addition, you cannot use this
statement on a table that has range fragmentation.
If the surviving_table has hash fragmentation, the only clauses available are
ATTACH and INIT. ♦
1. Run the UPDATE STATISTICS statement on the table. This step fills the
sysfragments system catalog table with the current table
information.
2. Query the sysfragments system catalog table to examine the npused
and nrows fields. The npused field gives you the number of data
pages used in the fragment, and the nrows field gives you the
number of rows in the fragment.
ATTACH Clause
Use the ATTACH clause to combine tables that contain identical table
structures into a fragmentation strategy.
Important: Use the CREATE TABLE statement or the INIT clause of the ALTER
FRAGMENT statement to create fragmented tables.
,
ATTACH 1 surviving_table
consumed_table
AS expression
BEFORE dbspace
AFTER
1 AS REMAINDER
Privileges
You must be the DBA or the owner of the tables that are involved to use the
ATTACH clause.
You cannot use the ATTACH clause in certain situations. The attach operation
fails:
In other words, you cannot use the ATTACH clause for data movement
among fragments. To perform this task, see the “INIT Clause” on page 2-27.
IDS When you attach one or more tables to a fragmented table, a consumed table
must be nonfragmented. ♦
XPS When you attach one or more tables to a fragmented table, a consumed table
can be nonfragmented or have hash fragmentation.
If you specify a consumed_table that has hash fragmentation, the hash column
specification must match that of the surviving_table and any other
consumed_table involved in the attach operation. ♦
If you know the name of the dbslice, but not any of the dbspaces that it
comprises, you can name the first dbspace in the dbslice by adding .1 to the
name of the dbslice. For example, if the dbslice were named dbsl1, you could
specify dbsl1.1.
What Happens?
After the attach executes, all consumed tables no longer exist. Any
constraints (CHECK or NOT NULL) that were on the consumed tables also no
longer exist.
You must reference the records that were in the consumed tables through the
surviving table.
IDS In a nonlogging database, when the attach executes, the database server does
not extend indexes on the surviving table according to the new fragmen-
tation strategy of the surviving table. To extend the fragmentation strategy of
an attached index according to the new fragmentations strategy of the
surviving table, you must drop the index and recreate it on the surviving
table. ♦
For more information on what happens to indexes, see the discussion about
altering table fragments in your Performance Guide.
IDS Each BYTE and TEXT column in every table that is named in the ATTACH
clause must have the same storage type, either blobspace or tblspace. If the
BYTE or TEXT column is stored in a blobspace, the same column in all tables
must be in the same blobspace. If the BYTE or TEXT column is stored in a
tblspace, the same column must be stored in a tblspace in all tables. ♦
XPS In Extended Parallel Server, BYTE and TEXT columns are stored in separate
fragments that are created for that purpose. If a table includes a BYTE or TEXT
column, the database server creates a separate, additional fragment in the
same dbspace as each regular table fragment. BYTE or TEXT columns are
stored in the separate fragment that is associated with the regular table
fragment where a given row resides.
When an attach occurs, BYTE and TEXT fragments of the consumed table
become part of the surviving table and continue to be associated with the
same rows and data fragments as they were before the attach. ♦
No triggers are activated with the ATTACH clause, but subsequent data-
manipulation operations on the new rows can activate triggers.
IDS The following table shows the distribution schemes that can result from
different distribution schemes of the tables mentioned in the ATTACH clause.
XPS The following table shows the distribution schemes that can result from
different distribution schemes of the tables mentioned in the ATTACH clause.
When you attach a nonfragmented table to a table that has hash fragmen-
tation, the resulting table has hybrid fragmentation.
You can attach a table with a hash distribution scheme to a table that
currently has no fragmentation, hash fragmentation, or hybrid fragmen-
tation. In any of these situations, the resulting table has a hybrid distribution
scheme. ♦
Examples
The following examples illustrate the use of the ATTACH clause to create
fragmented tables with different distribution schemes.
After you execute the ATTACH clause, the database server fragments the table
pen_types round-robin into two dbspaces: the dbspace that contained
pen_types and the dbspace that contained pen_makers. Table pen_makers
is consumed, and no longer exists; all rows that were in table pen_makers are
now in table pen_types.
When you examine the sysfragments system catalog table after you alter the
fragment, you see that table cur_acct is fragmented by expression into three
dbspaces. For additional information about the sysfragments system catalog
table, see the Informix Guide to SQL: Reference.
In addition to simple range rules, you can use the ATTACH clause to fragment
by expression with hash or arbitrary rules. For a discussion of all types of
expressions in an expression-based distribution scheme, see “FRAGMENT
BY Clause for Tables” on page 2-30.
Warning: When you specify a date value in a fragment expression, make sure to
specify 4 digits instead of 2 digits for the year. When you specify a 4-digit year, the
DBCENTURY environment variable has no effect on the distribution scheme. When
you specify a 2-digit year, the DBCENTURY environment variable can affect the
distribution scheme and can produce unpredictable results. For more information on
the DBCENTURY environment variable, see the “Informix Guide to SQL: Reference.”
The data for a new month is originally loaded from an external source. The
data is distributed evenly across the name coservers on which the sales_info
table is defined, using a system-defined hash function on the same column:
CREATE TABLE jan_97 (order_num int, sale_date date, ...)
FRAGMENT BY HASH (order_num) IN sales_slice_9701
INSERT INTO jan_97 SELECT (...) FROM ...
Once the data is loaded, you can attach the new table to sales_info. You can
issue the following ALTER FRAGMENT statement to attach the new table:
ALTER FRAGMENT ON TABLE sales_info ATTACH jan_97
AS sale_date >= '01/01/1997' AND sale_date < '02/01/1997'
DETACH Clause
Use the DETACH clause to detach a table fragment from a distribution scheme
and place the contents into a new nonfragmented table.
XPS In Extended Parallel Server, the new table can also be a table with hash
fragmentation. ♦
The new table that results from the execution of the DETACH clause does not
inherit any indexes or constraints from the original table. Only the data
remains.
The new table that results from the execution of the DETACH clause does not
inherit any privileges from the original table. Instead this table has the
default privileges for any new table. For further information on default table-
level privileges, see the GRANT statement on “Table-Level Privileges” on
page 2-505.
Restrictions
The DETACH clause cannot be applied to a table if that table is the parent of
a referential constraint or if a rowid column is defined on the table.
XPS In Extended Parallel Server, you cannot use the DETACH clause if the table
has a dependent GK index defined on it. ♦
This example detaches dbsp2 from the distribution scheme for cur_acct and
places the rows in a new table, accounts. Table accounts now has the same
structure (column names, number of columns, data types, and so on) as table
cur_acct, but the table accounts does not contain any indexes or constraints
from the table cur_acct. Both tables are now nonfragmented.
This statement detaches dbsp3 from the distribution scheme for bus_acct
and places the rows in a new table, cli_acct. Table cli_acct now has the same
structure (column names, number of columns, data types, and so on) as
bus_acct, but the table cli_acct does not contain any indexes or constraints
from the table bus_acct. Table cli_acct is a nonfragmented table, and table
bus_acct remains a fragmented table.
In this example, data from January 1996 is detached from the sales_info table
and placed in a new table called jan_96.
INIT Clause
The INIT clause allows you to:
FRAGMENT BY
INIT Clause for Tables
p. 2-30
IDS WITH ROWIDS
FRAGMENT BY
IDS Clause for Indexes
p. 2-33
IN dbspace
XPS
IN dbslice
XPS You cannot use the INIT clause to change the fragmentation strategy of a table
that has a GK index. ♦
For more information about the storage spaces in which you can store a table,
see “Using the IN Clause” on page 2-257.
When you use the INIT clause to modify a table, the tabid value in system
catalog tables changes for the affected table. The constrid of all unique and
referential constraints on the table also change.
Use the WITH ROWIDS option to add a new column called the rowid column.
The database server assigns a unique number to each row that remains stable
for the existence of the row. The database server creates an index that it uses
to find the physical location of the row. Each row contains an additional
4 bytes to store the rowid column after you add the WITH ROWIDS option.
Important: Informix recommends that you use primary keys, rather than the rowid
column, as an access method.
You must use the IN dbspace clause to place the table in a dbspace explicitly.
,
FRAGMENT BY ROUND ROBIN IN dbspace , dbspace
XPS
IN dbslice
,
EXPRESSION expression IN dbspace , expression IN dbspace
REMAINDER
XPS
, ,
HASH ( column ) IN dbspace , dbspace
IN dbslice
,
HYBRID ( column )
,
EXPRESSION expression IN dbslice , expression IN dbslice
REMAINDER
dbspace dbspace
, ,
( dbspace ) ( dbspace )
The following example shows the statement that originally defined the
fragmentation strategy on the table account and then shows an ALTER
FRAGMENT statement that redefines the fragmentation strategy:
IDS When you use the INIT clause to fragment an existing nonfragmented table,
all indexes on the table become fragmented in the same way as the table. ♦
XPS When you use the INIT clause to fragment an existing nonfragmented table,
indexes retain their existing fragmentation strategy.
The following example shows the original table definition as well as how to
use the ALTER FRAGMENT statement to fragment the table:
CREATE TABLE balances (col1 int, col2 int) IN dbsp1;
ADD new_dbspace
expression IN new_dbspace
BEFORE existing_dbspace
AFTER
REMAINDER IN new_dbspace
To add another dbspace, use the ADD clause, as shown in the following
example:
ALTER FRAGMENT ON TABLE book ADD dbsp3;
If you want to add another fragment to the fragmentation list and have this
fragment hold rows between 200 and 300, use the following ALTER
FRAGMENT statement:
Any rows that were formerly in the remainder fragment and that fit the
criteria c1 >= 200 and c1 < 300 are moved to the new dbspace.
DROP dbspace
You cannot drop one of the fragments when the table contains only two
fragments. You cannot drop a fragment in a table that is fragmented with an
expression-based distribution scheme if the fragment contains data that
cannot be moved to another fragment. If the distribution scheme contains a
REMAINDER option, or if the expressions were constructed in an overlapping
manner, you can drop a fragment that contains data.
When you want to make a fragmented table nonfragmented, use either the
INIT or DETACH clause.
When you drop a fragment from a dbspace, the underlying dbspace is not
affected. Only the fragment data within that dbspace is affected. When you
drop a fragment all the records located in the fragment move to another
fragment. The destination fragment might not have enough space for the
additional records. When this happens, follow one of the procedures that are
listed in “Making More Space” on page 2-14 to increase your space, and retry
the procedure.
,
MODIFY mod_dbspace TO expression IN new_dbspace
1 REMAINDER IN new_dbspace
General Usage
When you use the MODIFY clause, the underlying dbspaces are not affected.
Only the fragment data within the dbspaces is affected.
The following example shows how to use the MODIFY clause to change an
existing expression:
ALTER FRAGMENT ON TABLE cust_acct
MODIFY dbsp1 to acct_num < 65 IN dbsp1
The following example shows how to use the MODIFY clause to move an
expression from one dbspace to another:
ALTER FRAGMENT ON TABLE cust_acct
MODIFY dbsp1 to acct_num < 35 in dbsp2
In this example, the distribution scheme for the cust_acct table is modified so
that all row items in the column acct_num that are less than 35 are now
contained in the dbspace dbsp2. These items were formerly contained in the
dbspace dbsp1.
Related Information
Related statements: CREATE TABLE, CREATE INDEX, and ALTER TABLE
+ ALTER FUNCTION
IDS
Use the ALTER FUNCTION statement to change the routine modifiers or
pathname of a user-defined function.
Syntax
Routine
ALTER FUNCTION function WITH ( ADD Modifier )
p. 4-274
MODIFY
,
DROP
parameter_type
Ext Shared-
SPECIFIC FUNCTION Specific Name Object
p. 4-296 MODIFY EXTERNAL NAME Filename
p. 4-292
Usage
The ALTER FUNCTION statement allows you to modify a user-defined
function to tune its performance. With this statement you can modify charac-
teristics that control how the function executes. You can also add or replace
related UDRs that provide alternatives for the optimizer, which can improve
performance.
Privileges
To use the ALTER FUNCTION statement, you must be the owner of the UDR or
have the DBA privilege.
Keyword Purpose
If the routine modifier is a Boolean value, MODIFY sets the value to be T (that
is, it is the equivalent of using the keyword ADD to add the routine modifier).
For example, both of the following statements alter the func1 function so that
it can be executed in parallel in the context of a parallelizable data query
statement.
ALTER FUNCTION func1 WITH (MODIFY PARALLELIZABLE)
Related Information
Related Statements: ALTER PROCEDURE, ALTER ROUTINE, CREATE
FUNCTION, CREATE PROCEDURE, DROP FUNCTION, DROP PROCEDURE, and
DROP ROUTINE
For a discussion on how to create and use SPL routines, see the Informix Guide
to SQL: Tutorial.
For a discussion of how to create and use external routines, see Extending
Informix Dynamic Server 2000.
For information about how to create C UDRs, see the DataBlade API
Programmer’s Manual.
+
ALTER INDEX
Use the ALTER INDEX statement to put the data in a table in the order of an
existing index or to release an index from the clustering attribute.
Syntax
NOT
XPS
NORMAL
Usage
The ALTER INDEX statement works only on indexes that are created with the
CREATE INDEX statement; it does not affect constraints that are created with
the CREATE TABLE statement.
You cannot alter the index of a temporary table.
TO CLUSTER Option
The TO CLUSTER option causes the rows in the physical table to reorder in the
indexed order.
The following example shows how you can use the ALTER INDEX TO
CLUSTER statement to order the rows in the orders table physically. The
CREATE INDEX statement creates an index on the customer_num column of
the table. Then the ALTER INDEX statement causes the physical ordering of
the rows.
CREATE INDEX ix_cust ON orders (customer_num);
When you reorder, the entire file is rewritten. This process can take a long
time, and it requires sufficient disk space to maintain two copies of the table.
Over time, if you modify the table, you can expect the benefit of an earlier
cluster to disappear because rows are added in space-available order, not
sequentially. You can recluster the table to regain performance by issuing
another ALTER INDEX TO CLUSTER statement on the clustered index. You do
not need to drop a clustered index before you issue another ALTER INDEX TO
CLUSTER statement on a currently clustered index.
XPS If you are using Extended Parallel Server, you cannot use the CLUSTER
option on STANDARD tables. ♦
The first two statements create indexes for the orders table and cluster the
physical table in ascending order on the customer_num column. The last two
statements recluster the physical table in ascending order on the order_num
column.
When you use the coarse-lock mode, index-level locks are acquired on the
index instead of item-level or page-level locks. This mode reduces the
number of lock calls on an index.
Use the coarse-lock mode when you know the index is not going to change,
that is, when read-only operations are performed on the index.
Use the coarse-lock mode to have the database server place item-level or
page-level locks on the index as necessary. Use this mode when the index gets
updated frequently.
When the database server executes the command to change the lock mode to
coarse, it acquires an exclusive lock on the table for the duration of the
command. Any transactions that are currently using a lock of finer granu-
larity must complete before the database server switches to the coarse-lock
mode.
Related Information
Related statements: CREATE INDEX and CREATE TABLE
For a discussion of the performance implications of clustered indexes, see
your Performance Guide.
+ ALTER PROCEDURE
IDS
Use the ALTER PROCEDURE statement to change the routine modifiers or
pathname of a previously defined external procedure.
Syntax
,
Routine
ALTER PROCEDURE procedure WITH ( ADD Modifier )
p. 4-274
MODIFY
,
DROP
parameter_type
Shared-
SPECIFIC PROCEDURE Specific Name Object
p. 4-296 MODIFY EXTERNAL NAME Filename
p. 4-292
Usage
The ALTER PROCEDURE statement allows you to modify an external
procedure to tune its performance. With this statement you can modify
characteristics that control how the external procedure executes. You can also
add or replace related UDRs that provide alternatives for the optimizer,
which can improve performance.
Privileges
To use the ALTER PROCEDURE statement, you must be the owner of the UDR
or have the DBA privilege.
Keyword Purpose
If the routine modifier is a Boolean value, MODIFY sets the value to be T (that
is, it is the equivalent of using the keyword ADD to add the routine modifier).
For example, both of the following statements alter the proc1 procedure so
that it can be executed in parallel in the context of a parallelizable data query
statement.
ALTER PROCEDURE proc1 WITH (MODIFY PARALLELIZABLE)
Related Information
Related Statements: ALTER FUNCTION, ALTER ROUTINE, CREATE
FUNCTION, CREATE PROCEDURE, DROP FUNCTION, DROP PROCEDURE, and
DROP ROUTINE
For a discussion on how to create and use SPL routines, see the Informix Guide
to SQL: Tutorial.
For a discussion of how to create and use external routines, see Extending
Informix Dynamic Server 2000.
For information about how to create C UDRs, see the DataBlade API
Programmer’s Manual.
+ ALTER ROUTINE
IDS
Use the ALTER ROUTINE statement to change the routine modifiers or
pathname of a previously defined user-defined routine (UDR).
Syntax
,
Routine
ALTER ROUTINE routine WITH ( ADD Modifier )
p. 4-274
MODIFY
,
DROP
parameter_type
EXT Shared-
SPECIFIC ROUTINE Specific Name Object
p. 4-296 MODIFY EXTERNAL NAME Filename
p. 4-292
Usage
The ALTER ROUTINE statement allows you to modify a previously-defined
UDR to tune its performance. With this statement you can modify character-
istics that control how the UDR executes. You can also add or replace related
UDRs that provide alternatives for the optimizer, which can improve
performance.
This statement is useful when you do not know whether a UDR is a user-
defined function or a user-defined procedure. When you use this statement,
the database server alters the appropriate user-defined procedure or user-
defined function.
Privileges
To use the ALTER ROUTINE statement, you must be the owner of the UDR or
have the DBA privilege.
Restrictions
When you use this statement, the type of UDR cannot be ambiguous. The
UDR that you specify must refer to either a user-defined function or a user-
defined procedure. If either of the following conditions exist, the database
server returns an error:
■ The name (and parameters) that you specify apply to both a user-
defined procedure and a user-defined function
■ The specific name that you specify applies to both a user-defined
function and a user-defined procedure
Keyword Purpose
If the routine modifier is a Boolean value, MODIFY sets the value to be T (that
is, it is the equivalent of using the keyword ADD to add the routine modifier).
For example, both of the following statements alter the func1 UDR so that it
can be executed in parallel in the context of a parallelizable data query
statement.
ALTER ROUTINE func1 WITH (MODIFY PARALLELIZABLE)
Note also, that because the name func1 is not unique to the database, the data
type parameters are specified so that the routine signature would be unique.
If this function had a Specific Name, for example, raise_sal, specified when it
was created, you could identify the function with the following first line:
ALTER SPECIFIC ROUTINE raise_sal
Related Information
Related Statements: ALTER FUNCTION, ALTER PROCEDURE, CREATE
FUNCTION, CREATE PROCEDURE, DROP FUNCTION, DROP PROCEDURE, and
DROP ROUTINE
For a discussion on how to create and use SPL routines, see the Informix Guide
to SQL: Tutorial.
For a discussion of how to create and use external routines, see Extending
Informix Dynamic Server 2000.
For information about how to create C UDRs, see the DataBlade API
Programmer’s Manual.
+
ALTER TABLE
Use the ALTER TABLE statement to modify the definition of a table.
Syntax
Typed-Table Options
IDS p. 2-89
Usage
Altering a table on which a view depends might invalidate the view.
Warning: The clauses available with this statement have varying performance impli-
cations. Before you undertake alter operations, check corresponding sections in your
“Performance Guide” to review effects and strategies.
Restrictions
You cannot alter a temporary table. You also cannot alter a violations or
diagnostics table. In addition, you cannot add, drop, or modify a column if
the table that contains the column has violations and diagnostics tables
associated with it.
XPS If a table has range fragmentation, the parts of this statement that you can use
are the Usage-TYPE options, and the Lock-Mode clause. All other operations
return an error.
If you have a static or raw table, the only information that you can alter is the
usage type of the table. That is, the Usage-TYPE options are the only part of
the ALTER TABLE statement that you can use. ♦
Privileges
To use the ALTER TABLE statement, you must meet one of the following
conditions:
■ You must have the DBA privilege on the database where the table
resides.
■ You must own the table.
■ You must have the Alter privilege on the specified table and the
Resource privilege on the database where the table resides.
■ To add a referential constraint, you must have the DBA or References
privilege on either the referenced columns or the referenced table.
■ To drop a constraint, you must have the DBA privilege or be the
owner of the constraint. If you are the owner of the constraint but not
the owner of the table, you must have Alter privilege on the specified
table. You do not need the References privilege to drop a constraint.
Basic-Table Options
With the ALTER TABLE statement, you can perform basic alter operations
such as adding, modifying, or dropping columns and constraints, and
changing the extent size and locking granularity of a table. The database
server performs the alter operations in the order that you specify. If any of the
actions fails, the entire operation is cancelled.
ADD Clause
p. 2-59
DROP Clause
p. 2-69
MODIFY Clause
p. 2-72
DROP ROWIDS
ADD CRCOLS
DROP CRCOLS
IDS You can also associate a table with a named-row type or specify a new storage
space to store large-object data.
In addition, you can add or drop rowid columns and shadow columns that
for Enterprise Replication. However, you cannot specify these options in
conjunction with any other alterations. ♦
When you add a rowid column, the database server assigns a unique number
to each row that remains stable for the life of the row. The database server
creates an index that it uses to find the physical location of the row. After you
add the rowid column, each row of the table contains an additional 4 bytes to
store the rowid value.
Tip: Use the ADD ROWIDS clause only on fragmented tables. In nonfragmented
tables, the rowid column remains unchanged. Informix recommends that you use
primary keys as an access method rather than exploiting the rowid column.
ADD Clause
Use the ADD clause to add a column to a table.
,
( New Column )
New Column
Data Type
new_column p. 4-53
Single-Column BEFORE column
DEFAULT
Clause Constraint
p. 2-60 Format
p. 2-62
■ You cannot add a serial column to a table if the table contains data.
XPS ■ In Extended Parallel Server, you cannot add a column to a table that
has a bit-mapped index. ♦
If you do not include the BEFORE option, the database server adds the new
column or list of columns to the end of the table definition by default.
In the following example, the BEFORE option directs the database server to
add the item_weight column before the total_price column:
ALTER TABLE items
ADD (item_weight DECIMAL(6,2) NOT NULL
BEFORE total_price)
DEFAULT Clause
Use the DEFAULT clause to specify the default value that the database server
should insert in a column when an explicit value for the column is not
specified.
DEFAULT literal
NULL
USER
+
CURRENT
DATETIME
Field Qualifier
p. 4-71
TODAY
SITENAME
DBSERVERNAME
If the table that you are altering already has rows in it when you add a
column that contains a default value, the database server inserts the default
value for all pre-existing rows.
For more information about the options of the DEFAULT clause, refer to
“DEFAULT Clause” on page 2-234.
In this example, each existing row in the items table has a default value of
2.00 for the item_weight column.
UNIQUE
+ +
NOT NULL
+ DISTINCT Constraint
Definition
PRIMARY KEY p. 2-64
Constraint
Definition REFERENCES
p. 2-64 Clause
p. 2-64
CHECK
Clause
p. 2-68
The following rules apply when you place primary-key or unique constraints
on existing columns:
You cannot place a unique constraint on a BYTE or TEXT column, nor can you
place referential constraints on these types of columns. You can place a check
constraint on a BYTE or TEXT column. However, you can check only for IS
NULL, IS NOT NULL, or LENGTH.
The following statement is valid whether or not the table contains data:
ALTER TABLE items
ADD (item_weight DECIMAL(6,2)
DEFAULT 2.0 NOT NULL
BEFORE total_price)
Constraint Definition
IDS Use the Constraint Definition portion of the ALTER TABLE statement to assign
a name to a constraint and to set the mode of the constraint to disabled,
enabled, or filtering. ♦
XPS In Extended Parallel Server, use the Constraint Definition portion of the
ALTER TABLE statement to assign a name to a constraint. ♦
DISABLED
ENABLED
FILTERING
WITH ERROR
WITHOUT ERROR
REFERENCES Clause
The REFERENCES clause allows you to place a foreign-key reference on a
column. The referenced column can be in the same table as the referencing
column, or the referenced column can be in a different table in the same
database.
REFERENCES table
, +
( column ) ON DELETE CASCADE
If you specify this option, later when you delete a row in the parent table, the
database server also deletes any rows associated with that row (foreign keys)
in a child table. The principal advantage to the cascading deletes feature is
that it allows you to reduce the quantity of SQL statements you need to
perform delete actions.
For example, in the stores_demo database, the stock table contains the
stock_num column as a primary key. The catalog table refers to the
stock_num column as a foreign key. The following ALTER TABLE statements
drop an existing foreign-key constraint (without cascading delete) and add a
new constraint that specifies cascading deletes:
ALTER TABLE catalog DROP CONSTRAINT aa
Restrictions
If a table has a trigger with a DELETE trigger event, you cannot define a
cascading-delete referential constraint on that table. You receive an error
when you attempt to add a referential constraint that specifies ON DELETE
CASCADE to a table that has a delete trigger.
For information about syntax restrictions and locking implications when you
delete rows from tables that have cascading deletes, see “Considerations
When Tables Have Cascading Deletes” on page 2-375.
CHECK Clause
A check constraint designates a condition that must be met before data can be
inserted into a column.
( Condition )
CHECK p. 4-27
During an insert or update, if a row evaluates to false for any check constraint
defined on a table, the database server returns an error. The database server
does not return an error if a row evaluates to null for a check constraint. In
some cases, you might wish to use both a check constraint and a NOT NULL
constraint.
Check constraints are defined using search conditions. The search condition
cannot contain the following items: subqueries, aggregates, host variables,
rowids, or user-defined routines. In addition, the search condition cannot
contain the following built-in functions: CURRENT, USER, SITENAME,
DBSERVERNAME, or TODAY.
You cannot create check constraints for columns across tables. When you are
using the ADD or MODIFY clause, the check constraint cannot depend upon
values in other columns of the same table. The following example adds a new
column, unit_price, to the items table and includes a check constraint that
ensures that the entered value is greater than 0:
ALTER TABLE items
ADD (unit_price MONEY (6,2) CHECK (unit_price > 0) )
To create a constraint that checks values in more than one column, use the
ADD CONSTRAINT clause. The following example builds a constraint on the
column that was added in the previous example. The check constraint now
spans two columns in the table.
ALTER TABLE items ADD CONSTRAINT
CHECK (unit_price < total_price)
DROP Clause
Use the DROP clause to drop one or more columns from a table.
DROP column
,
( column )
You cannot issue an ALTER TABLE DROP statement that would drop every
column from the table. At least one column must remain in the table.
XPS In Extended Parallel Server, you cannot use the DROP clause if the table has
a dependent GK index. ♦
Because any constraints that are associated with a column are dropped when
the column is dropped, the structure of other tables might also be altered
when you use this clause. For example, if the dropped column is a unique or
primary key that is referenced in other tables, those referential constraints
also are dropped. Therefore the structure of those other tables is also altered.
After the ALTER TABLE statement, tab2 has only one column. The col1trig
trigger is invalidated because the action clause as it is currently defined with
values for two columns cannot occur.
If you drop a column that occurs in the triggering column list of an UPDATE
trigger, the database server drops the column from the triggering column list.
If the column is the only member of the triggering column list, the database
server drops the trigger from the table. For more information on triggering
columns in an UPDATE trigger, see “CREATE TRIGGER” on page 2-296.
If a trigger is invalidated when you alter the underlying table, drop and then
recreate the trigger.
The database server does not automatically drop the column because you can
change the order of columns in a table by dropping a column and then
adding a new column with the same name. In this case, views based on the
altered table continue to work. However, they retain their original sequence
of columns.
If a view is invalidated when you alter the underlying table, you must rebuild
the view.
MODIFY Clause
Use the MODIFY clause to change the data type of a column and the length of
a character column, to add or change the default value for a column, and to
allow or disallow nulls in a column.
Modify Column
Clause
XPS In Extended Parallel Server, you cannot use the MODIFY clause if the table
has a dependent GK index. ♦
IDS You cannot change the data type of a column to be a collection type or a row
type. ♦
When you modify a column, all attributes previously associated with that
column (that is, default value, single-column check constraint, or referential
constraint) are dropped. When you want certain attributes of the column to
remain, such as PRIMARY KEY, you must re-specify those attributes. For
example, if you are changing the data type of an existing column, quantity,
to SMALLINT, and you want to keep the default value (in this case, 1) and
non-null attributes for that column, you can issue the following ALTER TABLE
statement:
ALTER TABLE items
MODIFY (quantity SMALLINT DEFAULT 1 NOT NULL)
For example, if you modify a column that has a unique constraint, the unique
constraint is dropped. If this column was referenced by columns in other
tables, those referential constraints are also dropped. In addition, if the
column is part of a multiple-column primary-key or unique constraint, the
multiple-column constraints are not dropped, but any referential constraints
placed on the column by other tables are dropped. For example, a column is
part of a multiple-column primary-key constraint. This primary key is refer-
enced by foreign keys in two other tables. When this column is modified, the
multiple-column primary-key constraint is not dropped, but the referential
constraints placed on it by the two other tables are dropped.
IDS You can also use the MODIFY clause to change a BYTE column to a BLOB
column and a TEXT column to a CLOB column. ♦
As an alternative, you can use the INSERT statement to create a gap in the
sequence of a serial column. For more information, see “Inserting Values into
Serial Columns” on page 2-543.
Suppose you have row types parent, child1, child2, and child3.
CREATE ROW TYPE parent (a int);
CREATE ROW TYPE child1 (s serial) UNDER parent;
CREATE ROW TYPE child2 (b float, s8 serial8) UNDER child1;
CREATE ROW TYPE child3 (d int) UNDER child2;
To change the next serial and next serial 8 numbers to 75, you can enter the
following command:
ALTER TABLE child3tab
MODIFY (s serial(75), s8 serial8(75))
When the ALTER TABLE statement executes, the database server updates
corresponding serial columns in the child1, child2, and child3 tables.
When you change the data type of an existing column, all data is converted
to the new data type, including numbers to characters and characters to
numbers (if the characters represent numbers). The following statement
changes the data type of the quantity column:
ALTER TABLE items MODIFY (quantity CHAR(6))
You can modify an existing column that did not permit nulls to permit nulls.
To do this, specify MODIFY with the column name and the existing data type,
and omit the NOT NULL keywords. The omission of the NOT NULL keywords
drops the not-null constraint on the column. If a unique index exists on the
column, you can remove it using the DROP INDEX statement.
6. After you fix all the nonconforming rows in the target table, issue the
SET statement again to switch the disabled constraint to the enabled
mode.
This time the constraint is enabled, and no integrity-violation error
message is returned because all rows in the target table now satisfy
the new constraint.
When you modify a column in a table, the triggers based on that table remain
unchanged. However, the column modification might invalidate the trigger.
After the ALTER TABLE statement, column i4 accepts only character values.
Because character columns accept only values enclosed in quotation marks,
the action clause of the col1trig trigger is invalidated.
If a trigger is invalidated when you modify the underlying table, drop and
then recreate the trigger.
,
PUT column IN ( sbspace )
,
( )
EXTENT SIZE kilobytes
LOG
NO LOG
HIGH INTEG
When you modify the storage characteristics of a column that holds smart
large objects, the database server does not alter smart large objects that
already exist. The database server applies the new storage characteristics to
only those smart large objects that are inserted after the ALTER TABLE
statement takes effect.
Multiple-Column
ADD CONSTRAINT Constraint Format
p. 2-81
( Multiple-Column )
Constraint Format
p. 2-81
For example, to add a unique constraint to the fname and lname columns of
the customer table, use the following statement:
ALTER TABLE customer
ADD CONSTRAINT UNIQUE (lname, fname)
When you do not provide a constraint name, the database server provides
one. You can find the name of the constraint in the sysconstraints system
catalog table. For more information about the sysconstraints system catalog
table, see the Informix Guide to SQL: Reference.
UNIQUE ( column )
+ +
CHECK
Clause
p. 2-68
IDS ■ The total length of the list of columns cannot exceed 390 bytes. ♦
XPS ■ The total length of the list of columns cannot exceed 255 bytes. ♦
You can assign a name to the constraint and set its mode by means of
“Constraint Definition” on page 2-64.
When you use this clause, the size of existing extents does not change. You
cannot change the size of existing extents without unloading all of the data.
XPS TABLE
Locking
Granularity Option Purpose
When you use the ADD TYPE clause, you assign a named-row type to a table
whose columns match the fields of the row type.
You cannot combine the ADD TYPE clause with any clause that changes the
structure of the table. That is, you cannot use an ADD, DROP, or MODIFY
clause in the same statement as the ADD TYPE clause.
Tip: To change the data type of a column, use the MODIFY clause. The ADD TYPE
clause does not allow you to change column data types.
TYPE ( RAW )
STATIC
OPERATIONAL
STANDARD
Other than the default option (STANDARD) that is used for OLTP databases,
these Usage-TYPE options are used primarily to improve performance in data
warehousing databases.
Option Purpose
Option Purpose
■ You cannot change the usage type if the table has a dependent GK
index.
■ You must perform a level-0 archive before the usage type of a table
can be altered to STANDARD from any other type.
■ If you want to change the usage type of a table to RAW, you must
drop all indexes on the table before you do so.
■ If you have triggers defined on the table, you cannot change the
usage type to RAW or STATIC.
That is, raw and static tables do not support triggers.
■ You cannot use this clause with SCRATCH or TEMP tables.
That is, you cannot change any of these types of tables to either a
SCRATCH or TEMP table. Similarly, you cannot change a SCRATCH or
TEMP table to any of these types of tables.
If a table is part of a table hierarchy, you cannot drop its type unless it is the
last subtype in the hierarchy. That is, you can only drop a type from a table if
that table has no subtables. When you drop the type of a subtable, it is
automatically removed from the hierarchy. The table rows are deleted from
all indexes defined by its supertables.
Related Information
Related statements: CREATE TABLE, DROP TABLE, LOCK TABLE, and SET
Database Object Mode
For a discussion of database and table creation, see the Informix Guide to
Database Design and Implementation.
+
BEGIN WORK
Use the BEGIN WORK statement to start a transaction (a sequence of database
operations that the COMMIT WORK or ROLLBACK WORK statement
terminates). Use the BEGIN WORK WITHOUT REPLICATION statement to start
a transaction that does not replicate to other database servers.
Syntax
BEGIN
WORK
IDS
WORK WITHOUT REPLICATION
E/C
Usage
Each row that an UPDATE, DELETE, or INSERT statement affects during a
transaction is locked and remains locked throughout the transaction. A trans-
action that contains many such statements or that contains statements
affecting many rows can exceed the limits that your operating system or the
database server configuration imposes on the maximum number of simulta-
neous locks. If no other user is accessing the table, you can avoid locking
limits and reduce locking overhead by locking the table with the LOCK TABLE
statement after you begin the transaction. Like other locks, this table lock is
released when the transaction terminates. The example of a transaction on
“Example of BEGIN WORK” on page 2-93 includes a LOCK TABLE statement.
Important: You can issue the BEGIN WORK statement only if a transaction is not in
progress. If you issue a BEGIN WORK statement while you are in a transaction, the
database server returns an error.
E/C In ESQL/C, if you use the BEGIN WORK statement within a UDR called by a
WHENEVER statement, specify WHENEVER SQLERROR CONTINUE and
WHENEVER SQLWARNING CONTINUE before the ROLLBACK WORK
statement. These statements prevent the program from looping if the
ROLLBACK WORK statement encounters an error or a warning. ♦
WORK Keyword
The WORK keyword is optional in a BEGIN WORK statement. The following
two statements are equivalent:
BEGIN;
BEGIN WORK;
■ DATABASE
■ COMMIT WORK
■ CREATE DATABASE
■ ROLLBACK WORK
An error is generated if you use a BEGIN WORK statement after any other
statement.
You cannot use the DECLARE cursor CURSOR WITH HOLD with the BEGIN
WORK WITHOUT REPLICATION statement.
For more information about data replication, see the Guide to Informix
Enterprise Replication.
Related Information
Related statements: COMMIT WORK, ROLLBACK WORK
For discussions of transactions and locking, see the Informix Guide to SQL:
Tutorial.
E/C
CLOSE
Use the CLOSE statement when you no longer need to refer to the rows that
a select or function cursor produced or when you want to flush and close an
insert cursor.
Syntax
CLOSE cursor_id
cursor_id_var
Usage
Closing a cursor makes the cursor unusable for any statements except OPEN
or FREE and releases resources that the database server had allocated to the
cursor. A CLOSE statement treats a cursor that is associated with an INSERT
statement differently than one that is associated with a SELECT or EXECUTE
FUNCTION (or EXECUTE PROCEDURE) statement.
You can close a cursor that was never opened or that has already been closed.
No action is taken in these cases.
After you close a select or function cursor, you cannot execute a FETCH
statement that names that cursor until you have reopened it.
The SQLCODE field of the sqlca structure, sqlca.sqlcode, indicates the result
of the CLOSE statement for an insert cursor. If all buffered rows are success-
fully inserted, SQLCODE is set to zero. If an error is encountered, the
sqlca.sqlcode field in the SQLCODE is set to a negative error message number.
When SQLCODE is zero, the row buffer space is released, and the cursor is
closed; that is, you cannot execute a PUT or FLUSH statement that names the
cursor until you reopen it.
Tip: When you encounter an SQLCODE error, a corresponding SQLSTATE error
value also exists. For information about how to get the message text, check the GET
DIAGNOSTICS statement.
For more information on how to use a collection cursor, see the following
sections: “Fetching From a Collection Cursor” on page 2-466 and “Inserting
into a Collection Cursor” on page 2-599.
For how to use insert cursors and the WITH HOLD clause, see “DECLARE”
on page 2-349.
Related Information
Related statements: DECLARE, FETCH, FLUSH, FREE, OPEN, PUT, and SET
AUTOFREE
+
CLOSE DATABASE
Use the CLOSE DATABASE statement to close the current database.
Syntax
CLOSE DATABASE
Usage
When you issue a CLOSE DATABASE statement, you can issue only the
following SQL statements immediately after it:
■ CONNECT
■ CREATE DATABASE
■ DATABASE
■ DROP DATABASE
■ DISCONNECT
This statement is valid only if an explicit connection existed before
you issued the CLOSE DATABASE statement.
Issue the CLOSE DATABASE statement before you drop the current database.
If your database has transactions, and if you have started a transaction, you
must issue a COMMIT WORK statement before you use the CLOSE DATABASE
statement.
The following example shows how to use the CLOSE DATABASE statement to
drop the current database:
DATABASE stores_demo
.
.
.
CLOSE DATABASE
DROP DATABASE stores_demo
When you issue the CLOSE DATABASE statement, declared cursors are no
longer valid. You must re-declare any cursors that you want to use. ♦
Related Information
Related statements: CONNECT, CREATE DATABASE, DATABASE,
DISCONNECT, and DROP DATABASE
COMMIT WORK
Use the COMMIT WORK statement to commit all modifications made to the
database from the beginning of a transaction. This statement informs the
database server that you reached the end of a series of statements that must
succeed as a single unit. The database server takes the required steps to make
sure that all modifications made by the transaction are completed correctly
and committed to disk.
Syntax
COMMIT
WORK
Usage
Use the COMMIT WORK statement when you are sure you want to keep
changes that are made to the database from the beginning of a transaction.
Use the COMMIT WORK statement only at the end of a multistatement
operation.
The COMMIT WORK statement releases all row and table locks.
E/C In ESQL/C, the COMMIT WORK statement closes all open cursors except those
declared with hold. ♦
WORK Keyword
The WORK keyword is optional in a COMMIT WORK statement. The following
two statements are equivalent:
COMMIT;
COMMIT WORK;
Example
The following example shows a transaction bounded by BEGIN WORK and
COMMIT WORK statements. In this example, the user first deletes the row
from the call_type table where the value of the call_code column is O. The
user then inserts a new row in the call_type table where the value of the
call_code column is S. The database server guarantees that both operations
succeed or else neither succeeds.
BEGIN WORK;
DELETE FROM call_type WHERE call_code = 'O';
INSERT INTO call_type VALUES ('S', 'order status');
COMMIT WORK;
However, if you do not issue a BEGIN WORK statement, the database server
executes each statement within its own transaction. These single-statement
transactions do not require either a BEGIN WORK statement or a COMMIT
WORK statement.
You must issue an explicit COMMIT WORK statement to mark the end of each
transaction. If you fail to do so, the database server rolls back the modifica-
tions to the database that the transaction made.
Related Information
Related statements: BEGIN WORK, ROLLBACK WORK, and DECLARE
+
CONNECT
Use the CONNECT statement to connect to a database environment.
Syntax
Database
CONNECT TO Environment
p. 2-108
E/C E/C
USER
AS ' connection ' Clause
E/C
p. 2-112
AS connection_var
DEFAULT
Usage
The CONNECT statement connects an application to a database environment.
The database environment can be a database, a database server, or a database
and a database server. If the application successfully connects to the specified
database environment, the connection becomes the current connection for
the application. SQL statements fail if no current connection exists between an
application and a database server. If you specify a database name, the
database server opens the database.You cannot use the CONNECT statement
in a PREPARE statement.
WIN NT On Windows NT, the local connection mechanism is named pipes. Multiple
connections to the local server from one client can exist. ♦
Only one connection is current at any time; other connections are dormant.
The application cannot interact with a database through a dormant
connection. When an application establishes a new connection, that
connection becomes current, and the previous current transaction becomes
dormant. You can make a dormant connection current with the SET
CONNECTION statement. For more information, see “SET CONNECTION”
on page 2-694.
The user who executes the CONNECT statement cannot have the same user
name as an existing role in the database.
For information on using the USER clause to specify an alternate user name
when the CONNECT statement connects to a database server on a remote
host, see “USER Clause” on page 2-112.
Connection Identifiers
The optional connection name is a unique identifier that an application can
use to refer to a connection in subsequent SET CONNECTION and
DISCONNECT statements. If the application does not provide a connection
name (or a connection-host variable), it can refer to the connection using the
database environment. If the application makes more than one connection to
the same database environment, however, each connection must have a
unique connection name.
After you associate a connection name with a connection, you can refer to the
connection using only that connection name.
Connection Context
Each connection encompasses a set of information that is called the connection
context. The connection context includes the name of the current user, the
information that the database environment associates with this name, and
information on the state of the connection (such as whether an active trans-
action is associated with the connection). The connection context is saved
when an application becomes dormant, and this context is restored when the
application becomes current again. (For more information on dormant
connections, see “Making a Dormant Connection the Current Connection”
on page 2-695.)
DEFAULT Option
Use the DEFAULT option to request a connection to a default database server,
called a default connection. The default database server can be either local or
remote. To designate the default database server, set its name in the
environment variable INFORMIXSERVER. This form of the CONNECT
statement does not open a database.
If you select the DEFAULT option for the CONNECT statement, you must use
the DATABASE statement or the CREATE DATABASE statement to open or
create a database in the default database environment.
■ DATABASE
■ CREATE DATABASE
■ DROP DATABASE
main()
{
EXEC SQL connect to 'a@srv1' as 'A';
EXEC SQL connect to 'b@srv2' as 'B' with concurrent transaction;
EXEC SQL connect to 'c@srv3' as 'C' with concurrent transaction;
/*
Execute SQL statements in connection 'C' , starting a
transaction
*/
/*
Execute SQL statements starting a transaction in 'B'.
Now there are two active transactions, one each in 'B'
and 'C'.
*/
/*
Execute SQL statements starting a transaction in 'A'.
Now there are three active transactions, one each in 'A',
'B' and 'C'.
*/
/*
SET CONNECTION 'C' fails (current connection is still 'A')
The transaction in 'A' must be committed/rolled back since
connection 'A' was started without the CONCURRENT TRANSACTION
clause.
*/
/*
Now, there are two active transactions, in 'B' and in 'C',
which must be committed/rolled back separately
*/
Database Environment
'dbname'
'@dbservername'
'dbname@dbservername'
E/C db_var
UNIX On UNIX, the database server that you specify in dbservername must match
the name of a database server in the sqlhosts file. ♦
WIN NT On Windows NT, the database server that you specify in dbservername must
match the name of a database server in the sqlhosts subkey in the registry.
Informix recommends that you use the setnet32 utility to update the
registry. ♦
If the database server that you specify is not on-line, you receive an error.
The resulting DBPATH that your application uses is shown in the following
example:
//srvA://srvB://srvC
If the database does not reside on the default database server, or if the default
database server is not on-line, the application connects to the next database
server in DBPATH. In the previous example, that server would be srvB.
USER Clause
The USER clause specifies information that is used to determine whether the
application can access the target computer when the CONNECT statement
connects to the database server on a remote host. Subsequent to the
CONNECT statement, all database operations on the remote host use the
specified user name.
user_id_var
WIN NT On Windows NT, the login name you specify in user_id must be a valid login
name and must exist in User Manager. If the application connects to a remote
server, the login name must exist in the domain of both the client and the
server. ♦
■ The specified user lacks the privileges to access the database named
in the database environment.
■ The specified user does not have the required permissions to connect
to the remote host.
■ You supply a USER clause but do not include the USING
validation_var phrase.
E/C In compliance with the X/Open specification for the CONNECT statement, the
ESQL/C preprocessor allows a CONNECT statement that has a USER clause
X/O without the USING validation_var phrase. However, if the validation_var is not
present, the database server rejects the connection at runtime. ♦
Related Information
Related Statements: DISCONNECT, SET CONNECTION, DATABASE, and
CREATE DATABASE
+ CREATE AGGREGATE
IDS
Use the CREATE AGGREGATE statement to create a new aggregate function.
User-defined aggregates extend the functionality of the database server
because they can perform any kind of aggregate computation that the user
wants to implement.
Syntax
Owner Name
p. 4-257
Modifiers
INIT = init_func
ITER = iter_func
COMBINE = comb_func
FINAL = final_func
HANDLESNULLS
Usage
You can specify the INIT, ITER, COMBINE, FINAL, and HANDLESNULLS
modifiers in any order.
Important: You must specify the ITER and COMBINE modifiers in a CREATE
AGGREGATE statement. You do not have to specify the INIT, FINAL, and
HANDLESNULLS modifiers in a CREATE AGGREGATE statement.
The ITER, COMBINE, FINAL, and INIT modifiers specify the support functions
for a user-defined aggregate. These support functions do not have to exist at
the time you create the user-defined aggregate.
Before you use the average aggregate in a query, you must also use CREATE
FUNCTION statements to create the support functions specified in the
CREATE AGGREGATE statement. The following table gives an example of the
task that each support function might perform for average.
Parallel Execution
The database server can break up an aggregate computation into several
pieces and compute them in parallel. The database server using the INIT and
ITER support functions to compute each piece sequentially. Then the
database server uses the COMBINE function to combine the partial results
from all the pieces into a single result value. Whether an aggregate is parallel
is an optimization decision that is transparent to the user.
Related Information
Related statements: DROP AGGREGATE
For information about how to invoke a user-defined aggregate, see the
discussion of user-defined aggregates in the Expression segment.
For a description of the sysaggregates system catalog table that holds infor-
mation about user-defined aggregates, see the Informix Guide to SQL:
Reference.
+ CREATE CAST
IDS
Use the CREATE CAST statement to register a cast that converts data from one
data type to another.
Syntax
EXPLICIT
Usage
A cast is a mechanism that the database server uses to convert one data type
to another. The database server uses casts to perform the following tasks:
To create a cast, you must have the necessary privileges on both the source
data type and the target data type. All users have permission to use the built-in
data types. However, to create a cast to or from an opaque type, distinct type,
or named-row type requires the Usage privilege on that type.
The CREATE CAST statement registers a cast in the syscasts system catalog
table. For more information on syscasts, see the chapter on system catalog
tables in the Informix Guide to SQL: Reference.
■ Either the source data type or the target data type, but not both, can be
a built-in type.
■ Neither the source data type nor the target data type can be a distinct
type of the other.
■ Neither the source data type nor the target data type can be a collection
data type.
Explicit Casts
An explicit cast is a cast that you must specifically invoke, with either the
CAST AS keywords or with the cast operator (::). The database server does not
automatically invoke an explicit cast to resolve data type conversions. The
EXPLICIT keyword is optional; by default, the CREATE CAST statement
creates an explicit cast.
The following CREATE CAST statement defines an explicit cast from the
rate_of_return opaque data type to the percent distinct data type:
CREATE EXPLICIT CAST (rate_of_return AS percent
WITH rate_to_prcnt)
The following SELECT statement explicitly invokes this explicit cast in its
WHERE clause to compare the bond_rate column (of type rate_of_return) to
the initial_APR column (of type percent):
SELECT bond_rate FROM bond
WHERE bond_rate::percent > initial_APR
Implicit Casts
The database server invokes built-in casts to convert from one built-in data
type to another built-in type that is not directly substitutable. For example,
the database server performs conversion of a character type such as CHAR to
a numeric type such as INTEGER through a built-in cast.
An implicit cast is a cast that the database server can invoke automatically
when it encounters data types that cannot be compared with built-in casts.
This type of cast enables the database server to automatically handle conver-
sions between other data types.
To define an implicit cast, specify the IMPLICIT keyword in the CREATE CAST
statement. For example, the following CREATE CAST statement specifies that
the database server should automatically use the prcnt_to_char() function
when it needs to convert from the CHAR data type to a distinct data type,
percent:
CREATE IMPLICIT CAST (CHAR AS percent WITH prcnt_to_char)
This cast provides the database server with only the ability to automatically
convert from the CHAR data type to percent. For the database server to
convert from percent to CHAR, you need to define another implicit cast, as
follows:
CREATE IMPLICIT CAST (percent AS CHAR WITH char_to_prcnt)
Users can also invoke implicit casts explicitly. For more information on how
to explicitly invoke a cast function, see “Explicit Casts” on page 2-121.
When a built-in cast does not exist for conversion between data types, you
can create user-defined casts to make the necessary conversion.
WITH Clause
The WITH clause of the CREATE CAST statement specifies the name of the
user-defined function to invoke to perform the cast. This function is called
the cast function. You must specify a function name unless the source data type
and the target data type have identical representations. Two data types have
identical representations when the following conditions are met:
The cast function must be registered in the same database as the cast at the
time the cast is invoked, but need not exist when the cast is created. The
CREATE CAST statement does not check permissions on the specified function
name, or even verify that the cast function exists. Each time a user invokes the
cast explicitly or implicitly, the database server verifies that the user has
Execute privilege on the cast function.
Related Information
Related statements: CREATE FUNCTION, CREATE DISTINCT TYPE, CREATE
OPAQUE TYPE, CREATE ROW TYPE and DROP CAST
For more information about data types, casting, and conversion, see the Data
Types segment in this manual and the Informix Guide to SQL: Reference.
For examples that show how to create and use casts, see the Informix Guide to
SQL: Tutorial.
+
CREATE DATABASE
Use the CREATE DATABASE statement to create a new database.
Syntax
BUFFERED
LOG MODE ANSI
Usage
This statement is an extension to ANSI-standard syntax. The ANSI standard
does not provide any syntax for the construction of a database, that is how a
database comes into existence.
The database name that you use must be unique within the database server
environment in which you are working. The database server creates the
system catalog tables that describe the structure of the database.
When you create a database, you alone have access to it. The database
remains inaccessible to other users until you, as DBA, grant database privi-
leges. For information on how to grant database privileges, see “GRANT” on
page 2-500.
If you do not specify the dbspace, the database server creates the system
catalog tables in the root dbspace. The following statement creates the
vehicles database in the root dbspace:
CREATE DATABASE vehicles
Logging Options
The logging options of the CREATE DATABASE statement determine the type
of logging that is done for the database.
In the event of a failure, the database server uses the log to re-create all
committed transactions in your database.
If you do not specify the WITH LOG option, you cannot use transactions or
the statements that are associated with databases that have logging (BEGIN
WORK, COMMIT WORK, ROLLBACK WORK, SET LOG, and SET ISOLATION).
XPS If you are using Extended Parallel Server, the CREATE DATABASE statement
always creates a database with unbuffered logging. The database server
ignores any logging specifications included in a CREATE DATABASE
statement. ♦
If you use a buffered log, you marginally enhance the performance of logging
at the risk of not being able to re-create the last few transactions after a failure.
(See the discussion of buffered logging in the Informix Guide to Database
Design and Implementation.)
ANSI-compliant databases are set apart from databases that are not ANSI-
compliant by the following features:
■ All statements are automatically contained in transactions.
All databases use unbuffered logging.
■ Owner-naming is enforced.
You must use the owner name when you refer to each table, view,
synonym, index, or constraint unless you are the owner.
■ For databases, the default isolation level is repeatable read.
■ Default privileges on objects differ from those in databases that are
not ANSI-compliant.
Users do not receive PUBLIC privilege to tables and synonyms by
default.
Other slight differences exist between databases that are ANSI-compliant and
those that are not. These differences are noted as appropriate with the related
SQL statement. For a detailed discussion of the differences between ANSI-
compliant databases and databases that are not ANSI-compliant, see the
Informix Guide to Database Design and Implementation.
Creating an ANSI-compliant database does not mean that you get ANSI
warnings when you run the database. You must use the -ansi flag or the
DBANSIWARN environment variable to receive warnings.
For additional information about -ansi and DBANSIWARN, see the Informix
Guide to SQL: Reference.
Related Information
Related statements: CLOSE DATABASE, CONNECT, DATABASE, DROP
DATABASE
Syntax
Usage
To create a distinct type in a database, you must have the Resource privilege.
Any user with the Resource privilege can create a distinct type from one of
the built-in data types, which are owned by user informix.
Important: You cannot create a distinct type on the SERIAL or SERIAL8 data type.
Once a distinct type is defined, only the type owner and the DBA can use it.
The owner of the type can grant other users the Usage privilege on the type.
A distinct type has the same storage structure as its source type.The
following statement creates the distinct type birthday, based on the built-in
data type, DATE:
CREATE DISTINCT TYPE birthday AS DATE
Dynamic Server uses the same storage method for the distinct type as it does
for the source type of the distinct type. However, a distinct type and its source
type cannot be compared in an operation unless one type is explicitly cast to
the other type.
To find out what privileges exist on a particular type, check the sysxtdtypes
system catalog table for the owner name and the sysxtdtypeauth system
catalog table for additional type privileges that might have been granted. For
more information on system catalog tables, see the Informix Guide to SQL:
Reference.
Because the two types have the same representation (the same length and
alignment), no support functions are required to implement the casts.
You can create an implicit cast between a distinct type and its source type.
However, to create an implicit cast, you must first drop the default explicit
cast between the distinct type and its source type.
All support functions and casts that are defined on the source type can be
used on the distinct type. However, casts and support functions that are
defined on the distinct type are not available to the source type.
You must explicitly cast one type to the other in the following situations:
■ To insert or update a column of one type with values of the other type
■ To use a relational operator to add, subtract, multiply, divide,
compare, or otherwise manipulate two values, one of the source type
and one of the distinct type
For example, suppose you create a distinct type, dist_type, that is based on
the NUMERIC data type. You then create a table with two columns, one of
type dist_type and one of type NUMERIC.
CREATE DISTINCT TYPE dist_type AS NUMERIC;
CREATE TABLE t(col1 dist_type, col2 NUMERIC);
To directly compare the distinct type and its source type or assign a value of
the source type to a column of the distinct type, you must cast one type to the
other, as the following examples show:
INSERT INTO tab (col1) VALUES (3.5::dist_type);
Related Information
Related statements: CREATE CAST, CREATE FUNCTION, CREATE OPAQUE
TYPE, CREATE ROW TYPE, DROP TYPE and DROP ROW TYPE
For information and examples that show how to use and cast distinct types,
see the Informix Guide to SQL: Tutorial.
For more information on when you might create a distinct type, see Extending
Informix Dynamic Server 2000.
Syntax
Column DATAFILES
CREATE EXTERNAL TABLE table Definition USING ( Clause )
p. 2-132 p.2-137
Table , , Table
Options Options
p. 2-139 p. 2-139
Usage
After you create a table with the CREATE EXTERNAL TABLE statement, you
can move data to and from the external source with an INSERT INTO...SELECT
statement.
Column Definition
SAMEAS template
,
Data
column Type
p. 4-53
Default Column-Level
Clause Constraints
p. 2-234 p. 2-136
Data
EXTERNAL Type
p. 4-53
' TEXT'
' HEX'
You must specify an external type for every column that is in fixed format.
You cannot specify an external type for delimited format columns except for
BYTE and TEXT columns where your specification is optional. For more infor-
mation, see “TEXT and HEX External Types” on page 2-135.
Big-Endian Format
The database server also supports two IBM-format binary representations of
integers: BINARY(2) for 16-bit integer storage and BINARY(4) for 32-bit
integer storage. The most significant byte of each number has the lowest
address; that is, binary-format integers are stored big-end first (big-endian
format) in the manner of IBM and Motorola processors. Intel processors and
some others store binary-format integers little-end first, a storage method
that the database server does not support for external data.
The database server uses the null representation for a fixed-format external
table to both interpret values as the data is loaded into the database and to
format null values into the appropriate data type when data is unloaded to
an external table.
The following examples are of column definitions with null values for a
fixed-format external table:
i smallint external “binary (2)” null “-32767”
li integer external “binary (4)” null “-99999”
d decimal (5,2) external “packed (5,2)” null “0xffffff”
z decimal (4,2) external “zoned (4,2)” null “0x0f0f0f0f”
zl decimal (3,2) external “zoned (3,2)” null “-1.00”
If the packed decimal or zoned decimal is stored with all bits cleared to
represent a null value, the null_string can be defined as “0x0”. The following
rules apply to the value assigned to a null_string:
■ The null representation must fit into the length of the external field.
■ If a bit pattern is defined, the null_string is not case sensitive.
■ If a bit pattern is defined, the null_string must begin with “0x”.
■ For numeric fields, the left-most fields are assigned zeros by the
database server if the bit pattern does not fill the entire field.
■ If the null representation is not a bit pattern, the null value must be a
valid number for that field.
Warning: If a row that contains a null value is unloaded into an external table and
the column that receives the null value has no null value defined, the database server
inserts a zero into the column.
You do not need to specify these external types. If you do not define an
external column specifically, Informix TEXT columns default to TEXT and
Informix BYTE columns default to HEX.
The database server interprets two adjacent field delimiters as a null value.
User-defined delimiters are limited to one byte each. For information about
delimiters if you are using a multibyte locale, see the Informix Guide to GLS
Functionality.
For more information on BYTE and TEXT data, see your Administrator’s Guide.
Column-Level Constraints
Use column-level constraints to limit the type of data that is allowed in a
column. Constraints at the column level are limited to a single column.
NOT NULL
CHECK ( Condition )
p. 4-27
Check constraints are defined with search conditions. The search condition
cannot contain subqueries, aggregates, host variables, or SPL routines. In
addition, it cannot include the following built-in functions: CURRENT, USER,
SITENAME, DBSERVERNAME, or TODAY.
When you define a check constraint at the column level, the only column that
the check constraint can check against is the column itself. In other words, the
check constraint cannot depend upon values in other columns of the table.
DATAFILES Clause
The DATAFILES clause names the external files that are opened when you use
external tables.
You can use cogroup names and coserver numbers when you describe the
input or output files for the external table definition. You can identify the
DATAFILES either by coserver number or by cogroup name. A coserver
number contains only digits. A cogroup name is a valid identifier that begins
with a letter but otherwise contains any combination of letters, digits, and
underscores.
If you use only some of the available coservers for reading or writing files,
you can designate these coservers as a cogroup using onutil and then use the
cogroup name rather than explicitly naming each coserver and file
separately. Whenever you use all coservers to manage external files, you can
use the predefined coserver_group.
Important: The formatted pathname option does not support the %o formatting
string.
Table Options
The optional table parameters include additional characteristics that define
the table.
DEFAULT
EXPRESS
DELUXE
SIZE num_rows
Use the table options keywords as the following table describes. You can use
each keyword whenever you plan to load or unload data unless only one of
the two modes is specified.
Keyword Purpose
DELUXE Sets a flag that causes the database server to load data in
deluxe mode
(load only)
Deluxe mode is required for loading into STANDARD tables.
EXPRESS Sets a flag that causes the database server to attempt to load
data in express mode
If you request express mode but indexes or unique constraints
exist on the table or the table contains BYTE or TEXT data, or
the target table is not RAW or OPERATIONAL, the load stops
with an error message reporting the problem.
MAXERRORS Sets the number of errors that are allowed per coserver before
the database server stops the load
(1 of 2)
Keyword Purpose
REJECTFILE Sets the full pathname for all coservers to the area where reject
files are written for data-conversion errors
If conversion errors occur and you have not specified
REJECTFILE or the reject files cannot be opened, the load job
ends abnormally.
For information on reject-file naming and use of formatting
characters, see “Reject Files” on page 2-142.
Reject Files
Rows that have conversion errors during a load or rows that violate check
constraints defined on the external table are written to a reject file on the
coserver that performs the conversion. Each coserver manages its own reject
file. The REJECTFILE keyword determines the name given to the reject file on
each coserver.
You can use the formatting characters %c and %n (but not %r) in the filename
format. Use the %c formatting characters to make the filenames unique. For
more information on formatting characters, see the section “Using
Formatting Characters” on page 2-138.
If you perform another load to the same table during the same session, any
earlier reject file of the same name is overwritten.
Element Purpose
record Record number in the input file where the error was detected
field-name External field name where the first error in the line occurred,
or '<none>' if the rejection is not specific to a particular
column
The reject file writes the coserver-number, filename, record, field-name and reason-
code in ASCII. The bad line information varies with the type of input file. For
delimited files or fixed-position character files, up to 80 characters of the bad
line are copied directly into the reject file. For Informix internal data files, the
bad line is not placed in the reject file, because you cannot edit the binary
representation in a file. However, coserver-number, filename, record, reason-code,
and field-name are still reported in the reject file so you can isolate the
problem.
Examples
The examples in this section show how you can name files to use in the
DATAFILES field.
Assume that the database server is running on four nodes, and one file is to
be read from each node. All files have the same name. The DATAFILES item
can then be as follows:
DATAFILES ("DISK:cogroup_all:/work2/unload.dir/mytbl")
Now, consider a system with 16 coservers where only three coservers have
tape drives attached (for example, coservers 2, 5, and 9). If you define a
cogroup for these coservers before you run load and unload commands, you
can use the cogroup name rather than a list of individual coservers when you
execute the commands. To set up the cogroup, run onutil.
% onutil
1> create cogroup tape_group
2> from coserver.2, coserver.5, coserver.9;
Cogroup successfully created.
If, instead, you want to process three files on each of two coservers, define the
files as follows:
DATAFILES ("DISK:1:/work2/extern.dir/mytbl.%r(1..3)",
"DISK:2:/work2/extern.dir/mytbl.%r(4..6)")
Related Information
Related statements: INSERT, SELECT, and SET PLOAD FILE
+ CREATE FUNCTION
IDS
Use the CREATE FUNCTION statement to create a user-defined function. With
this statement, you can register an external function or write and register an
SPL function.
Tip: If you are trying to create a function from text that is in a separate file, use the
CREATE FUNCTION FROM statement.
Syntax
, ;
SPECIFIC Specific
Name WITH ( Routine )
p. 4-296 Modifier
p. 4-274
Statement
SPL Block END FUNCTION
p. 4-298
External Routine
Ext Reference
p. 4-202
END FUNCTION
,
WITH LISTING IN 'pathname '
DOCUMENT Quoted String
p. 4-260
Usage
The database server supports user-defined functions written in the following
languages:
For information on how the manual uses the terms UDR, function, and
procedure as well as recommended usage, see “Relationship Between
Routines, Functions and Procedures” on page 2-201 and “Using CREATE
PROCEDURE Versus CREATE FUNCTION” on page 2-199, respectively.
E/C You can use a CREATE FUNCTION statement only within a PREPARE
statement. If you want to create a user-defined function for which the text is
known at compile time, you must put the text in a file and specify this file
with the CREATE FUNCTION FROM statement. ♦
Ext Before you can create an external function, you must also have the Usage
privilege on the language in which you will write the function. For more
information, see “GRANT” on page 2-500. ♦
SPL By default, the Usage privilege on SPL is granted to PUBLIC. You must also
have at least the Resource privilege on a database to create an SPL function
within that database. ♦
If you do not use the DBA keyword, the UDR is known as an owner-privileged
UDR.
Ext If an external function has a negator function, you must grant the Execute
privilege on both the external function and its negator function before users
can execute the external function. ♦
Naming a Function
Because Dynamic Server offers routine overloading, you can define more than
one function with the same name, but different parameter lists. You might
want to overload functions in the following situations:
For a brief description of the routine signature which uniquely identifies each
user-defined function, see “Routine Overloading and Naming UDRs with a
Routine Signature” on page 4-52.
DOCUMENT Clause
The quoted string in the DOCUMENT clause provides a synopsis and
description of the UDR. The string is stored in the sysprocbody system
catalog table and is intended for the user of the UDR.
Anyone with access to the database can query the sysprocbody system
catalog table to obtain a description of one or all of the UDRs stored in the
database.
For example, the following query obtains a description of the SPL function
update_by_pct, shown in “SPL Functions” on page 2-150:
SELECT data FROM sysprocbody b, sysprocedures p
WHERE b.procid = p.procid
--join between the two catalog tables
AND p.procname = 'update_by_pct'
-- look for procedure named update_by_pct
AND b.datakey = 'D'-- want user document;
A UDR or application program can query the system catalog tables to fetch
the DOCUMENT clause and display it for a user.
Ext You can use a DOCUMENT clause at the end of the CREATE FUNCTION
statement, whether or not you use the END FUNCTION keywords. ♦
If you do not use the WITH LISTING IN clause, the compiler does not generate
a list of warnings.
UNIX If you specify a filename but not a directory, this listing file is created in your
home directory on the computer where the database resides. If you do not
have a home directory on this computer, the file is created in the root
directory (the directory named “/”). ♦
Windows If you specify a filename but not a directory, this listing file is created in your
current working directory if the database is on the local machine. Otherwise,
the default directory is %INFORMIXDIR%\bin. ♦
SPL functions are parsed, optimized (as far as possible), and stored in the
system catalog tables in executable format. The body of an SPL function is
stored in the sysprocbody system catalog table. Other information about the
function is stored in other system catalog tables, including sysprocedures,
sysprocplan, and sysprocauth. For more information about these system
catalog tables, see the discussion of the system catalog in the Informix Guide
to SQL: Reference.
You must use the END FUNCTION keywords with an SPL function.
Place a semicolon after the clause that immediately precedes the statement
block.
DEFINE n INT;
END FUNCTION
DOCUMENT "USAGE: Update a price by a percentage",
"Enter an integer percentage from 1 - 100",
"and a part id number"
WITH LISTING IN '/tmp/warn_file'
For more information on writing SPL functions, see the Informix Guide to SQL:
Tutorial. ♦
1. Write a Java static method, which can use the JDBC functions to
interact with the database server.
2. Compile the Java source file and create a jar file (the shared-object file
for Java).
3. Execute the install_jar() procedure with the EXECUTE PROCEDURE
statement to install the jar file in the current database.
4. If the UDR uses user-defined types, create a map between SQL data
types and Java classes.
Use the setUDTExtName() procedure that is explained in
“EXECUTE PROCEDURE” on page 2-444.
5. Register the UDR with the CREATE FUNCTION statement.
Rather than storing the body of an external routine directly in the database,
the database server stores only the pathname of the shared-object file that
contains the compiled version of the routine. When the database server
executes the external routine, the database server invokes the external object
code.
This function returns a single value of type INTEGER. The EXTERNAL NAME
clause specifies that the Java implementation of the sql_explosive_reaction()
function is a method called explosiveReaction(), which resides in the
Chemistry Java class that resides in the course_jar jar file.
For example, assume that user mike creates the following user-defined
function:
CREATE FUNCTION func1 () RETURNING INT;
CREATE TABLE tab1 (colx INT);
RETURN 1;
END FUNCTION
If user joan now executes function func1, user mike, not user joan, is the
owner of the newly created table tab1.
However, in the case of a DBA-privileged UDR, the user who executes the
UDR—not the UDR owner—owns any database objects created by the UDR,
unless another owner is specified for the database object within the UDR.
For example, assume that user mike creates the following user-defined
function:
CREATE DBA FUNCTION func2 () RETURNING INT;
CREATE TABLE tab2 (coly INT);
RETURN 1;
END FUNCTION
If user joan now executes function func2, user joan, not user mike, is the
owner of the newly created table tab2.
Related Information
Related statements: ALTER FUNCTION, ALTER ROUTINE, CREATE
PROCEDURE, CREATE FUNCTION FROM, DROP FUNCTION, DROP ROUTINE,
GRANT, EXECUTE FUNCTION, PREPARE, REVOKE, and UPDATE STATISTICS
For a discussion on creating and using SPL routines, see the Informix Guide to
SQL: Tutorial.
For a discussion of how to create and use external routines, see Extending
Informix Dynamic Server 2000.
For information about how to create C UDRs, see the DataBlade API
Programmer’s Manual.
Syntax
file_var Name of a program variable that The file that is specified in the Name must conform
holds the value of file program variable must exist. to language-specific
The file that you specify can rules for variable
contain only one CREATE names.
FUNCTION statement.
Usage
An ESQL/C program cannot directly create a user-defined function. That is,
it cannot contain the CREATE FUNCTION statement. However, you can create
these functions within an ESQL/C program with the following steps:
In the ESQL/C program, you can access the delete_order() SPL function with
the following CREATE FUNCTION FROM statement:
EXEC SQL create function from 'del_ord.sql';
If you are not sure whether the UDR in the file is a user-defined function or a
user-defined procedure, use the CREATE ROUTINE FROM statement.
The filename that you provide is relative. If you provide a simple filename (as
in the preceding example), the client application looks for the file in the
current directory.
Important: The ESQL/C preprocessor does not process the contents of the file that you
specify. It just sends the contents to the database server for execution. Therefore, there
is no syntactic check that the file that you specify in CREATE FUNCTION FROM
actually contains a CREATE FUNCTION statement. However, to improve readability
of the code, Informix recommends that you match these two statements.
Related Information
Related statements: CREATE FUNCTION, CREATE PROCEDURE, CREATE
PROCEDURE FROM, and CREATE ROUTINE FROM
+
CREATE INDEX
Use the CREATE INDEX statement to create an index for one or more columns
in a table, to specify whether or not it allows only unique values, to cluster
the physical table in the order of the index, and to designate where the index
should be stored.
Syntax
synonym XPS
Index Type
Options LOCK MODE
p. 2-159 Options
p. 2-181
Index Key
Specification
p. 2-161
IDS FILLFACTOR Storage IDS
Option Options
p. 2-171 p. 2-172 Index
USING
Access XPS Modes
Method p. 2-178
Clause USING BITMAP
p. 2-169
GK SELECT
XPS GK INDEX index ON static ( Clause )
p. 2-183
USING BITMAP
Usage
A secondary access method (sometimes referred to as an index access method) is
a set of database server functions that build, access, and manipulate an index
structure such as a B-tree, R-tree, or an index structure that a DataBlade
module provides. Typically, a secondary access method speeds up the
retrieval of data.
When you issue the CREATE INDEX statement, the table is locked in exclusive
mode. If another process is using the table, the database server cannot
execute the CREATE INDEX statement and returns an error.
XPS If you are using Extended Parallel Server, use the USING BITMAP keywords
to store the list of records in each key of the index as a compressed bitmap.
The storage option is not compatible with a bitmap index because bitmap
indexes must be fragmented in the same way as the table. ♦
Index-Type Options
The index-type options let you specify the characteristics of the index.
UNIQUE CLUSTER
DISTINCT
CLUSTER Option
Use the CLUSTER option to reorder the physical table in the order that the
index designates. The CREATE CLUSTER INDEX statement fails if a CLUSTER
index already exists.
CREATE CLUSTER INDEX c_clust_ix ON customer (zipcode)
This statement creates an index on the customer table that physically orders
the table by zip code.
XPS If you are using Extended Parallel Server, you cannot use the CLUSTER
option on STANDARD tables. In addition, you cannot use the CLUSTER option
and storage options in the same CREATE INDEX statement (see “Storage
Options” on page 2-172). When you create a clustered index the constrid of
any unique or referential constraints on the associated table changes. The
constrid is stored in the sysconstraints system catalog table. ♦
IDS Some secondary access methods (such as R-tree) do not support clustering.
Before you specify CLUSTER for your index, be sure that it uses an access
method that supports clustering. ♦
Index-Key Specification
Use the Index-Key Specification portion of the CREATE INDEX statement to
specify the key value for the index, an operator class, and whether the index
will be sorted in ascending or descending order.
,
( column )
IDS , IDS
ASC
function ( func_col ) op_class DESC
The index-key value can be one or more columns that contain built-in data
types. When multiple columns are listed, the concatenation of the set of
columns is treated as a single composite column for indexing.
IDS In addition, the index-key value can be one of the following types:
■ All the columns you specify must exist and must belong to the table
being indexed.
■ The maximum number of columns and the total width of all columns
vary with the database server. See “Creating Composite Indexes” on
page 2-164.
■ You cannot add an ascending index to a column or column list that
already has a unique constraint on it. See “Using the ASC and DESC
Sort-Order Options” on page 2-164.
■ You cannot add a unique index to a column or column list that has a
primary-key constraint on it. The reason is that defining the column
or column list as the primary key causes the database server to create
a unique internal index on the column or column list. So you cannot
create another unique index on this column or column list with the
CREATE INDEX statement.
■ The number of indexes you can create on the same column or same
sequence of columns is restricted. See “Restrictions on the Number
of Indexes on a Single Column” on page 2-167 and “Restrictions on
the Number of Indexes on a Sequence of Columns” on page 2-167.
IDS ■ You cannot create an index on a column that belongs to an external
table.
■ The column you specify cannot be a column whose data type is a
collection. ♦
The following example creates a composite index using the stock_num and
manu_code columns of the stock table:
CREATE UNIQUE INDEX st_man_ix ON stock (stock_num, manu_code
)
XPS You can include up to 16 columns in a composite index. The total width of all
indexed columns in a single CREATE INDEX statement cannot exceed
255 bytes. ♦
XPS
IDS A composite index can have up to 16 key parts. An index key part is either a
table column or the result of a user-defined function on one or more table
columns. A composite index can have any of the following items as an index
key:
The total width of all indexed columns in a single CREATE INDEX statement
cannot exceed 390 bytes. ♦
However, you can create a descending index on such columns, and you can
include such columns in composite ascending indexes in different combina-
tions. For example, the following sequence of statements is allowed:
CREATE TABLE customer (
customer_num SERIAL(101) UNIQUE,
fname CHAR(15),
lname CHAR(15),
company CHAR(20),
address1 CHAR(20),
address2 CHAR(20),
city CHAR(15),
state CHAR(2),
zipcode CHAR(5),
phone CHAR(18)
)
Because of this capability, it does not matter whether you create a single-
column index as an ascending or descending index. Whichever storage order
you choose for an index, the database server can traverse that index in
ascending or descending order when it processes queries.
However, if you create a composite index on a table, the ASC and DESC
keywords might be required. For example, if you want to enter a SELECT
statement whose ORDER BY clause sorts on multiple columns and sorts each
column in a different order and you want to use an index for this query, you
need to create a composite index that corresponds to the ORDER BY columns.
For example, suppose that you want to enter the following query:
SELECT stock_num, manu_code, description, unit_price
FROM stock
ORDER BY manu_code ASC, unit_price DESC
This query sorts first in ascending order by the value of the manu_code
column and then in descending order by the value of the unit_price column.
To use an index for this query, you need to issue a CREATE INDEX statement
that corresponds to the requirements of the ORDER BY clause. For example,
you can enter either of the following statements to create the index:
CREATE INDEX stock_idx1 ON stock
(manu_code ASC, unit_price DESC);
The composite index that was used for this query (stock_idx1 or stock_idx2)
cannot be used for queries in which you specify the same sort direction for
the two columns in the ORDER BY clause. For example, suppose that you
want to enter the following queries:
SELECT stock_num, manu_code, description, unit_price
FROM stock
ORDER BY manu_code ASC, unit_price ASC;
■ The ix1 and ix2 indexes achieve exactly the same results for sorts in
which the user specifies the same sort direction (ascending or
descending) for both columns. Therefore, you only need to create
one index of this pair.
■ The ix3 and ix4 indexes achieve exactly the same results for sorts in
which the user specifies different sort directions for the two columns
(ascending on the first column and descending on the second column
or vice versa). Therefore, you only need to create one index of this
pair.
Specify an operator class when you create an index if you have one of the
following situations:
■ A default operator class for the secondary access method does not
exist. For example, some of the user-defined access methods do not
provide a default operator class.
■ You want to use an operator class that is different from the default
operator class that the secondary access method provides.
For more information, see “Default Operator Classes” on page 2-197. The
following CREATE INDEX statement creates a B-tree index on the cust_tab
table that uses the abs_btree_ops operator class for the cust_num key:
CREATE INDEX c_num1_ix ON cust_tab (cust_num abs_btree_ops);
A secondary access method is a set of routines that perform all of the operations
needed to make an index available to a server, such as create, drop, insert,
delete, update, and scan.
The following example assumes that the database implements the R-tree
index. It creates an R-tree index on the location column that contains an
opaque data type, point.
CREATE INDEX loc_ix ON TABLE emp (location)
USING rtree;
SELECT name FROM emp
WHERE location N_equator_equals point('500, 0');
FILLFACTOR Option
Use the FILLFACTOR option to provide for expansion of an index at a later
date or to create compacted indexes.
FILLFACTOR percent
When the index is created, the database server initially fills only that
percentage of the nodes specified with the FILLFACTOR value.
The FILLFACTOR option takes effect only when you build an index on a table
that contains more than 5,000 rows and uses more than 100 table pages, when
you create an index on a fragmented table, or when you create a fragmented
index on a nonfragmented table.
The FILLFACTOR can also be set as a parameter in the ONCONFIG file. The
FILLFACTOR clause on the CREATE INDEX statement overrides the setting in
the ONCONFIG file.
For more information about the ONCONFIG file and the parameters you can
use with ONCONFIG, see your Administrator’s Guide.
Storage Options
The storage options let you specify the distribution scheme of an index. You
can use the IN clause to specify a storage space to hold the entire index, or you
can use the FRAGMENT BY clause to fragment the index across multiple
storage spaces
IN dbspace
XPS dbslice
IDS
extspace
FRAGMENT BY
Clause for Indexes
p. 2-175
If you do not use the storage options (that is, if you do not specify a distri-
bution scheme), by default the index inherits the distribution scheme as of
the table on which it is built. Such an index is called an attached index.
An attached index is created in the same dbspace (or dbspaces if the table is
fragmented) as the table on which it is built. If the distribution scheme of a
table changes, all attached indexes start using the new distribution scheme.
When you specify one of the storage options, you create a detached index.
Detached indexes are indexes that are created with a specified distribution
scheme. Even if the distribution scheme specified for the index is identical to
that specified for the table, the index is still considered to be detached. If the
distribution scheme of a table changes, all detached indexes continue to use
their own distribution scheme.
If you are using Extended Parallel Server, you cannot use the CLUSTER
option and storage options in the same CREATE INDEX statement. See
“CLUSTER Option” on page 2-160. ♦
IN Clause
Use the IN clause to specify a storage space to hold the entire index. The
storage space that you specify must already exist.
The IN dbspace clause allows you to isolate an index. For example, if the
customer table is created in the custdata dbspace, but you want to create an
index in a separate dbspace called custind, use the following statements:
CREATE TABLE customer
.
.
.
IN custdata EXTENT SIZE 16
, REMAINDER IN dbspace
XPS
, ,
IN dbslice
,
HYBRID ( column )
,
EXPRESSION expr IN dbslice , expr IN dbslice
REMAINDER
dbspace dbspace
, ,
( dbspace ) ( dbspace )
XPS You can fragment indexes on any column of a table, even if the table spans
multiple coservers. The columns that you specify in the FRAGMENT BY clause
do not have to be part of the index key.
DISABLED
ENABLED
FILTERING
WITHOUT ERROR
WITH ERROR
Mode Purpose
DISABLED The database server does not update the index after insert, delete,
and update operations that modify the base table.
The optimizer does not use the index during the execution of
queries.
ENABLED The database server updates the index after insert, delete, and
update operations that modify the base table.
The optimizer uses the index during query execution.
If an insert or update operation causes a duplicate key value to be
added to a unique index, the statement fails.
(1 of 2)
Mode Purpose
FILTERING The database server updates a unique index after insert, delete, and
update operations that modify the base table. (This option is not
available with duplicate indexes.)
The optimizer uses the index during query execution.
If an insert or update operation causes a duplicate key value to be
added to a unique index in filtering mode, the statement continues
processing, but the bad row is written to the violations table
associated with the base table. Diagnostic information about the
unique-index violation is written to the diagnostics table associated
with the base table.
(2 of 2)
If you specify filtering for a unique index, you can also specify one of the
following error options.
■ When you add a new unique index to an existing base table and
specify the enabled or filtering mode for the index, your CREATE
INDEX statement succeeds provided that no duplicate values exist in
the indexed column that would cause a unique-index violation.
However, if any duplicate values exist in the indexed column, your
CREATE INDEX statement fails and returns an error.
■ When you add a new unique index to an existing base table in the
enabled or filtering mode, and duplicate values exist in the indexed
column, erroneous rows in the base table are not filtered to the viola-
tions table. Thus, you cannot use a violations table to detect the
erroneous rows in the base table.
1. Add the index in the disabled mode. Issue the CREATE INDEX
statement again, but this time specify the DISABLED keyword.
2. Start a violations and diagnostics table for the target table with the
START VIOLATIONS TABLE statement.
3. Issue a SET Database Object Mode statement to switch the mode of
the index to enabled. When you issue this statement, existing rows in
the target table that violate the unique-index requirement are dupli-
cated in the violations table. However, you receive an integrity-
violation error message, and the index remains disabled.
4. Issue a SELECT statement on the violations table to retrieve the
nonconforming rows that are duplicated from the target table. You
might need to join the violations and diagnostics tables to get all the
necessary information.
5. Take corrective action on the rows in the target table that violate the
unique-index requirement.
6. After you fix all the nonconforming rows in the target table, issue the
SET Database Object Mode statement again to switch the disabled
index to the enabled mode. This time the index is enabled, and no
integrity violation error message is returned because all rows in the
target table now satisfy the new unique-index requirement.
When an index is disabled, the database server stops updating it and stops
using it during queries, but the catalog information about the disabled index
is retained. So you cannot create a new index on a column or set of columns
if a disabled index on that column or set of columns already exists.
NORMAL
When you use the coarse-lock mode, index-level locks are acquired on the
index instead of item-level or page-level locks. This mode reduces the
number of lock calls on an index.
Use the coarse-lock mode when you know the index is not going to change,
that is, when read-only operations are performed on the index.
If you do not specify a lock mode, the default is normal. That is, the database
server places item-level or page-level locks on the index as necessary.
A GK index is defined on a table when that table is the one being indexed. A
GK index depends on a table when the table appears in the FROM clause of the
index. Before you create a GK index, keep the following issues in mind:
FROM indexed_table
synonym
, table
synonym alias
AS
All tables that appear in the FROM clause must be local static tables. That is,
no views, non-static, or remote tables are allowed.
The tables that are mentioned in the FROM clause must be transitively joined
on key to the indexed table. Table A is transitively joined on key to table B if
A and B are joined with equal joins on the unique-key columns of A. For
example, suppose tables A, B, and C each have col1 as a primary key. In the
following example, B is joined on key to A and C is joined on key to B. C is
transitively joined on key to A.
CREATE GK INDEX gki
(SELECT A.col1, A.col2 FROM A, B, C
WHERE A.col1 = B.col1 AND B.col1 = C.col1)
AND
WHERE Condition
p. 4-27
Join
p. 2-666
Related Information
Related statements: ALTER INDEX, CREATE OPCLASS, CREATE TABLE, DROP
INDEX, and SET Database Object Mode
GLS For a discussion of the GLS aspects of the CREATE INDEX statement, see the
Informix Guide to GLS Functionality. ♦
Syntax
VARIABLE
,
, Opaque-Type Modifier
p. 2-188
Usage
The CREATE OPAQUE TYPE statement registers a new opaque type in the
database. Dynamic Server stores information on extended data types,
including opaque types, in the sysxtdtypes system catalog table.
To find out what privileges exist on a particular type, check the sysxtdtypes
system catalog table for the owner name and the sysxtdtypeauth system
catalog table for additional type privileges that might have been granted. For
more information on system catalog tables, see the Informix Guide to SQL:
Reference.
The owner name is case sensitive. If you do not put quotes around the owner
name, the name of the opaque-type owner is stored in uppercase letters. ♦
INTERNALLENGTH Modifier
The INTERNALLENGTH modifier specifies the size of an opaque type. The
way you specify the internal length defines whether the opaque type is fixed
length or varying length.
To create a varying-length opaque type, use the VARIABLE keyword for the
INTERNALLENGTH modifier. The following statement creates a variable-
length opaque type called varlen_typ:
CREATE OPAQUE TYPE varlen_typ(INTERNALLENGTH=VARIABLE,
MAXLEN=1024)
Opaque-Type Modifier
MAXLEN = length
CANNOTHASH
PASSEDBYVALUE
ALIGNMENT = align_value
■ A data structure that serves as the internal storage of the opaque type
The internal storage details of the data type are hidden, or opaque.
Once you define a new opaque type, the database server can manip-
ulate it without knowledge of the C structure in which it is stored.
■ Support functions that allow the database server to interact with this
internal structure
The support functions tell the database server how to interact with
the internal structure of the type. These support functions must be
written in the C programming language.
■ Additional user-defined functions that can be called by other
support functions or by end users to operate on the opaque type
(optional)
Possible support functions include operator functions and cast
functions. Before you can use these functions in SQL statements, they
must be registered with the appropriate DEFINE CAST, CREATE
PROCEDURE, or CREATE FUNCTION statement.
The following table summarizes the support functions for an opaque type.
Once you write the necessary support functions for the opaque type, use the
CREATE FUNCTION statement to register these support functions in the same
database as the opaque type. Certain support functions convert other data
types to or from the new opaque type. After you create and register these
support functions, use the CREATE CAST statement to associate each function
with a particular cast. The cast must be registered in the same database as the
support function.
When you have written the necessary source code to define the opaque type,
you then use the CREATE OPAQUE TYPE statement to register the opaque type
in the database.
Related Information
Related statements: CREATE CAST, CREATE DISTINCT TYPE, CREATE
FUNCTION, CREATE ROW TYPE, CREATE TABLE, and DROP TYPE
For a summary of an opaque type, see the Informix Guide to SQL: Reference.
For information about the GLS aspects of the CREATE OPAQUE TYPE
statement, refer to the Informix Guide to GLS Functionality.
+ CREATE OPCLASS
IDS
Use the CREATE OPCLASS statement to create an operator class for a secondary
access method.
Syntax
, ,
( Strategy Specification ) ( )
p. 2-195 SUPPORT support_function
Usage
An operator class is the set of operators that Dynamic Server associates with
the specified secondary access method for query optimization and building
the index. A secondary access method (sometimes referred to as an index
access method) is a set of database server functions that build, access, and
manipulate an index structure such as a B-tree, R-tree, or an index structure
that a DataBlade module provides.
■ an index to use a different order for the data than the sequence
provided by the default operator class.
■ a set of operators that is different from any existing operator classes
that are associated with a particular secondary access method.
You must have the Resource privilege or be the DBA to create an operator
class. The actual name of an operator class is an SQL identifier. When you
create an operator class, opclass name must be unique within a database.
The owner name is case sensitive. If you do not put quotes around the owner
name, the name of the operator-class owner is stored in uppercase letters. ♦
For more information on the btree secondary access method, see “Default
Operator Classes” on page 2-197.
■ Strategy functions
Specify strategy functions of an operator class in the STRATEGY
clause of the CREATE OPCLASS statement. In the preceding CREATE
OPCLASS statement, the abs_btree_ops operator class has five
strategy functions.
■ Support functions
Specify support functions of an operator class in the SUPPORT clause
of the CREATE OPCLASS statement. In the preceding CREATE
OPCLASS statement, the abs_btree_ops operator class has one
support function.
STRATEGIES Clause
Strategy functions are functions that end users can invoke within an SQL
statement to operate on a data type. The query optimizer uses the strategy
functions to determine if a particular index can be used to process a query. If
an index exists on a column or user-defined function in a query, and the
qualifying operator in the query matches one of the strategy functions in the
Strategy Specification list, the optimizer considers using the index for the
query. For more information on query plans, see your Performance Guide.
When you create a new operator class, you specify the strategy functions for
the secondary access method in the STRATEGIES clause. The Strategy Specifi-
cation lists the name of each strategy function. List these functions in the
order that the secondary access method expects. For the specific order of
strategy operators for the default operator classes for a B-tree index and an
R-tree index, see Extending Informix Dynamic Server 2000.
Strategy Specification
strategy_function
,
( 2 input_type )
output_type
■ an input data type for each of the two input parameters of the strategy
function, in the order that the strategy function uses them.
■ optionally, one output data type for an output parameter of the
strategy function.
You can specify user-defined data types as well as built-in types. If you do not
specify the function signature, the database server assumes that each strategy
function takes two arguments of the same data type and returns a boolean
value.
Side-Effect Indexes
Side-effect data is additional data that a strategy function returns when
Dynamic Server executes a query containing the strategy function. For
example, an image DataBlade module might use a fuzzy index to search
image data. The index ranks the images according to how closely they match
the search criteria. The database server returns the rank value as the side-
effect data, along with the qualifying images.
SUPPORT Clause
Support functions are functions that the secondary access method uses inter-
nally to build and search the index. You specify the support functions for the
secondary access method in the SUPPORT clause of the CREATE OPCLASS
statement.
You must list the names of the support functions in the order that the
secondary access method expects. For the specific order of support operators
for the default operator classes for a B-tree index and an R-tree index, refer to
“Default Operator Classes” on page 2-197.
For each of the secondary access methods that Dynamic Server provides, it
provides a default operator class, as follows:
Related Information
Related statements: CREATE FUNCTION, CREATE INDEX, and DROP OPCLASS
For information on how to create and extend an operator class, see Extending
Informix Dynamic Server 2000.
For information about the R-tree index, see the Informix R-Tree Index User’s
Guide.
For information about the GLS aspects of the CREATE OPCLASS statement,
refer to the Informix Guide to GLS Functionality.
+
CREATE PROCEDURE
Use the CREATE PROCEDURE statement to create a user-defined procedure.
Tip: If you are trying to create a procedure from text that is in a separate file, use the
CREATE PROCEDURE FROM statement.
IDS In Dynamic Server, although you can use the CREATE PROCEDURE statement
to write and register an SPL routine that returns one or more values (that is,
an SPL function), Informix recommends that you use the CREATE FUNCTION
statement. To register an external function, you must use the CREATE
FUNCTION statement.
Syntax
Statement
SPL Block END PROCEDURE
p. 4-298
;
IDS External Routine
Reference
Ext p.4-202
END PROCEDURE
,
WITH LISTING IN 'pathname'
DOCUMENT Quoted String
p. 4-260
Usage
The entire length of a CREATE PROCEDURE statement must be less than
64 kilobytes. This length is the literal length of the CREATE PROCEDURE
statement, including blank space and tabs.
E/C In ESQL/C, you can use a CREATE PROCEDURE statement only within a
PREPARE statement. If you want to create a procedure for which the text is
known at compile time, you must use a CREATE PROCEDURE FROM
statement. ♦
You can write a UDR in SPL (SPL routine) or in an external language (external
routine) that the database server supports. Consequently, anywhere the term
UDR appears in the manual, its significance applies to both SPL routines and
external routines. Likewise, the term user-defined procedure applies to SPL
procedures and external procedures. Similarly, the term user-defined
function applies to SPL functions and external functions.
SPL In earlier Informix products, the term stored procedure was used for both SPL
procedures and SPL functions. In this manual, the term SPL routine replaces
the term stored procedure. When it is necessary to distinguish between an
SPL function and an SPL procedure, the manual does so. ♦
XPS Extended Parallel Server does not support external routines. However, the
term user-defined routine (UDR) encompasses both the terms SPL routine and
external routine. Therefore, wherever the term UDR appears it is applicable
to SPL routines. ♦
Ext Before you can create an external procedure, you must also have the Usage
privilege on the language in which you will write the procedure. For more
information, see “GRANT” on page 2-500. ♦
SPL By default, the Usage privilege on SPL is granted to PUBLIC. You must also
have at least the Resource privilege on a database to create an SPL procedure
within that database. ♦
If you do not use the DBA keyword, the UDR is known as an owner-privileged
UDR.
■ You create a UDR with the same name as a built-in routine (such as
equal()) to process a new user-defined data type.
■ You create type hierarchies, in which subtypes inherit data represen-
tation and UDRs from supertypes.
■ You create distinct types, which are data types that have the same
internal storage representation as an existing data type, but have
different names and cannot be compared to the source type without
casting. Distinct types inherit UDRs from their source types.
For a brief description of the routine signature that uniquely identifies each
UDR, see “Routine Overloading and Naming UDRs with a Routine
Signature” on page 4-52.
DOCUMENT Clause
The quoted string in the DOCUMENT clause provides a synopsis and
description of a UDR. The string is stored in the sysprocbody system catalog
table and is intended for the user of the UDR.
Anyone with access to the database can query the sysprocbody system
catalog table to obtain a description of one or all the UDRs stored in the
database.
For example, to find the description of the SPL procedure raise_prices, shown
in “SPL Procedures” on page 2-205, enter a query such as the following
example:
SELECT data FROM sysprocbody b, sysprocedures p
WHERE b.procid = p.procid
--join between the two catalog tables
AND p.procname = 'raise_prices'
-- look for procedure named raise_prices
AND b.datakey = 'D';-- want user document
A UDR or application program can query the system catalog tables to fetch
the DOCUMENT clause and display it for a user.
Ext You can use a DOCUMENT clause at the end of the CREATE PROCEDURE
statement, whether or not you use the END PROCEDURE keywords. ♦
If you do not use the WITH LISTING IN clause, the compiler does not generate
a list of warnings.
This listing file is created on the computer where the database resides.
UNIX If you specify a filename but not a directory, this listing file is created in your
home directory on the computer where the database resides. If you do not
have a home directory on this computer, the file is created in the root
directory (the directory named “/”). ♦
Windows If you specify a filename but not a directory, this listing file is created in your
current working directory if the database is on the local computer. Otherwise,
the default directory is %INFORMIXDIR%\bin. ♦
SPL procedures are parsed, optimized (as far as possible), and stored in the
system catalog tables in executable format. The body of an SPL procedure is
stored in the sysprocbody system catalog table. Other information about the
procedure is stored in other system catalog tables, including sysprocedures,
sysprocplan, and sysprocauth.
If you specify an optional clause after the parameter list, you must place a
semicolon after the clause that immediately precedes the Statement Block.
Example
The following example creates an SPL procedure:
CREATE PROCEDURE raise_prices ( per_cent INT )
UPDATE stock SET unit_price =
unit_price + (unit_price * (per_cent/100) );
END PROCEDURE
DOCUMENT "USAGE: EXECUTE PROCEDURE raise_prices( xxx )",
"xxx = percentage from 1 - 100 "
WITH LISTING IN '/tmp/warn_file'
1. Write a Java static method, which can use the JDBC functions to
interact with the database server.
2. Compile the Java source file and create a jar file (the shared-object file
for Java).
3. Execute the install_jar() procedure with the EXECUTE PROCEDURE
statement to install the jar file in the current database.
4. If the UDR uses user-defined types, create a mapping between SQL
data types and Java classes.
Use the setUDTExtName() procedure that is explained in
“EXECUTE PROCEDURE” on page 2-444.
5. Register the UDR with the CREATE PROCEDURE statement.
Rather than storing the body of an external routine directly in the database,
the database server stores only the pathname of the shared-object file that
contains the compiled version of the routine. When the database server
executes an external routine, the database server invokes the external object
code.
If an external routine returns a value, you must register it with the CREATE
FUNCTION statement.
The EXTERNAL NAME clause specifies that the Java implementation of the
showusers() procedure is a method called showusers(), which resides in the
admin Java class that resides in the admin_jar jar file.
However, in the case of a DBA-privileged UDR, the user who executes the
UDR, not the UDR owner, owns any database objects created by the UDR
unless another owner is specified for the database object within the UDR.
Related Information
Related statements: ALTER FUNCTION, ALTER PROCEDURE, ALTER
ROUTINE, CREATE FUNCTION, CREATE FUNCTION FROM, CREATE
PROCEDURE FROM, DROP FUNCTION, DROP PROCEDURE, DROP ROUTINE,
EXECUTE FUNCTION, EXECUTE PROCEDURE, GRANT, EXECUTE
PROCEDURE, PREPARE, REVOKE, and UPDATE STATISTICS
For a discussion of how to create and use SPL routines, see the Informix Guide
to SQL: Tutorial.
For a discussion of how to create and use external routines, see Extending
Informix Dynamic Server 2000.
For information about how to create C UDRs, see the DataBlade API
Programmer’s Manual.
XPS In Extended Parallel Server, use this statement to access any SPL routine.
Extended Parallel Server does not support the CREATE FUNCTION FROM
statement. ♦
Syntax
Usage
You cannot create a user-defined procedure directly in an ESQL/C program.
That is, the program cannot contain the CREATE PROCEDURE statement. The
following steps describe how you can use a user-defined procedure in an
ESQL/C program:
In the ESQL/C program, you can access the raise_prices() SPL procedure with
the following CREATE PROCEDURE FROM statement:
EXEC SQL create procedure from 'raise_pr.sql';
IDS If you are not sure whether the UDR in the file is a user-defined function or a
user-defined procedure, use the CREATE ROUTINE FROM statement. ♦
UNIX On UNIX, if you specify a simple filename instead of a full pathname in the
file parameter, the client application looks for the file in your home directory
on the computer where the database resides. If you do not have a home
directory on this computer, the default directory is the root directory. ♦
WIN NT On Windows NT, if you specify a filename but not a directory in the file
parameter, the client application looks for the file in your current working
directory if the database is on the local computer. Otherwise, the default
directory is %INFORMIXDIR%\bin. ♦
Important: The ESQL/C preprocessor does not process the contents of the file that you
specify. It just sends the contents to the database server for execution. Therefore, there
is no syntactic check that the file that you specify in CREATE PROCEDURE FROM
actually contains a CREATE PROCEDURE statement. However, to improve
readability of the code, Informix recommends that you match these two statements.
Related Information
Related statements: CREATE PROCEDURE, CREATE FUNCTION FROM, and
CREATE ROUTINE FROM
+ CREATE ROLE
IDS
Use the CREATE ROLE statement to create a new role.
Syntax
Usage
The database administrator (DBA) uses the CREATE ROLE statement to create
a new role. A role can be considered as a classification, with privileges on
database objects granted to the role. The DBA can assign the privileges of a
related work task, such as engineer, to a role and then grant that role to users,
instead of granting the same set of privileges to every user.
After a role is created, the DBA can use the GRANT statement to grant the role
to users or to other roles. When a role is granted to a user, the user must use
the SET ROLE statement to enable the role. Only then can the user use the
privileges of the role.
The CREATE ROLE statement, when used with the GRANT and SET ROLE
statements, allows a DBA to create one set of privileges for a role and then
grant the role to many users, instead of granting the same set of privileges to
many users.
A role exists until either the DBA or a user to whom the role was granted with
the WITH GRANT OPTION uses the DROP ROLE statement to drop the role.
Related Information
Related statements: DROP ROLE, GRANT, REVOKE, and SET ROLE
For a discussion of how to use roles, see the Informix Guide to Database Design
and Implementation.
Syntax
Usage
An Informix ESQL/C program cannot directly define a UDR. That is, it cannot
contain the CREATE FUNCTION or CREATE PROCEDURE statement. The
following steps describe how you can use a UDR in an ESQL/C program:
The filename that you provide is relative. If you provide a simple filename,
the client application looks for the file in the current directory.
If you do not know at compile time whether the UDR in the file is a function
or a procedure, use the CREATE ROUTINE FROM statement in the ESQL/C
program. However, if you do know if the UDR is a function or procedure,
Informix recommends that you use the matching statement to access the
source file:
Related Information
Related statements: CREATE FUNCTION, CREATE FUNCTION FROM, CREATE
PROCEDURE, and CREATE PROCEDURE FROM
Syntax
,
CREATE ROW TYPE row_type ( Field Definition )
p. 2-220
UNDER supertype
Usage
The CREATE ROW TYPE statement creates a named-row type. You can assign
a named-row type to a table or view to create a typed table or typed view. You
can also assign a named-row type to a column. Although you can assign a
row type to a table to define the structure of the table, row types are not the
same as table rows. Table rows consist of one or more columns; row types
consist of one or more fields, which are defined using the Field Definition
syntax.
You can use a named-row type anywhere you can use any other data type.
Named-row types are strongly typed. Any two named-row types are not
considered equivalent even if they are structurally equivalent. Row types
without names are called unnamed-row types. Any two unnamed-row types
are considered equivalent if they are structurally equivalent. For more infor-
mation on unnamed-row types, see “Unnamed Row Types” on page 4-68.
To find out what privileges exist on a particular type, check the sysxtdtypes
system catalog table for the owner name and the sysxtdtypeauth system
catalog table for additional type privileges that might have been granted. For
more information on system catalog tables, see the Informix Guide to SQL:
Reference.
For information about the RESOURCE, UNDER, and ALL privileges, see
GRANT.
Privileges on a typed table (a table that is assigned a named-row type) are the
same as privileges on any table. For more information, see “Table-Level Privi-
leges” on page 2-505.
To find out what privileges you have on a particular table, check the
systabauth system catalog table.
To find out what privileges you have on a particular column, check the
syscolauth system catalog table. This table is described in the Informix Guide
to SQL: Reference.
When you create a named-row type as a subtype, the subtype inherits all
fields of the supertype. In addition, you can add new fields to the subtype
that you create. The new fields are specific to the subtype alone.
You cannot substitute a row type in an inheritance hierarchy for its supertype
or its subtype. For example, suppose you define a type hierarchy in which
person_t is the supertype and employee_t is the subtype. If a column is of
type person_t, the column can only contain person_t data. It cannot contain
employee_t data. Likewise, if a column is of type employee_t, the column
can only contain employee_t data. It cannot contain person_t data.
Creating a Subtype
In most cases, you add new fields when you create a named-row type as a
subtype of another named-row type (supertype). To create the fields of a
named-row type, you use the field definition clause (see “Field Definition”
on page 2-220).
When you create a subtype, you must use the UNDER keyword to associate
the supertype with the named-row type that you want to create. The
following statement creates the employee_t type under the person_t type:
CREATE ROW TYPE employee_t
(salary NUMERIC(10,2), bonus NUMERIC(10,2))
UNDER person_t;
The employee_t type inherits all the fields of person_t and has two
additional fields: salary and bonus. However, the person_t type is not
altered.
Type Hierarchies
When you create a subtype, you create a type hierarchy. In a type hierarchy,
each subtype that you create inherits its properties from a single supertype.
If you create a named-row type customer_t under person_t, customer_t
inherits all the fields of person_t. If you create another named-row type,
salesrep_t under customer_t, salesrep_t inherits all the fields of customer_t.
More specifically, salesrep_t inherits all the fields that customer_t inherited
from person_t as well as all the fields defined specifically for customer_t. For
a full discussion of type inheritance, refer to the Informix Guide to SQL:
Tutorial.
Important: When you create a subtype, do not redefine fields that the subtype
inherited for its supertype. If you attempt to redefine these fields, the database server
returns an error.
Field Definition
Use the field definition portion of CREATE ROW TYPE to define a new field in
a named-row type.
field data_type
NOT NULL
The NOT NULL constraint that you specify on a field of a named-row type
also applies to corresponding columns of a table when the named-row type
is used to create a typed table.
You cannot create a row type that has a BYTE or TEXT value that is stored in
a separate storage space. That is, you cannot use the IN clause to specify the
storage location. For example, the following example produces an error:
CREATE ROW TYPE row1 (field1 byte IN blobspace1) --INVALID
CODE
Across a table hierarchy, you can use only one SERIAL and one SERIAL8. That
is, if a supertable table contains a SERIAL column, no subtable can contain a
SERIAL column. However, a subtable can have a SERIAL8 column (as long as
no other subtables contain a SERIAL8 column). Consequently, when you
create the named-row types on which the table hierarchy is to be based, they
can contain at most one SERIAL and one SERIAL8 field among them.
You cannot set the starting serial value with CREATE ROW TYPE.
To modify the value for a serial field, you must use either the MODIFY clause
of the ALTER TABLE statement or the INSERT statement to insert a value that
is larger than the current maximum (or default) serial value.
When you use serial fields in row types, you create performance implications
across a table hierarchy. When you insert data into a subtable whose
supertable (or its supertable) contains the serial counter, the database server
must also open the supertable, update the serial value, and close the
supertable, thus adding extra overhead.
Related Information
Related statements: DROP ROW TYPE, CREATE TABLE, CREATE CAST, GRANT,
and REVOKE
DB CREATE SCHEMA
SQLE
Use the CREATE SCHEMA statement to issue a block of CREATE and GRANT
statements as a unit. The CREATE SCHEMA statement allows you to specify
an owner of your choice for all database objects that the CREATE SCHEMA
statement creates.
Syntax
GRANT Statement
p. 2-500
Usage
You cannot issue the CREATE SCHEMA statement until you create the affected
database.
Users with the Resource privilege can create a schema for themselves. In this
case, user must be the name of the person with the Resource privilege who is
running the CREATE SCHEMA statement. Anyone with the DBA privilege can
also create a schema for someone else. In this case, user can identify a user
other than the person who is running the CREATE SCHEMA statement.
You can put CREATE and GRANT statements in any logical order within the
statement, as the following example shows. Statements are considered part
of the CREATE SCHEMA statement until a semicolon or an end-of-file symbol
is reached.
CREATE SCHEMA AUTHORIZATION sarah
CREATE TABLE mytable (mytime DATE, mytext TEXT)
GRANT SELECT, UPDATE, DELETE ON mytable TO rick
CREATE VIEW myview AS
SELECT * FROM mytable WHERE mytime > '12/31/1997'
CREATE INDEX idxtime ON mytable (mytime);
Related Information
Related statements: CREATE INDEX, CREATE SYNONYM, CREATE TABLE,
CREATE VIEW, and GRANT
For a discussion of how to create a database, see the Informix Guide to Database
Design and Implementation.
+
CREATE SYNONYM
Use the CREATE SYNONYM statement to provide an alternative name for a
table or view.
Syntax
PRIVATE
Usage
Users have the same privileges for a synonym that they have for the table to
which the synonym applies.
The synonym name must be unique; that is, the synonym name cannot be the
same as another database object, such as a table, view, or temporary table.
Once a synonym is created, it persists until the owner executes the DROP
SYNONYM statement. This property distinguishes a synonym from an alias
that you can use in the FROM clause of a SELECT statement. The alias persists
for the existence of the SELECT statement. If a synonym refers to a table or
view in the same database, the synonym is automatically dropped if you
drop the referenced table or view.
You can create a synonym for any table or view in any database on your
database server. Use the owner. convention if the table is part of an
ANSI-compliant database. The following example shows a synonym for a
table outside the current database. It assumes that you are working on the
same database server that contains the payables database.
CREATE SYNONYM mysum FOR payables:jean.summary
The following example shows how to create a synonym for a database object
that is not in the current database:
CREATE SYNONYM mysum FOR payables@phoenix:jean.summary
The identifier mysum now refers to the table jean.summary, which is in the
payables database on the phoenix database server. Note that if the summary
table is dropped from the payables database, the mysum synonym is left
intact. Subsequent attempts to use mysum return the error Table not
found.
IDS Restrictions
You cannot create synonyms on the following types of remote tables:
ANSI In an ANSI-compliant database, synonyms are always private. If you use the
PUBLIC or PRIVATE keywords, you receive a syntax error. ♦
If you use the PRIVATE keyword, the synonym can be used only by the owner
of the synonym or if the name of the owner is specified explicitly with the
synonym. More than one private synonym with the same name can exist in
the same database. However, a different user must own each synonym with
that name.
You can own only one synonym with a given name; you cannot create both
private and public synonyms with the same name. For example, the
following code generates an error:
CREATE SYNONYM our_custs FOR customer;
CREATE PRIVATE SYNONYM our_custs FOR cust_calls;-- ERROR!!!
If you use DROP SYNONYM with a synonym, and multiple synonyms exist
with the same name, the private synonym is dropped. If you issue the DROP
SYNONYM statement again, the public synonym is dropped.
Chaining Synonyms
If you create a synonym for a table that is not in the current database, and this
table is dropped, the synonym stays in place. You can create a new synonym
for the dropped table, with the name of the dropped table as the synonym
name, which points to another external or remote table. In this way, you can
move a table to a new location and chain synonyms together so that the
original synonyms remain valid. (You can chain as many as 16 synonyms in
this manner.)
The following steps chain two synonyms together for the customer table,
which will ultimately reside on the zoo database server (the CREATE TABLE
statements are not complete):
The synonym cust on the accntg database server now points to the customer
table on the zoo database server.
The synonym cust on the accntg database server now points to a new version
of the customer table on the training database server.
Related Information
Related statement: DROP SYNONYM
CREATE TABLE
Use the CREATE TABLE statement to create a new table in the current
database, place data-integrity constraints on columns, designate where the
table should be stored, indicate the size of its initial and subsequent extents,
and specify how to lock it.
You can use the CREATE TABLE statement to create relational-database tables
or typed tables (object-relational tables). For information on how to create
temporary tables, see “CREATE Temporary TABLE” on page 2-286.
Syntax
OPERATIONAL
STANDARD
Table Definition
,
+ , Multiple-Column
Constraint Format
IDS p. 2-250
OF TYPE Clause
p. 2-280
Usage
When you create a table, the table and columns within that table must have
unique names and every table column must have a data type associated with
it.
E/C In ESQL/C, using the CREATE TABLE statement generates warnings if you use
the -ansi flag or set DBANSIWARN. ♦
Option Purpose
Column Definition
Use the column definition portion of CREATE TABLE to list the name, data
type, default values, and constraints of a single column.
When you name a column, as with any SQL identifier, you can use a reserved
word, but syntactic ambiguities can occur. For more information on reserved
words for Dynamic Server, see Appendix A, “Reserved Words for Dynamic
Server.” For more information on reserved words for Extended Parallel
Server, see Appendix B, “Reserved Words for Extended Parallel Server.” For
more information on the ambiguities that can occur, see “Using Keywords as
Column Names” on page 4-212.
IDS If you define a column of a table to be of a named-row type, the table does not
adopt any constraints of the named row. ♦
DEFAULT Clause
Use the DEFAULT clause to specify the default value that the database server
should insert in a column when an explicit value for the column is not
specified.
DEFAULT literal
NULL
USER
+
TODAY
SITENAME
DBSERVERNAME
If you do not indicate a default value for a column, the default is null unless
you place a not-null constraint on the column. In that case, no default value
exists for the column.
Format of
For Columns of Data Type Default Value Syntax Restrictions
Date literals must be of the format that the DBDATE environment variable
specifies. If DBDATE is not set, the date literals must be of the mm/dd/yyyy
format.
If you specify NULL as the default value for a column, you cannot specify a
not-null constraint as part of the column definition.
You cannot designate null as the default value for a column that is part of a
primary key.
If the column is BYTE or TEXT data type, null is the only default value that you
can designate.
IDS If the column is BLOB or CLOB data type, null is the only default value that
you can designate.
CURRENT DATETIME column with matching qualifier Byte value that accommodates the
largest DATETIME value for your
locale.
Informix recommends a column size because if the column length is too small
to store the default value during INSERT and ALTER TABLE operations, the
database server returns an error.
IDS You cannot designate a built-in function (that is, CURRENT, USER, TODAY,
SITENAME, or DBSERVERNAME) as the default value for a column that holds
opaque or distinct data types. ♦
UNIQUE
NOT +
DISTINCT +
+
PRIMARY KEY Constraint
Definition
Constraint REFERENCES p. 2-247
Definition Clause
p. 2-247 p. 2-241
CHECK
Clause
p. 2-245
The constraints used in this example are defined in the following sections.
The following example creates the newitems table. In newitems, the column
manucode does not have a default value nor does it allow nulls.
CREATE TABLE newitems (
newitem_num INTEGER,
manucode CHAR(3) NOT NULL,
promotype INTEGER,
descrip CHAR(20))
Relationship Between the Default Value and the NOT NULL Constraint
If you do not indicate a default value for a column, the default is null unless
you place a NOT NULL constraint on the column. In this case, no default value
exists for the column.
You cannot specify NULL as the default value for a column and also specify
the NOT NULL constraint.
REFERENCES Clause
Use the REFERENCES clause to establish a referential relationship:
■ within a table (that is, between two columns of the same table).
■ between two tables (in other words, create a foreign key).
REFERENCES table
, +
( column ) ON DELETE CASCADE
The referencing column (the column being defined) is the column or set of
columns that refers to the referenced column or set of columns. The refer-
encing column or set of columns can contain null and duplicate values.
However, the values in the referenced column or set of columns must be
unique.
When you use the REFERENCES clause, you must observe the following
restrictions:
XPS ■ When you use the multiple-column constraint format, the maximum
number of columns in the REFERENCES clause is 16, and the total
length of the columns cannot exceed 255 bytes. ♦
IDS ■ When you use the multiple-column constraint format, the maximum
number of columns in the REFERENCES clause is 16, and the total
length of the columns cannot exceed 390 bytes.
■ You cannot place a referential constraint on a BLOB or CLOB
column. ♦
When you use the single-column constraint format, you do not explicitly
specify the ref_num column as a foreign key. To use the FOREIGN KEY
keyword, use the “Multiple-Column Constraint Format” on page 2-250.
If you specify this option, later when you delete a row in the parent table, the
database server also deletes any rows associated with that row (foreign keys)
in a child table. The principal advantage to the cascading-deletes feature is
that it allows you to reduce the quantity of SQL statements you need to
perform delete actions.
Because the ON DELETE CASCADE option is specified for the child table,
when an item from the all_candy table is deleted, the delete cascades to the
corresponding rows of the hard_candy table.
For information about syntax restrictions and locking implications when you
delete rows from tables that have cascading deletes, see “Considerations
When Tables Have Cascading Deletes” on page 2-375.
CHECK Clause
Use the CHECK clause to designate conditions that must be met before data
can be assigned to a column during an INSERT or UPDATE statement.
CHECK ( Condition )
p. 4-27
During an insert or update, if a row evaluates to false for any check constraint
defined on a table, the database server returns an error. The database server
does not return an error if a row evaluates to null for a check constraint. In
some cases, you might wish to use both a check constraint and a NOT NULL
constraint.
You use search conditions to define check constraints. The search condition
cannot contain the following items: subqueries, aggregates, host variables,
rowids, or user-defined routines. In addition, the search condition cannot
contain the following built-in functions: CURRENT, USER, SITENAME,
DBSERVERNAME, or TODAY.
When you specify a date value in a search condition, make sure you specify 4 digits
instead of 2 digits for the year. When you specify a 4-digit year, the DBCENTURY
environment variable has no effect on the distribution scheme. When you specify a 2-
digit year, the DBCENTURY environment variable can affect the distribution scheme
and can produce unpredictable results. See the “Informix Guide to SQL: Reference”
for more information on the DBCENTURY environment variable.
With a BYTE or TEXT column, you can check for null or not-null values. This
constraint is the only constraint allowed on a BYTE or TEXT columns.
IDS With a BLOB or CLOB column, you can check for null or not-null values. This
constraint is the only constraint allowed on a BLOB or CLOB columns.
Example
The following example creates the my_accounts table which has two
columns with check constraints:
CREATE TABLE my_accounts (
chk_id SERIAL PRIMARY KEY,
acct1 MONEY CHECK (acct1 BETWEEN 0 AND 99999),
acct2 MONEY CHECK (acct2 BETWEEN 0 AND 99999))
Both acct1 and acct2 are columns of MONEY data type whose values must be
between 0 and 99999.
If, however, you want to test that acct1 has a larger balance than acct2, you
cannot use the single-column constraint format. To create a constraint that
checks values in more than one column, you must use the “Multiple-Column
Constraint Format” on page 2-250.
Constraint Definition
Use the constraint definition portion of CREATE TABLE for the following
purposes:
IDS
CONSTRAINT constraint
DISABLED
ENABLED
FILTERING
WITHOUT ERROR
WITH ERROR
If you wish, you can specify a meaningful name for the constraint. The name
of a constraint must be unique within the database.
IDS In addition, you specify a constraint name when you change the mode of
constraint with the SET Database Object Mode statement or the SET Trans-
action Mode statement. ♦
ANSI When you create a constraint of any type, the owner.constraint (the combi-
nation of the owner name and constraint name) must be unique within the
database. ♦
IDS The system catalog table that holds information about indexes is the
sysindices table. ♦
If the generated name conflicts with an existing identifier, the database server
returns an error, and you must then supply a constraint name.
The index name in sysindexes (or sysindices) is created with the following
format:
[space]<tabid>_<constraintid>
For example, the index name might be something like: " 111_14" (quotation
marks are used to show the space).
Mode Purpose
DISABLED Does not enforce the constraint during insert, delete, and update
operations.
If you choose filtering mode, you can specify the WITHOUT ERROR or WITH
ERROR options. The following list explains these options.
For how to set the constraint mode after the table exists, see “SET Database
Object Mode” on page 2-700. For information about where the database
server stores data that violates a constraint set to filtering, see “START
VIOLATIONS TABLE” on page 2-778.
UNIQUE ( column )
+ +
DISTINCT
Constraint
PRIMARY KEY Definition
p. 2-247
,
) REFERENCES
FOREIGN KEY ( column Clause
p. 2-241
CHECK Clause
p. 2-245
When you use the multiple-column constraint format, you can perform the
following tasks:
When you use this format, you can create composite primary and foreign
keys. You can also define check constraints that involve comparing data in
different columns.
A foreign key references a unique or primary key in a table. For every entry
in the foreign-key columns, a matching entry must exist in the unique or
primary-key columns if all foreign-key columns contain non-null values.
In this example, the acct1 column must be greater than the acct2 column, or
the insert or update fails.
The following example creates two tables. The first table has a composite key
that acts as a primary key, and the second table has a composite key that acts
as a foreign key.
CREATE TABLE accounts (
acc_num INTEGER,
acc_type INTEGER,
acc_descr CHAR(20),
PRIMARY KEY (acc_num, acc_type))
In this example, the foreign key of the sub_accounts table, ref_num and
ref_type, references the composite key, acc_num and acc_type, in the
accounts table. If, during an insert or update, you tried to insert a row into
the sub_accounts table whose value for ref_num and ref_type did not
exactly correspond to the values for acc_num and acc_type in an existing row
in the accounts table, the database server would return an error.
Because of the default behavior of the database server, when you create the
foreign key reference, you do not have to reference the composite key
columns (acc_num and acc_type) explicitly.
You can rewrite the references section of the previous example as follows:
...
FOREIGN KEY (ref_num, ref_type) REFERENCES accounts
...
Options
The CREATE TABLE options let you specify storage locations, extent size,
locking modes, and user-defined access methods.
IDS +
LOCK MODE USING
Options Access-Method
WITH CRCOLS Storage p. 2-278 Clause
Options p. 2-279
p. 2-256
For most database operations, the cdrserver and cdrtime columns are
hidden. For example, if you include the WITH CRCOLS keywords when you
create a table, the cdrserver and cdrtime columns:
To view the contents of cdrserver and cdrtime, explicitly name the columns
in a SELECT statement, as the following example shows:
SELECT cdrserver, cdrtime from tablename
For more information about using this option, refer to the Guide to Informix
Enterprise Replication.
Storage Options
Use the storage option portion of CREATE TABLE to specify the storage space
and the size of the extents for the table.
IDS
IN dbspace EXTENT SIZE
PUT Clause Options
p. 2-273 p. 2-276
XPS dbslice
IDS
extspace
FRAGMENT BY
Clause
p. 2-259
You can specify a dbspace for the table that is different from the storage
location specified for the database, or fragment the table into several
dbspaces. If you do not specify the IN clause or a fragmentation scheme, the
database server stores the table in the dbspace where the current database
resides.
IDS You can use the PUT clause to specify storage options for smart large objects.
For more information, see “PUT Clause” on page 2-273.
Tip: If your table has columns that contain simple large objects (TEXT or BYTE), you
can specify a separate blobspace for each object. For information on storing simple
large objects, refer to “Large-Object Data Types” on page 4-62. ♦
For more information about how to store and manage your tables in separate
dbspaces, see your Administrator’s Guide.
To fragment a table across a dbslice, you can use either the IN dbslice syntax
or the FRAGMENT BY ROUND ROBIN IN dbslice syntax.
FRAGMENT BY Clause
Use the FRAGMENT BY clause to create fragmented tables and specify the
distribution scheme.
REMAINDER
XPS
, ,
IN dbslice
,
HYBRID ( column )
,
EXPRESSION expression IN dbslice , expression IN dbslice
REMAINDER
dbspace dbspace
, ,
( dbspace ) ( dbspace )
When you fragment a table, the IN keyword introduces the storage space
where a table fragment is to be stored.
You cannot use the WITH ROWIDS clause with typed tables.
XPS If you are using Extended Parallel Server, you can specify the name of a
dbslice to fragment a table across a group of dbspaces that share the same
naming convention. For a syntax alternative to FRAGMENT BY ROUND ROBIN
IN dbslice that achieves the same results, see “Storing Data in a dbslice” on
page 2-258. ♦
IDS Use the PUT clause to specify round-robin fragmentation for smart large
objects. For more information, see “PUT Clause” on page 2-273. ♦
Fragmenting by EXPRESSION
In an expression-based distribution scheme, each fragment expression in a rule
specifies a storage space. Each fragment expression in the rule isolates data
and aids the database server in searching for rows. Specify one of the
following rules:
■ Range rule
A range rule specifies fragment expressions that use a range to
specify which rows are placed in a fragment, as the following
example shows:
...
FRAGMENT BY EXPRESSION
c1 < 100 IN dbsp1,
c1 >= 100 AND c1 < 200 IN dbsp2,
c1 >= 200 IN dbsp3
■ Arbitrary rule
An arbitrary rule specifies fragment expressions based on a
predefined SQL expression that typically uses OR clauses to group
data, as the following example shows:
...
FRAGMENT BY EXPRESSION
zip_num = 95228 OR zip_num = 95443 IN dbsp2,
zip_num = 91120 OR zip_num = 92310 IN dbsp4,
REMAINDER IN dbsp5
Warning: When you specify a date value in a fragment expression, make sure you
specify 4 digits instead of 2 digits for the year. When you specify a 4-digit year, the
DBCENTURY environment variable has no effect on the distribution scheme. When
you specify a 2-digit year, the DBCENTURY environment variable can affect the
distribution scheme and can produce unpredictable results. See the “Informix Guide
to SQL: Reference” for more information on the DBCENTURY environment variable.
If you do not specify a remainder and a row is inserted or updated such that
it no longer belongs to any dbspace, the database server returns an error.
This example uses eight coservers with one dbspace defined on each
coserver.
You can also specify a dbslice. When you specify a dbslice, the database server
fragments the table across the dbspaces that make up the dbslice.
When you specify a dbslice, the database server fragments the table across
the dbspaces that make up the dbslice. Similarly, if you specify a dbspacelist,
the database server fragments the table across the dbspaces specified in that
list.
For example, the following table, my_hybrid, distributes rows based on two
columns of the table. The value of col1 determines in which dbslice the row
belongs. The hash value of col2 determines in which dbspace (within the
previously determined dbslice) to insert into.
CREATE TABLE my_hybrid
(col1 INT,
col2 DATE,
col3 CHAR(10)
)
HYBRID (col2)
EXPRESSION
col1 < 100 IN dbslice1,
col1 >= 100 and col1 < 200 IN dbslice2,
REMAINDER IN dbslice3
,
Range
RANGE ( column Definition ) IN dbspace
p. 2-268
dbslice
REMAINDER IN dbspace
Range Range IN
HYBRID ( RANGE ( column ) ) RANGE ( column Definition ) Clause
p. 2-268 p. 2-269
Range Definition
Use the range definition to specify the minimum and maximum values of the
entire range.
max_val
The database server uses the minimum and maximum values to determine
the exact range of values to allocate for each storage space.
Range IN Clause
Use the IN clause to specify the storage spaces across which to distribute the
data.
IN dbslice
, REMAINDER IN dbslice
( dbspace ) ,
( dbspace )
When you use a range fragmentation method, the number of integral values
between the minimum and maximum specified values must be equal to or
greater than the number of storage spaces specified so that the database
server can allocate non-overlapping contiguous ranges across the dbspaces.
For example, the following code returns an error because the allocations for
the range cannot be distributed across all specified dbspaces:
CREATE TABLE Tab1 (Col1 INT...)
FRAGMENT BY RANGE (Col1 MIN 5 MAX 7)
IN db1, db2, db3, db4, db5, db6 -- code returns an
error
The error for this example occurs because the specified range contains three
values (5, 6, and 7), but six dbspaces are specified; three values cannot be
distributed across six dbspaces.
If you do not specify a remainder and a row is inserted or updated such that
it no longer belongs to any storage space, the database server returns an error.
Restrictions
If you fragment a table with range fragmentation, you cannot perform the
following operations on it once it is created:
Examples
The following examples illustrate range fragmentation in its simple and
hybrid forms.
In this example, the database server fragments the table according to the
following allocations.
The previous table shows allocations that can also be made with an
expression-based fragmentation scheme:
... FRAGMENT BY EXPRESSION
Col1 >= 100 AND Col1 < 125 IN db1
Col1 >= 125 AND Col1 < 150 IN db2
Col1 >= 150 AND Col1 < 175 IN db3
Col1 >= 175 AND Col1 < 200 IN db4
Row-Major-Range Allocation
The following example demonstrates the syntax for row-major-range
allocation, a hybrid-range fragmentation strategy:
CREATE TABLE tab3 (col3 INT, colx char (5))
FRAGMENT BY HYBRID
( RANGE (col3) )
RANGE (col3 MIN 100 MAX 220)
IN dbsl1, dbsl2, dbsl3
Independent-Range Allocation
The following example demonstrates the syntax for an independent-range
allocation, a hybrid-range fragmentation strategy:
CREATE TABLE tab4 (col4 INT, colx char (5), col5 INT)
FRAGMENT BY HYBRID
( RANGE (col4 MIN 100 MAX 200) )
RANGE (col5 MIN 500 MAX 800)
IN dbsl1, dbsl2, dbsl3
In this type of range fragmentation, the two columns are independent, and
therefore the range allocations are independent. The range allocation for a
dbspace on both columns is the conjunctive combination of the range
allocation on each of the two independent columns. This type of fragmen-
tation does not provide subdivisions within either column.
With this type of fragmentation, a query that specifies values for both
columns (such as, WHERE col4 = 128 and col5 = 650) uniquely identifies
the dbspace at the intersection of the two dbslices identified by the columns
independently.
,
,
PUT column IN ( sbspace )
,
( )
EXTENT SIZE kbytes
LOG
NO LOG
HIGH INTEG
When you specify more than one sbspace, the database server distributes the
smart large objects in a round-robin distribution scheme so that the number
of smart large objects in each space is approximately equal. The fragmen-
tation scheme is stored in the syscolattribs system catalog table.
When you fragment smart large objects across different sbspaces you can
work with smaller sbspaces. If you limit the size of an sbspace, backup and
archive operations can perform more quickly. For an example that uses the
PUT clause, see “Storage Options” on page 2-256.
Important: The PUT clause does not affect the storage of simple-large-object data
types (BYTE and TEXT). For information on how to store BYTE and TEXT data, see
“Large-Object Data Types” on page 4-62.
Option Purpose
HIGH INTEG Produces user-data pages that contain a page header and a
page trailer to detect incomplete writes and data
corruption.
This is the default data-integrity behavior.
NO KEEP ACCESS Do not record the system time at which the corresponding
TIME smart large object was last read or written.
This option provides better performance than the KEEP
ACCESS TIME option.
This option is the default tracking behavior.
If a user-defined type or complex type contains more than one large object,
the specified large-object storage options apply to all large objects in the type
unless the storage options are overridden when the large object is created.
Use the NO LOG option to turn off logging. If you use NO LOG, you can
restore the smart-large-object metadata later to a state in which no structural
inconsistencies exist. In most cases, no transaction inconsistencies will exist
either, but that result is not guaranteed.
The following example specifies a first extent of 20 kilobytes and allows the
rest of the extents to use the default size:
CREATE TABLE emp_info
(
f_name CHAR(20),
l_name CHAR(20),
position CHAR(20),
start_date DATETIME YEAR TO DAY,
comments VARCHAR(255)
)
EXTENT SIZE 20
ROW
XPS TABLE
Locking-
Granularity Option Purpose
ROW Obtains and releases one lock per row
Row-level locking provides the highest level of concurrency.
However, if you are using many rows at one time, the lock-
management overhead can become significant. You can also
exceed the maximum number of locks available, depending on
the configuration of your database server.
PAGE Obtains and releases one lock on a whole page of rows
This is the default locking granularity.
Page-level locking is especially useful when you know that the
rows are grouped into pages in the same order that you are
using to process all the rows. For example, if you are processing
the contents of a table in the same order as its cluster index,
page locking is appropriate.
TABLE Places a lock on the entire table
(XPS only) This type of lock reduces update concurrency compared to row
and page locks. A table lock reduces the lock-management
overhead for the table
With table locking, multiple read-only transactions can still
access the table.
You can change the lock mode of an existing table with the ALTER TABLE
statement.
You store and manage a virtual table either outside of the database server in
an extspace or inside the database server in an sbspace. (See “Storage
Options” on page 2-256.) You can access a virtual table with SQL statements.
Access to a virtual table requires a user-defined primary access method.
,
Specific
USING Name
p. 4-296 ,
( config_ keyword )
= ' config_value '
For example, if an access method called textfile exists, you can specify that
access method with the following syntax:
create table mybook
(... )
IN myextspace
USING textfile (delimiter=’:’)
, Multiple-Column
Constraint Format
p. 2-250 UNDER supertable
When you create a typed table, the columns of the table are not named in the
CREATE TABLE statement. Instead, the columns are specified when you create
the row type. The columns of a typed table correspond to the fields of the
named-row type. You cannot add additional columns to a typed table.
If a table is assigned the type student_t, the table is a typed table whose
columns are of the same name and data type (and in the same order) as the
fields of the type student_t.
For more information about row types, refer to the CREATE ROW TYPE
statement on page 1-194.
Continuing the example shown in “OF TYPE Clause” on page 2-280, the
following statements create a typed table, grad_students, that inherits all of
the columns of the students table. In addition, the grad_students table has
columns for adviser and field_of_study that correspond to their respective
fields in the grad_student_t row type:
CREATE ROW TYPE grad_student_t
(adviser CHAR(25),
field_of_study CHAR(40))
UNDER student_t;
For more information about inheritance, refer to the Informix Guide to SQL:
Tutorial.
Privileges on Tables
The privileges on a table describe both who can access the information in the
table and who can create new tables. For more information about privileges,
see “GRANT” on page 2-500.
When you create a table with a referential constraint, the database server
creates an internal, nonunique, ascending index for each column specified in
the referential constraint.
The database server stores this internal index in the same location that the
table uses. If you fragment the table, the database server stores the index
fragments in the same dbspaces as the table fragments or in some cases, the
database dbspace.
Related Information
Related statements: ALTER TABLE, CREATE INDEX, CREATE DATABASE,
CREATE EXTERNAL TABLE, CREATE ROW TYPE, CREATE Temporary TABLE,
DROP TABLE, SET Database Object Mode, and SET Transaction Mode
For information about the system catalog tables that store information about
objects in the database, see the Informix Guide to SQL: Reference.
For information about the syschunks table (in the sysmaster database) that
contains information about the location of smart large objects, see your
Administrator’s Reference.
Syntax
XPS
SCRATCH
Table Definition
,
Column Definition Options
( p. 2-288 ) p. 2-292
,
Multiple-Column
, Constraint Format WITH NO LOG
p. 2-290
Usage
If you have the Connect privilege on a database, you can create a temporary
table. However, you are the only user who can see the temporary table.
E/C The CREATE TABLE statement generates warnings if you use the -ansi flag or
set the DBANSIWARN environment variable. ♦
IDS If your database does not have logging, the table behaves in the same way as
a table that uses the WITH NO LOG option. ♦
The name must be different from existing table, view, or synonym names in
the current database; however, it need not be different from other temporary
table names used by other users.
Use the WITH NO LOG option to reduce the overhead of transaction logging.
If you use the WITH NO LOG option, operations on the temporary table are
not included in the transaction-log operations.
You must use the WITH NO LOG option on temporary tables you create in
temporary dbspaces.
IDS If you use the WITH NO LOG option in a database that does not use logging,
the WITH NO LOG option is ignored. ♦
Once you turn off logging on a temporary table, you cannot turn it back on;
a temporary table is, therefore, always logged or never logged.
Column Definition
Use the column definition portion of CREATE Temporary TABLE to list the
name, data type, default value, and constraints of a single column.
UNIQUE
NOT NULL +
DISTINCT
PRIMARY KEY
CHECK Clause
p. 2-245
The following table indicates where you can find detailed discussions of
specific constraints.
UNIQUE ( column )
+
DISTINCT
PRIMARY KEY
CHECK Clause
p. 2-245
The following table indicates where you can find detailed discussions of
specific constraints.
Options
The CREATE TABLE options let you specify storage locations, locking modes,
and user-defined access methods
You cannot specify initial and next extents for a temporary table. Extents for
a temporary table are always eight pages.
IDS +
Storage LOCK MODE USING
Options Options Access-Method
WITH CRCOLS p. 2-292 p. 2-278 Clause
p. 2-279
Storage Options
Use the storage-option portion of the CREATE Temporary Table statement to
specify the distribution scheme for the table.
XPS If you are using Extended Parallel Server, you can fragment a temporary
table across multiple dbspaces that different coservers manage. ♦
IDS
IN dbspace
PUT Clause
p. 2-273
XPS dbslice
IDS extspace
FRAGMENT BY
Clause
p. 2-259
For temporary tables for which you do not specify an explicit distribution
scheme, each temporary table that you create round-robins to a dbspace
specified by the DBSPACETEMP environment variable or the DBSPACETEMP
configuration parameter if the environment variable is not set. For example,
if you create three temporary tables, the first one goes into the dbspace called
tempspc1, the second one goes into tempspc2, and the third one goes into
tempspc3.
This behavior also applies temporary tables that you create with
SELECT...INTO TEMP or SELECT...INTO SCRATCH.
Example
The following example shows how to insert data into a temporary table
called result_tmp to output to a file the results of a user-defined function
(f_one) that returns multiple rows.
CREATE TEMP TABLE result_tmp( ... );
INSERT INTO result_tmp EXECUTE FUNCTION f_one();
UNLOAD TO 'file' SELECT * FROM temp1;
XPS In Extended Parallel Server, to recreate this example use the CREATE
PROCEDURE statement instead of the CREATE FUNCTION statement. ♦
XPS You can use the following data definition statements on a temporary table
from a secondary coserver: CREATE Temporary TABLE, CREATE INDEX,
CREATE SCHEMA, DROP TABLE, and DROP INDEX.
DB You cannot use the INFO statement and the Info Menu option with temporary
tables. ♦
Because these tables do not disappear when the database is closed, you can
use a nonlogging temporary table to transfer data from one database to
another while the application remains connected.
Related Information
Related statements: ALTER TABLE, CREATE TABLE, CREATE DATABASE, DROP
TABLE, and SELECT
+
CREATE TRIGGER
Use the CREATE TRIGGER statement to create a trigger on a table.
Syntax
REFERENCING
Clause Action Clause Trigger
for Insert Referencing Modes
p. 2-310 p. 2-314 p. 2-332
REFERENCING
Clause Action Clause
for Delete Referencing
p. 2-311 p. 2-314
UPDATE
Clause ON table Action Clause
p. 2-300 p. 2-307
REFERENCING
Clause Action Clause
IDS for Update Referencing
p. 2-312 p. 2-314
SELECT
Clause ON table Action Clause
p. 2-302 p. 2-307
REFERENCING
Clause Action Clause
for Select Referencing
p. 2-313 p. 2-314
Usage
You can use the CREATE TRIGGER statement to define a trigger on a table. A
trigger is a database object that automatically sets off a specified set of SQL
statements when a specified event occurs.
XPS You cannot create a trigger on a raw or static table. When you create a trigger
on an operational table, the table cannot use light appends. For more infor-
mation on light appends, see your Administrator’s Guide.
For information about the relationship between the privileges of the trigger
owner and the privileges of other users, see “Privileges to Execute Triggered
Actions” on page 2-326.
IDS You can use roles with triggers. Role-related statements (CREATE ROLE,
DROP ROLE, and SET ROLE) and SET SESSION AUTHORIZATION statements
can be triggered inside a trigger. Privileges that a user has acquired through
enabling a role or through a SET SESSION AUTHORIZATION statement are not
relinquished when a trigger is executed. ♦
When you create a trigger, the name of the trigger must be unique within a
database.
You can create a trigger only on a table in the current database. You cannot
create a trigger on a temporary table, a view, or a system catalog table.
You cannot create a trigger inside an SPL routine if the routine is called inside
a data manipulation statement. For example, in the following INSERT
statement, if the sp_items procedure contains a trigger, the database server
returns an error:
INSERT INTO items EXECUTE PROCEDURE sp_items
E/C If you are embedding the CREATE TRIGGER statement in an ESQL/C program,
you cannot use a host variable in the trigger specification. ♦
Trigger Events
The trigger event specifies the type of statement that activates a trigger. The
trigger event can be an INSERT, DELETE, UPDATE, or SELECT statement. Each
trigger can have only one trigger event. The occurrence of the trigger event is
the triggering statement.
For each table, you can define only one trigger that is activated by an INSERT
statement and only one trigger that is activated by a DELETE statement. For
each table, you can define multiple triggers that are activated by UPDATE
statements or SELECT statements. For more information about multiple
update or select triggers on the same table, see “UPDATE Clause” on
page 2-300 and “SELECT Clause” on page 2-302.
You are responsible for guaranteeing that the triggering statement returns the
same result with and without the triggered actions. For more information on
the behavior of triggered actions, see “Action Clause” on page 2-307 and
“Triggered Action List” on page 2-315.
This behavior is different from what occurs when a triggering statement does
not use a cursor and updates multiple rows. In this case, the set of triggered
actions executes only once. For more information on the execution of
triggered actions, see “Action Clause” on page 2-307.
UPDATE Clause
UPDATE
,
OF column
If the trigger event is an UPDATE statement, the trigger executes when any
column in the triggering column list is updated.
If the trigger event is an UPDATE statement and you do not specify the OF
column option in the definition of the trigger event, the trigger executes when
any column in the triggering table is updated.
If the triggering UPDATE statement updates more than one of the triggering
columns in a trigger, the trigger executes only once.
Then trig1 for columns a and c executes first, and trig2 for columns b and d
executes next. In this case, the smallest column number in the two triggers is
column 1 (a), and the next is column 2 (b).
SELECT
,
OF column
If the trigger event is a SELECT statement, the trigger executes when any
column in the triggering column list is selected.
If the trigger event is a SELECT statement and you do not specify the OF
column option in the definition of the trigger event, the trigger executes when
any column in the triggering table is selected.
If the triggering SELECT statement selects more than one of the triggering
columns in a trigger, the trigger executes only once.
Now suppose that the following SELECT statement invokes the my_rtn UDR
in its select list:
SELECT my_rtn() FROM tab2
This SELECT statement activates the select trigger defined on column col1 of
table tab1 when the my_rtn UDR is executed.
If you add a select trigger to a subtable, this select trigger can override the
select trigger that the subtable inherits from its supertable. For example, if the
select trigger trig1 is defined on column col1 in supertable tab1, the subtable
tab2 inherits this trigger. But if you define a select trigger named trig2 on
column col1 in subtable tab2, and a SELECT statement selects from col1 in
supertable tab1, this SELECT statement activates trigger trig1 for the rows in
table tab1 and trigger trig2 (not trigger trig1) for the rows in table tab2. In
other words, the trigger that you add to the subtable overrides the trigger
that the subtable inherits from the supertable.
Action Clause
Triggered
BEFORE Action List
p. 2-315
Triggered Triggered
FOR EACH ROW Action List AFTER Action List
p. 2-315 p. 2-315
Triggered
FOR EACH ROW Action List
p. 2-315
Triggered
AFTER Action List
p. 2-315
Triggered
AFTER Action List
p. 2-315
The action clause defines the characteristics of triggered actions and specifies
the time when these actions occur. You must define at least one triggered
action, using the keywords BEFORE, FOR EACH ROW, or AFTER to indicate
when the action occurs relative to the triggering statement. You can specify
triggered actions for all three options on a single trigger, but you must order
them in the following sequence: BEFORE, FOR EACH ROW, and AFTER. You
cannot follow a FOR EACH ROW triggered action list with a BEFORE triggered
action list. If the first triggered action list is FOR EACH ROW, an AFTER action
list is the only option that can follow it. For more information on the action
clause when a REFERENCING clause is present, see “Action Clause Refer-
encing” on page 2-314.
BEFORE Actions
The BEFORE triggered action or actions execute once before the triggering
statement executes. If the triggering statement does not process any rows, the
BEFORE triggered actions still execute because the database server does not
yet know whether any row is affected.
If the triggering statement does not insert, delete, update, or select any rows,
the FOR EACH ROW triggered actions do not execute.
XPS You cannot have FOR EACH ROW actions on tables that have globally-
detached indexes. ♦
AFTER Actions
An AFTER triggered action or actions execute once after the action of the
triggering statement is complete. If the triggering statement does not process
any rows, the AFTER triggered actions still execute.
Next, assume that you define trig1 on columns a and c, and trig2 on columns
b and d. If both triggers have triggered actions that are executed BEFORE, FOR
EACH ROW, and AFTER, then the triggered actions are executed in the
following sequence:
The database server treats the triggers as a single trigger, and the triggered
action is the merged-action list. All the rules governing a triggered action
apply to the merged list as one list, and no distinction is made between the
two original triggers.
The database server does not enforce rules to prevent these situations
because doing so would restrict the set of tables from which a triggered
action can select. Furthermore, the result of most triggered actions is
independent of row order. Consequently, you are responsible for ensuring
that the results of the triggered actions are independent of row order.
AS
Once you assign a correlation name, you can use it only inside the FOR EACH
ROW triggered action. See “Action Clause Referencing” on page 2-314.
To use the correlation name, precede the column name with the correlation
name, followed by a period. For example, if the new correlation name is post,
refer to the new value for the column fname as post.fname.
If the trigger event is an INSERT statement, using the old correlation name as
a qualifier causes an error because no value exists before the row is inserted.
For the rules that govern how to use correlation names, see “Using Corre-
lation Names in Triggered Actions” on page 2-319.
You can use the INSERT REFERENCING clause only if you define a FOR EACH
ROW triggered action.
AS
Once you assign a correlation name, you can use it only inside the FOR EACH
ROW triggered action. See “Action Clause Referencing” on page 2-314.
You use the correlation name to refer to an old column value by preceding the
column name with the correlation name and a period (.). For example, if the
old correlation name is pre, refer to the old value for the column fname as
pre.fname.
If the trigger event is a DELETE statement, using the new correlation name as
a qualifier causes an error because the column has no value after the row is
deleted. For the rules governing the use of correlation names, see “Using
Correlation Names in Triggered Actions” on page 2-319.
You can use the DELETE REFERENCING clause only if you define a FOR EACH
ROW triggered action.
XPS The OLD correlation value cannot be a byte or text value. That is, you cannot
refer to a byte or text column. ♦
AS
1 NEW correlation
AS
Once you assign a correlation name, you can use it only inside the FOR EACH
ROW triggered action. See “Action Clause Referencing” on page 2-314.
Use the correlation name to refer to an old or new column value by preceding
the column name with the correlation name and a period (.). For example, if
the new correlation name is post, you refer to the new value for the column
fname as post.fname.
If the trigger event is an UPDATE statement, you can define both old and new
correlation names to refer to column values before and after the triggering
update. For the rules that govern the use of correlation names, see “Using
Correlation Names in Triggered Actions” on page 2-319.
You can use the UPDATE REFERENCING clause only if you define a FOR EACH
ROW triggered action.
XPS
The OLD correlation value cannot be a byte or text value. That is, you cannot
refer to a byte or text column. ♦
AS
Once you assign a correlation name, you can use it only inside the FOR EACH
ROW triggered action. See “Action Clause Referencing” on page 2-314.
You use the correlation name to refer to an old column value by preceding the
column name with the correlation name and a period (.). For example, if the
old correlation name is pre, refer to the old value for the column fname as
pre.fname.
If the trigger event is a SELECT statement, using the new correlation name as
a qualifier causes an error because the column does not have a new value
after the column is selected. For the rules governing the use of correlation
names, see “Using Correlation Names in Triggered Actions” on page 2-319.
You can use the SELECT REFERENCING clause only if you define a FOR EACH
ROW triggered action.
XPS The OLD correlation value cannot be a byte or text value. That is, you cannot
refer to a byte or text column. ♦
Triggered
FOR EACH ROW Action List
Triggered p. 2-315 Triggered
BEFORE Action List AFTER Action List
p. 2-315 p. 2-315
XPS You cannot have FOR EACH ROW actions on tables that have globally-
detached indexes. ♦
,
,
INSERT Statement
( p. 2-535 )
Condition
WHEN ( ) DELETE Statement
p. 4-27 p. 2-373
UPDATE Statement
p. 2-815
EXECUTE PROCEDURE
Statement
p. 2-444
IDS
EXECUTE FUNCTION
Statement
p. 2-434
The triggered action consists of an optional WHEN condition and the action
statements. Database objects that are referenced in the triggered action, that
is, tables, columns, and UDRs, must exist when the CREATE TRIGGER
statement is executed. This rule applies only to database objects that are refer-
enced directly in the trigger definition.
WHEN Condition
The WHEN condition lets you make the triggered action dependent on the
outcome of a test. When you include a WHEN condition in a triggered action,
if the triggered action evaluates to true, the actions in the triggered action list
execute in the order in which they appear. If the WHEN condition evaluates
to false or unknown, the actions in the triggered action list are not executed.
If the triggered action is in a FOR EACH ROW section, its search condition is
evaluated for each row.
For example, the triggered action in the following trigger executes only if the
condition in the WHEN clause is true:
CREATE TRIGGER up_price
UPDATE OF unit_price ON stock
REFERENCING OLD AS pre NEW AS post
FOR EACH ROW WHEN(post.unit_price > pre.unit_price * 2)
(INSERT INTO warn_tab VALUES(pre.stock_num,
pre.order_num, pre.unit_price, post.unit_price,
CURRENT))
An SPL routine that executes inside the WHEN condition carries the same
restrictions as a UDR that is called in a data-manipulation statement.That is,
the called SPL routine cannot contain certain SQL statements. For information
on which statements are restricted, see “Restrictions on an SPL Routine
Called in a Data Manipulation Statement” on page 4-302. ♦
Action Statements
The triggered-action statements can be INSERT, DELETE, UPDATE, EXECUTE
FUNCTION, or EXECUTE PROCEDURE statements. If a triggered-action list
contains multiple statements, these statements execute in the order in which
they appear in the list.
IDS Use the EXECUTE FUNCTION statement to execute any user-defined function.
Use the EXECUTE PROCEDURE statement to execute any user-defined
procedure. ♦
XPS Use the EXECUTE PROCEDURE statement to execute any SPL routine. ♦
For restrictions that apply to using SPL routines as triggered actions, see
“Rules for SPL Routines” on page 326.
You get a syntax error if these keywords are not qualified when you use these
clauses inside a triggered action.
If you use the keyword as a column name, it must be qualified by the table
name—for example, table.update. If both the table name and the column
name are keywords, they must be qualified by the owner name—for
example, owner.insert.update. If the owner name, table name, and column
name are all keywords, the owner name must be in quotes—for example,
'delete'.insert.update. The only exception is when these keywords are the
first table or column name in the list, and you do not have to qualify them.
For example, delete in the following statement does not need to be qualified
because it is the first column listed in the INTO clause:
CREATE TRIGGER t1 UPDATE OF b ON tab1
FOR EACH ROW (EXECUTE PROCEDURE p2()
INTO delete, d)
The following statements show examples in which you must qualify the
column name or the table name:
■ You can use the correlation names for the old and new column values
only in statements in the FOR EACH ROW triggered-action list. You
can use the old and new correlation names to qualify any column in
the triggering table in either the WHEN condition or the triggered
SQL statements.
■ The old and new correlation names refer to all rows affected by the
triggering statement.
■ You cannot use the correlation name to qualify a column name in the
GROUP BY, the SET, or the COUNT DISTINCT clause.
■ The scope of the correlation names is the entire trigger definition.
This scope is statically determined, meaning that it is limited to the
trigger definition; it does not encompass cascading triggers or
columns that are qualified by a table name in a UDR that is a
triggered action.
In other words, if a column name inside a FOR EACH ROW triggered action
list is not qualified by a correlation name, even if it is qualified by the
triggering table name, it is interpreted as if the statement is independent of
the triggered action. No special effort is made to search the definition of the
triggering table for the non-qualified column name.
For the statement to be valid, both col_c and col_c2 must be columns from
tab1. If col_c2 is intended to be a correlation reference to a column in the
triggering table, it must be qualified by either the old or the new correlation
name. If col_c2 is not a column in tab1 and is not qualified by either the old
or new correlation name, you get an error.
Term Purpose
Outside a FOR EACH ROW triggered-action list, you cannot qualify a column
from the triggering table with either the old correlation name or the new
correlation name; it always refers to the current value in the database.
Reentrancy of Triggers
In some cases a trigger can be reentrant. In these cases the triggered action
can reference the triggering table. In other words, both the trigger event and
the triggered action can operate on the same table. The following list summa-
rizes the situations in which triggers can be reentrant and the situations in
which triggers cannot be reentrant:
Then in the cascading triggers shown in the following example, trig2 fails at
runtime because it references column b, which is updated by the triggering
UPDATE statement:
Now consider the following SQL statements. When the final UPDATE
statement is executed, column a is updated and the trigger trig1 is activated.
The triggered action again updates column a with an EXECUTE PROCEDURE
INTO statement.
XPS In Extended Parallel Server, to recreate this example use the CREATE
PROCEDURE statement instead of the CREATE FUNCTION statement. ♦
Several questions arise from this example of cascading triggers. First, should
the update of column a activate trigger trig1 again? The answer is no.
Because the trigger was activated, it is stopped from being activated a second
time. Whenever the triggered action is an EXECUTE PROCEDURE INTO
statement or EXECUTE FUNCTION INTO statement, the only triggers that are
activated are those that are defined on columns that are mutually exclusive
from the columns in that table updated until then (in the cascade of triggers).
Other triggers are ignored.
Another question that arises from the example is whether trigger trig2
should be activated. The answer is yes. The trigger trig2 is defined on
column e. Until now, column e in table temp1 has not been modified. Trigger
trig2 is activated.
A final question that arises from the example is whether triggers trig1 and
trig2 should be activated after the triggered action in trig2 is performed. The
answer is no. Neither trigger is activated. By this time columns a and e have
been updated once, and triggers trig1 and trig2 have been executed once. The
database server ignores these triggers instead of firing them.
■ The SPL routine cannot be a cursor function (that is, a function that
returns more than one row) in a place where only one row is
expected.
■ You cannot use the old or new correlation name inside the SPL
routine.
If you need to use the corresponding values in the routine, you must
pass them as parameters. The routine should be independent of
triggers, and the old or new correlation name do not have any
meaning outside the trigger.
When you use an SPL routine as a triggered action, the database objects that
the routine references are not checked until the routine is executed.
If the triggered action is a UDR you must have the Execute privilege on the
UDR or the owner of the trigger must have the Execute privilege and the
WITH GRANT OPTION privilege.
While executing the UDR, you do not carry the privileges of the trigger
owner; instead you receive the privileges granted with the UDR, as follows:
1. Privileges for a DBA UDR
When a UDR is registered with the CREATE DBA keywords and you
are granted the Execute privilege on the UDR, the database server
automatically grants you temporary DBA privileges while the UDR
executes. These DBA privileges are available only when you are
executing the UDR.
Cascading Triggers
The database server allows triggers other than select triggers to cascade,
meaning that the triggered actions of one trigger can activate another trigger.
For further information on the restriction against cascading select triggers,
see “Circumstances When a Select Trigger is Not Activated” on page 2-305.
When you are not using logging, referential integrity constraints on both the
manufact and stock tables prohibit the triggers in this example from
executing. When you use logging, however, the triggers execute successfully
because constraint checking is deferred until all the triggered actions are
complete, including the actions of cascading triggers. For more information
about how constraints are handled when triggers execute, see “Constraint
Checking” on page 2-329.
The database server prevents loops of cascading triggers by not allowing you
to modify the triggering table in any cascading triggered action, except an
UPDATE statement, which does not modify any column that the triggering
UPDATE statement updated, or an INSERT statement. INSERT trigger state-
ments can have UPDATE triggered actions on the same table.
Constraint Checking
When you use logging, the database server defers constraint checking on the
triggering statement until after the statements in the triggered-action list
execute. The database server effectively executes a SET CONSTRAINTS ALL
DEFERRED statement before it executes the triggering statement. After the
triggered action is completed, it effectively executes a SET CONSTRAINTS
constraint IMMEDIATE statement to check the constraints that were deferred.
This action allows you to write triggers so that the triggered action can
resolve any constraint violations that the triggering statement creates. For
more information, see “SET Database Object Mode” on page 2-700.
Consider the following example, in which the table child has constraint r1,
which references the table parent. You define trigger trig1 and activate it with
an INSERT statement. In the triggered action, trig1 checks to see if parent has
a row with the value of the current cola in child; if not, it inserts it.
CREATE TABLE parent (cola INT PRIMARY KEY);
CREATE TABLE child (cola INT REFERENCES parent CONSTRAINT r1);
CREATE TRIGGER trig1 INSERT ON child
REFERENCING NEW AS new
FOR EACH ROW
WHEN((SELECT COUNT (*) FROM parent
WHERE cola = new.cola) = 0)
-- parent row does not exist
(INSERT INTO parent VALUES (new.cola));
When you insert a row into a table that is the child table in a referential
constraint, the row might not exist in the parent table. The database server
does not immediately return this error on a triggering statement. Instead, it
allows the triggered action to resolve the constraint violation by inserting the
corresponding row into the parent table. As the previous example shows,
you can check within the triggered action to see whether the parent row
exists, and if so, bypass the insert.
For a database without logging, the database server does not defer constraint
checking on the triggering statement. In this case, it immediately returns an
error if the triggering statement violates a constraint.
You cannot use the SET Transaction Mode statement in a triggered action. The
database server checks this restriction when you activate a trigger, because
the statement could occur inside a UDR.
XPS Rows that cause constraint violations might appear in the violations table
even if a later trigger action corrects the violation. ♦
Client/Server Environment
The statements inside the triggered action can affect tables in external
databases. The following example shows an update trigger on dbserver1,
which triggers an update to items on dbserver2:
CREATE TRIGGER upd_nt UPDATE ON newtab
REFERENCING new AS post
FOR EACH ROW(UPDATE stores_demo@dbserver2:items
SET quantity = post.qty WHERE stock_num = post.stock
AND manu_code = post.mc)
UPDATE stores_demo@dbserver1:newtab
SET qty = qty * 2 WHERE s_num = 5
AND mc = 'ANZ';
If the trigger fails and the database has transactions, all triggered actions and
the triggering statement are rolled back because the triggered actions are an
extension of the triggering statement. The rest of the transaction, however, is
not rolled back.
The row action of the triggering statement occurs before the triggered actions
in the FOR EACH ROW section. If the triggered action fails for a database
without logging, the application must restore the row that was changed by
the triggering statement to its previous value.
When you use a UDR as a triggered action, if you terminate the UDR in an
exception-handling section, any actions that modify data inside that section
are rolled back along with the triggering statement. In the following partial
example, when the exception handler traps an error, it inserts a row into the
table logtab:
ON EXCEPTION IN (-201)
INSERT INTO logtab values (errno, errstr);
RAISE EXCEPTION -201
END EXCEPTION
When the RAISE EXCEPTION statement returns the error, however, the
database server rolls back this insert because it is part of the triggered actions.
If the UDR is executed outside a triggered action, the insert is not rolled back.
The UDR that implements a triggered action cannot contain any BEGIN
WORK, COMMIT WORK, or ROLLBACK WORK statements. If the database has
logging, you must either begin an explicit transaction before the triggering
statement, or the statement itself must be an implicit transaction. In any case,
another transaction-related statement cannot appear inside the UDR.
You can use triggers to enforce referential actions that the database server
does not currently support. For any database without logging, you are
responsible for maintaining data integrity when the triggering statement
fails.
DISABLED
ENABLED
Mode Purpose
Related Information
Related statements: DROP TRIGGER, CREATE PROCEDURE, EXECUTE
PROCEDURE, and SET Database Object Mode
CREATE VIEW
Use the CREATE VIEW statement to create a new view that is based on existing
tables and views in the database.
Syntax
Subset of
CREATE VIEW view AS SELECT
, Statement
p. 2-336
WITH CHECK OPTION
( column )
IDS
OF TYPE row_type
Usage
You can create typed or untyped views. If you omit the OF TYPE clause, the
rows in the view are considered to be untyped and default to an unnamed-
row type. The following statement creates a view that is based on the person
table. When you create a view without an OF TYPE clause, the view is referred
to as an untyped view.
CREATE VIEW v1 AS SELECT *
FROM person
Typed views, like typed tables, are based on a named-row type. Each column
in the view corresponds to a field in the named-row type. The following
statement creates a typed view that is based on the table person. To create a
typed view, you must include an OF TYPE clause. When you create a typed
view, the named-row type that you specify immediately after the OF TYPE
keywords must already exist.
CREATE VIEW v2 OF TYPE person_t AS SELECT *
FROM person
Except for the statements in the following list, you can use a view in any SQL
statement where you can use a table:
ALTER FRAGMENT DROP INDEX
ALTER INDEX DROP TABLE
ALTER TABLE DROP TRIGGER
CREATE INDEX LOCK TABLE
CREATE TABLE RENAME TABLE
CREATE TRIGGER UNLOCK TABLE
The view behaves like a table that is called view. It consists of the set of rows
and columns that the SELECT statement returns each time the SELECT
statement is executed by using the view. The view reflects changes to the
underlying tables with one exception. If a SELECT * clause defines the view,
the view has only the columns in the underlying tables at the time the view
is created. New columns that are subsequently added to the underlying
tables with the ALTER TABLE statement do not appear in the view.
The view name must be unique; that is, a view name cannot have the same
name as another database object, such as a table, synonym, or temporary
table.
The view inherits the data types of the columns in the tables from which the
view is derived. The database server determines data types of virtual
columns from the nature of the expression.
To create a view, you must have the Select privilege on all columns from
which the view is derived.
The SELECT statement is stored in the sysviews system catalog table. When
you subsequently refer to a view in another statement, the database server
performs the defining SELECT statement while it executes the new statement.
Restrictions
You cannot create a view on a temporary table.
IDS You cannot create a view on the following types of tables in a remote
database:
■ Typed tables (including any table that is part of a table hierarchy)
■ Tables that contain any extended data types
Do not use display labels in the select list. Display labels in the select list are
interpreted as column names.
The SELECT statement in CREATE VIEW cannot include the following clauses:
■ FIRST
■ INTO TEMP
■ ORDER BY
Union Views
The SELECT statement in CREATE VIEW can contain a UNION or UNION ALL
operator. A view that contains a UNION or UNION ALL operator in its SELECT
statement is known as a union view. Observe the following restrictions on
union views:
For an example of a CREATE VIEW statement that defines a union view, see
“Naming View Columns.”
If you do not specify a list of columns, the view inherits the column names of
the underlying tables. In the following example, the view herostock has the
same column names as the ones in the SELECT statement:
CREATE VIEW herostock AS
SELECT stock_num, description, unit_price, unit,
unit_descr
FROM stock WHERE manu_code = 'HRO'
You must also provide a column name in cases where the selected columns
have duplicate column names when the table prefixes are stripped. For
example, when both orders.order_num and items.order_num appear in the
SELECT statement, you must provide two separate column names to label
them in the CREATE VIEW statement, as the following example shows:
CREATE VIEW someorders (custnum,ocustnum,newprice) AS
SELECT orders.order_num,items.order_num,
items.total_price*1.5
FROM orders, items
WHERE orders.order_num = items.order_num
AND items.total_price > 100.00
You must also provide column names in the column parameter when the
SELECT statement includes a UNION or UNION ALL operator and the names
of the corresponding columns in the SELECT statements are not identical. In
the following example, the user must specify the column parameter since the
second column in the first SELECT statement has a different name from the
second column in the second SELECT statement.
CREATE VIEW myview (cola, colb) AS
SELECT colx, coly from firsttab
UNION
SELECT colx, colz from secondtab
If you must provide names for some of the columns in a view, then you must
provide names for all the columns; that is, the column list must contain an
entry for every column that appears in the view.
The following example creates a view that is named palo_alto, which uses all
the information in the customer table for customers in the city of Palo Alto.
The database server checks any modifications made to the customer table
through palo_alto because the WITH CHECK OPTION is specified.
CREATE VIEW palo_alto AS
SELECT * FROM customer
WHERE city = 'Palo Alto'
WITH CHECK OPTION
You can insert into a view a row that does not satisfy the conditions of the
view (that is, a row that is not visible through the view). You can also update
a row of a view so that it no longer satisfies the conditions of the view. For
example, if the view was created without the WITH CHECK OPTION
keywords, you could insert a row through the view where the city is Los
Altos, or you could update a row through the view by changing the city from
Palo Alto to Los Altos.
To prevent such inserts and updates, you can add the WITH CHECK OPTION
keywords when you create the view. These keywords ask the database server
to test every inserted or updated row to ensure that it meets the conditions
that are set by the WHERE clause of the view. The database server rejects the
operation with an error if the row does not meet the conditions.
However, even if the view was created with the WITH CHECK OPTION
keywords, you can perform inserts and updates through the view to change
columns that are not part of the view definition. A column is not part of the
view definition if it does not appear in the WHERE clause of the SELECT
statement that defines the view.
In an updatable view, you can update the values in the underlying table by
inserting values into the view.
In addition, if a view is built on a table that has a derived value for a column,
that column is not updatable through the view. However, other columns in
the view can be updated.
Important: You cannot update or insert rows in a remote table through views with
check options.
Related Information
Related statements: CREATE TABLE, DROP VIEW, GRANT, SELECT, and SET
SESSION AUTHORIZATION
For a discussion of views, see the Informix Guide to Database Design and
Implementation.
+
DATABASE
Use the DATABASE statement to select an accessible database as the current
database.
Syntax
DATABASE database
EXCLUSIVE
Usage
You can use the DATABASE statement to select any database on your database
server. To select a database on another database server, specify the name of
the database server with the database name.
If you specify the name of the current database server or another database
server with the database name, the database server name cannot be
uppercase.
The current user (or PUBLIC) must have the Connect privilege on the
database specified in the DATABASE statement. The current user cannot have
the same user name as an existing role in the database.
If the database has transactions, the second element of the sqlwarn structure
(the sqlca.sqlwarn.sqlwarn1 field) contains a W after the DATABASE
statement executes.
EXCLUSIVE Keyword
The EXCLUSIVE keyword opens the database in exclusive mode and prevents
access by anyone but the current user. To allow others access to the database,
you must execute the CLOSE DATABASE statement and then reopen the
database without the EXCLUSIVE keyword.
If another user has already opened the database, exclusive access is denied,
an error is returned, and no database is opened.
Related Information
Related statements: CLOSE DATABASE and CONNECT
For discussions of how to use different data models to design and implement
a database, see the Informix Guide to Database Design and Implementation.
+ DEALLOCATE COLLECTION
IDS
Use the DEALLOCATE COLLECTION statement to release memory for a
E/C collection variable that was previously allocated with the ALLOCATE
COLLECTION statement.
Syntax
Usage
The DEALLOCATE COLLECTION statement frees all the memory that is
associated with the ESQL/C collection variable that variable identifies. You
must explicitly release memory resources for a collection variable with
DEALLOCATE COLLECTION. Otherwise, deallocation occurs automatically at
the end of the program.
Example
The following example shows how to deallocate resources with the
DEALLOCATE COLLECTION statement for the untyped collection variable,
a_set:
EXEC SQL BEGIN DECLARE SECTION;
client collection a_set;
EXEC SQL END DECLARE SECTION;
.
.
.
EXEC SQL allocate collection :a_set;
.
.
.
EXEC SQL deallocate collection :a_set;
Related Information
Related example: refer to the collection variable example in PUT.
+ DEALLOCATE DESCRIPTOR
E/C
Use the DEALLOCATE DESCRIPTOR statement to free a previously allocated,
system-descriptor area.
Syntax
Usage
The DEALLOCATE DESCRIPTOR statement frees all the memory that is
associated with the system-descriptor area that descriptor or descriptor_var
identifies. It also frees all the item descriptors (including memory for data
items in the item descriptors).
Related Information
Related statements: ALLOCATE DESCRIPTOR, DECLARE, DESCRIBE,
EXECUTE, FETCH, GET DESCRIPTOR, OPEN, PREPARE, PUT, and SET
DESCRIPTOR
+ DEALLOCATE ROW
IDS
Use the DEALLOCATE ROW statement to release memory for a row variable
E/C that was previously allocated with the ALLOCATE ROW statement.
Syntax
Usage
The DEALLOCATE ROW statement frees all the memory that is associated
with the ESQL/C row variable that variable identifies. You must explicitly
release memory resources for a row variable with DEALLOCATE ROW.
Otherwise, deallocation occurs automatically at the end of the program.
Tip: The DEALLOCATE ROW statement deallocates memory for an ESQL/C row
variable only. To deallocate memory for an ESQL/C collection variable, use the
DEALLOCATE COLLECTION statement.
Example
The following example shows how to deallocate resources for the row
variable, a_row, with the DEALLOCATE ROW statement:
EXEC SQL BEGIN DECLARE SECTION;
row (a int, b int) a_row;
EXEC SQL END DECLARE SECTION;
.
.
.
EXEC SQL allocate row :a_row;
.
.
.
EXEC SQL deallocate row :a_row;
Related Information
Related statements: ALLOCATE ROW and DEALLOCATE COLLECTION
For a discussion of row types, see the Informix Guide to SQL: Tutorial.
For a discussion of complex data types, see the Informix ESQL/C Programmer’s
Manual.
E/C
DECLARE
Use the DECLARE statement to associate a cursor with a group of rows.
Syntax
Subset of
DECLARE cursor_id CURSOR FOR + INSERT
+ Statement
+ p. 2-358
WITH HOLD
cursor_id_var
Subset of
SELECT FOR READ ONLY
Statement +
p. 2-363
FOR UPDATE
,
+ OF column
SCROLL CURSOR FOR
SELECT
WITH HOLD Statement
p. 2-634
statement_id
+
statement_id_var
EXECUTE PROCEDURE
Statement
p. 2-444
IDS IDS
EXECUTE FUNCTION
Statement
p. 2-444
SELECT with Collection Derived Table
CURSOR FOR p. 2-367
Usage
A cursor is an identifier that you associate with a group of rows. The
DECLARE statement associates the cursor with one of the following database
objects:
The DECLARE statement assigns an identifier to the cursor, specifies its uses,
and directs the preprocessor to allocate storage to hold the cursor.
The DECLARE statement must precede any other statement that refers to the
cursor during the execution of the program.
A program can consist of one or more source-code files. By default, the scope
of a cursor is global to a program, so a cursor declared in one file can be refer-
enced from another file. In a multiple-file program, if you want to limit the
scope of cursors to the files in which they are declared, you must preprocess
all the files with the -local command-line option.
To declare multiple cursors, use a single statement identifier. For instance, the
following ESQL/C example does not return an error:
EXEC SQL prepare id1 from 'select * from customer';
EXEC SQL declare x cursor for id1;
EXEC SQL declare y scroll cursor for id1;
EXEC SQL declare z cursor with hold for id1;
■ Illegal use of cursors (that is, normal cursors used as scroll cursors)
■ Use of undeclared cursors
■ Bad cursor or statement names (empty)
Checks for multiple declarations of a cursor of the same name are performed
at compile time only if the cursor or statement is an identifier. The following
example uses a host variable to hold the cursor name.
EXEC SQL declare x cursor for
select * from customer;
. . .
stcopy("x", s);
EXEC SQL declare :s cursor for
select * from customer;
Any of these cursor types can have cursor characteristics: sequential, scroll,
and hold. These characteristics determine the structure of the cursor. For
more information, see “Cursor Characteristics” on page 2-360. In addition, a
select or function cursor can have a cursor mode: read-only or update. For
more information, see “Select Cursor or Function Cursor” on page 2-353.
XPS In Extended Parallel Server, to create a function cursor, you must use the
EXECUTE PROCEDURE statement. Extended Parallel Server does not support
the EXECUTE FUNCTION statement. ♦
A select or function cursor enables you to scan returned rows of data and to
move data row by row into a set of receiving variables, as the following steps
describe:
1. DECLARE
Use a DECLARE statement to define a cursor and associate it with a
statement.
2. OPEN
Use the OPEN statement to open the cursor. The database server
processes the query until it locates or constructs the first row of the
active set.
3. FETCH
Use the FETCH statement to retrieve successive rows of data from the
cursor.
4. CLOSE
Use the CLOSE statement to close the cursor when the active set is no
longer needed.
5. FREE
Use the FREE statement to release the resources that are allocated for
the declared cursor.
The need for the FOR READ ONLY keywords depends on whether your
database is an ANSI-compliant database or a database that is not ANSI
compliant.
In a database that is not ANSI compliant, the cursor that the DECLARE
statement defines is a read-only cursor by default. So you do not need to
specify the FOR READ ONLY keywords if you want the cursor to be a read-
only cursor. The only advantage of specifying the FOR READ ONLY keywords
explicitly is for better program documentation.
In an update cursor, you can update or delete rows in the active set. After you
create an update cursor, you can update or delete the currently selected row
by using an UPDATE or DELETE statement with the WHERE CURRENT OF
clause. The words CURRENT OF refer to the row that was most recently
fetched; they take the place of the usual test expressions in the WHERE clause.
An update cursor lets you perform updates that are not possible with the
UPDATE statement because the decision to update and the values of the new
data items can be based on the original contents of the row. Your program can
evaluate or manipulate the selected data before it decides whether to update.
The UPDATE statement cannot interrogate the table that is being updated.
The following example declares an update cursor and specifies that this
cursor can update only the fname and lname columns in the
customer_notansi table:
EXEC SQL declare name_curs cursor for
select * from customer_notansi
for update of fname, lname;
If the columns that you intend to update are part of the index that is used to
process the SELECT statement, the database server must keep a list of each
row that is updated to ensure that no row is updated twice. When you use
the OF keyword to specify the columns that can be updated, the database
server determines whether to keep the list of updated rows. If the database
server determines that the list is unnecessary, then eliminating the work of
keeping the list results in a performance benefit. If you do not use the OF
keyword, the database server keeps the list of updated rows, although it
might be unnecessary.
The following example contains ESQL/C code that uses an update cursor
with a DELETE statement to delete the current row. Whenever the row is
deleted, the cursor remains between rows. After you delete data, you must
use a FETCH statement to advance the cursor to the next row before you can
refer to the cursor in a DELETE or UPDATE statement.
EXEC SQL declare q_curs cursor for
select * from customer where lname matches :last_name
for update;
if (answer[0] == 'y')
EXEC SQL delete from customer where current of q_curs;
if (strncmp(SQLSTATE, "00", 2) != 0)
break;
}
printf("\n");
EXEC SQL close q_curs;
The following example contains ESQL/C code that declares an insert cursor:
EXEC SQL declare ins_cur cursor for
insert into stock values
(:stock_no,:manu_code,:descr,:u_price,:unit,:u_desc);
The insert cursor simply inserts rows of data; it cannot be used to fetch data.
When an insert cursor is opened, a buffer is created in memory to hold a
block of rows. The buffer receives rows of data as the program executes PUT
statements. The rows are written to disk only when the buffer is full. You can
use the CLOSE, FLUSH, or COMMIT WORK statement to flush the buffer when
it is less than full. This topic is discussed further under the PUT and CLOSE
statements. You must close an insert cursor to insert any buffered rows into
the database before the program ends. You can lose data if you do not close
the cursor properly.
Insert Cursor
When you associate an INSERT statement with a cursor, the cursor is called an
insert cursor. An insert cursor is a data structure that represents the rows that
the INSERT statement is to add to the database. The insert cursor simply
inserts rows of data; it cannot be used to fetch data. To create an insert cursor,
you associate a cursor with a restricted form of the INSERT statement. The
INSERT statement must include a VALUES clause; it cannot contain an
embedded SELECT statement.
Create an insert cursor if you want to add multiple rows to the database in an
INSERT operation. An insert cursor allows bulk insert data to be buffered in
memory and written to disk when the buffer is full, as the following steps
describe:
5. Close the cursor with the CLOSE statement when the insert cursor is
no longer needed. You must close an insert cursor to insert any
buffered rows into the database before the program ends. You can
lose data if you do not close the cursor properly.
6. Free the cursor with the FREE statement. The FREE statement releases
the resources that are allocated for an insert cursor.
In addition to select and function cursors, insert cursors can also have the
sequential cursor characteristic. To create an insert cursor, you associate a
sequential cursor with a restricted form of the INSERT statement. (For more
information, see “Insert Cursor” on page 2-359.) The following example
contains Informix ESQL/C code that declares a sequential insert cursor:
EXEC SQL declare ins_cur cursor for
insert into stock values
(:stock_no,:manu_code,:descr,:u_price,:unit,:u_desc);
Cursor Characteristics
Structurally, you can declare a cursor as a sequential cursor (the default
condition), a scroll cursor (using the SCROLL keyword), or a hold cursor (using
the WITH HOLD keywords). The following sections explain these structural
characteristics.
In addition to select and function cursors, insert cursors can also have the
sequential cursor characteristic. To create an insert cursor, you associate a
sequential cursor with a restricted form of the INSERT statement. (For more
information, see “Insert Cursor” on page 2-359.) The following example
declares a sequential insert cursor:
EXEC SQL declare ins_cur cursor for
insert into stock values
(:stock_no,:manu_code,:descr,:u_price,:unit,:u_desc);
The database server retains the active set of the cursor as a temporary table
until the cursor is closed. You can fetch the first, last, or any intermediate
rows of the active set as well as fetch rows repeatedly without having to close
and reopen the cursor. (See FETCH.)
On a multiuser system, the rows in the tables from which the active-set rows
were derived might change after the cursor is opened and a copy is made in
the temporary table. If you use a scroll cursor within a transaction, you can
prevent copied rows from changing either by setting the isolation level to
Repeatable Read or by locking the entire table in share mode during the
transaction. (See SET ISOLATION and LOCK TABLE.)
Restrictions
You can create scroll cursors for select and function cursors but not for insert
cursors. Scroll cursors cannot be declared as FOR UPDATE.
You can use the WITH HOLD keywords to declare select and function cursors
(sequential and scroll), and insert cursors. These keywords follow the
CURSOR keyword in the DECLARE statement. The following example creates
a sequential hold cursor for a SELECT:
DECLARE hld_cur CURSOR WITH HOLD FOR
SELECT customer_num, lname, city FROM customer
You can use a select hold cursor as the following ESQL/C code example
shows. This code fragment uses a hold cursor as a master cursor to scan one
set of records and a sequential cursor as a detail cursor to point to records that
are located in a different table. The records that the master cursor scans are
the basis for updating the records to which the detail cursor points. The
COMMIT WORK statement at the end of each iteration of the first WHILE loop
leaves the hold cursor c_master open but closes the sequential cursor
c_detail and releases all locks. This technique minimizes the resources that
the database server must devote to locks and unfinished transactions, and it
gives other users immediate access to updated rows.
EXEC SQL BEGIN DECLARE SECTION;
int p_custnum,
int save_status;
long p_orddate;
EXEC SQL END DECLARE SECTION;
Use either the CLOSE statement to close the hold cursor explicitly or the
CLOSE DATABASE or DISCONNECT statements to close it implicitly. The
CLOSE DATABASE statement closes all cursors.
If the DECLARE statement includes the FOR READ ONLY option, the SELECT
statement must conform to the following restrictions:
XPS ■ In Extended Parallel Server, the statement cannot include the INTO
EXTERNAL and INTO SCRATCH clauses. ♦
If you want to make it clear in the program code that this cursor is a read-only
cursor, you can specify the FOR READ ONLY option as shown in the following
example:
EXEC SQL declare cust_curs cursor for
select * from customer_notansi
for read only;
If you want this cursor to be an update cursor, you need to specify the FOR
UPDATE option in your DECLARE statement. The following example declares
an update cursor:
EXEC SQL declare new_curs cursor for
select * from customer_notansi
for update;
If you want an update cursor to be able to modify only some of the columns
in a table, you need to specify these columns in the FOR UPDATE option. The
following example declares an update cursor and specifies that this cursor
can update only the fname and lname columns in the customer_notansi
table:
EXEC SQL declare name_curs cursor for
select * from customer_notansi
for update of fname, lname;
If you want to make it clear in the program documentation that this cursor is
an update cursor, you can specify the FOR UPDATE option as shown in the
following example:
EXEC SQL declare x_curs cursor for
select * from customer_ansi
for update;
If you want an update cursor to be able to modify only some of the columns
in a table, you must specify these columns in the FOR UPDATE option. The
following example declares an update cursor and specifies that this cursor
can update only the fname and lname columns in the customer_ansi table:
EXEC SQL declare y_curs cursor for
select * from customer_ansi
for update of fname, lname;
If you want a cursor to be a read-only cursor, you must override the default
behavior of the DECLARE statement by specifying the FOR READ ONLY
option in your DECLARE statement. The following example declares a
read-only cursor:
EXEC SQL declare z_curs cursor for
select * from customer_ansi
for read only;
You can associate a sequential cursor with any prepared SELECT or EXECUTE
FUNCTION (or EXECUTE PROCEDURE) statement. You cannot associate a
scroll cursor with a prepared INSERT statement or with a SELECT statement
that was prepared to include a FOR UPDATE clause.
If you want to use a prepared SELECT statement to modify data, add a FOR
UPDATE clause to the statement text that you wish to prepare, as the
following ESQL/C example shows:
EXEC SQL prepare sel_1 from
'select * from customer for update';
EXEC SQL declare sel_curs cursor for sel_1;
The Collection Derived Table segment identifies the collection variable for
which to declare the cursor. For more information, see “Collection Derived
Table” on page 4-9.
Restrictions
When you declare a select cursor for a collection variable, the DECLARE
statement has the following restrictions:
■ It can not include the FOR READ ONLY keywords that specify the
read-only cursor mode.
The select cursor is an update cursor.
■ It cannot include the SCROLL or WITH HOLD keywords.
The select cursor must be a sequential cursor.
In addition, the SELECT statement that you associate with the collection
cursor has the following restrictions:
Example
The following DECLARE statement declares a select cursor for a collection
variable:
EXEC SQL BEGIN DECLARE SECTION;
client collection set(integer not null) a_set;
EXEC SQL END DECLARE SECTION;
...
EXEC SQL declare set_curs cursor for
select * from table(:a_set);
For an extended code example that uses a collection cursor for a SELECT
statement, see “Fetching From a Collection Cursor” on page 2-466.
Restrictions
The insert cursor must be a sequential cursor, that is the DECLARE statement
cannot contain the WITH HOLD keywords.
When you declare an insert cursor for a collection variable, the Collection-
Derived Table clause of the INSERT statement must contain the name of the
collection variable. You cannot specify an input parameter (the question-
mark (?) symbol) for the collection variable. However, you can use an input
parameter in the VALUES clause of the INSERT statement. This parameter
indicates that the collection element is to be provided later by the FROM
clause of the PUT statement.
Example
For example, the following DECLARE statement declares an insert cursor for
the a_set collection variable:
EXEC SQL BEGIN DECLARE SECTION;
client collection multiset(smallint not null) a_mset;
int an_element;
EXEC SQL END DECLARE SECTION;
...
EXEC SQL declare mset_curs cursor for
insert into table(:a_mset)
values (?);
EXEC SQL open mset_curs;
while (1)
{
...
EXEC SQL put mset_curs from :an_element;
...
}
To insert the elements into the collection variable, use the PUT statement with
the FROM clause. For a code example that uses a collection cursor for an
INSERT statement, see “Inserting into a Collection Cursor” on page 2-599.
The database server enforces the following guidelines for select and update
cursors. These guidelines ensure that modifications can be committed or
rolled back properly:
■ Open an insert or update cursor within a transaction.
■ Include PUT and FLUSH statements within one transaction.
■ Modify data (update, insert, or delete) within one transaction.
The database server lets you open and close a hold cursor for an update
outside a transaction; however, you should fetch all the rows that pertain to
a given modification and then perform the modification all within a single
transaction. You cannot open and close hold or update cursors outside a
transaction.
When you update a row within a transaction, the row remains locked until
the cursor is closed or the transaction is committed or rolled back. If you
update a row when no transaction is in effect, the row lock is released when
the modified row is written to disk.
If you update or delete a row outside a transaction, you cannot roll back the
operation.
In a database that uses transactions, you cannot open an insert cursor outside
a transaction unless it was also declared with the WITH HOLD keywords.
Related Information
Related statements: CLOSE, DELETE, EXECUTE PROCEDURE, FETCH, FREE,
INSERT, OPEN, PREPARE, PUT, SELECT, and UPDATE
For discussions of cursors and data modification, see the Informix Guide to
SQL: Tutorial.
DELETE
Use the DELETE statement to delete one or more rows from a table, or one or
more elements in an SPL or ESQL/C collection variable.
Syntax
view
+
synonym
IDS Condition
WHERE
Optimizer + p. 4-27
Directives
p. 4-244 IDS
+
,
XPS
USING table WHERE Condition
p. 4-27
FROM view
synonym
alias
Usage
If you use the DELETE statement without a WHERE clause (either to introduce
a condition or to indicate the active set of the cursor), the database server
deletes all the rows in the table.
If you use the DELETE statement outside a transaction in a database that uses
transactions, each DELETE statement that you execute is treated as a single
transaction.
The database server locks each row affected by a DELETE statement within a
transaction for the duration of the transaction. The type of lock that the
database server uses is determined by the lock mode of the table, as set by a
CREATE TABLE or ALTER TABLE statement, as follows:
■ If the lock mode is ROW, the database server acquires one lock for
each row affected by the delete.
XPS ■ In Extended Parallel Server, if the lock mode is PAGE, the database
server acquires one lock for each page affected by the delete. ♦
If the number of rows affected is very large and the lock mode is ROW, you
might exceed the limits your operating system places on the maximum
number of simultaneous locks. If this occurs, you can either reduce the scope
of the DELETE statement or lock the table in exclusive mode before you
execute the statement.
If you specify a view name, the view must be updatable. For an explanation
of an updatable view, see “Updating Through Views” on page 2-339.
DB If you omit the WHERE clause while you are working within the SQL menu,
DB-Access prompts you to verify that you want to delete all rows from a
table. You do not receive a prompt if you run the DELETE statement within a
command file. ♦
Warning: If you use the DELETE statement on a supertable without the ONLY
keyword and without a WHERE clause, all rows of the supertable and its subtables
are deleted.
You cannot specify the ONLY keyword if you plan to use the WHERE
CURRENT OF clause to delete the current row of the active set of a cursor.
You cannot use a child table in a correlated subquery to delete a row from a
parent table.
IDS You must turn logging on when you perform the deletes. If logging is turned
off in a database, even temporarily, deletes do not cascade because if logging
is turned off, you cannot roll back any actions. For example, if a parent row
is deleted, and the system fails before the child rows are deleted, the database
will have dangling child records, which violates referential integrity.
However, when logging is turned back on, subsequent deletes cascade. ♦
DB If you include a WHERE clause that selects all rows in the table, DB-Access
gives no prompt and deletes all rows. ♦
IDS If you are deleting from a supertable in a table hierarchy, a subquery in the
WHERE clause cannot reference a subtable.
When you use the WHERE CURRENT OF clause, THE DELETE statement
removes the row of the active set at the current position of the cursor. After
the deletion, no current row exists; you cannot use the cursor to delete or
update a row until you reposition the cursor with a FETCH statement.
You access the current row of the active set of a cursor with an update cursor.
Before you can use the THIS clause, you must create a cursor with the
FOREACH statement (SPL) or the DECLARE statement with the FOR UPDATE
clause (ESQL/C). ♦
IDS You cannot use this clause if you are selecting from only one table in a table
hierarchy. That is, you cannot use this option if you use the ONLY keyword.
You use this clause to delete an element from a collection. However, you
actually delete the current row of the collection derived table that a collection
variable holds. For more information, see “Collection Derived Table” on
page 4-9. ♦
When you use this syntax, the WHERE clause can include any complex join.
If you do not list a join in the WHERE clause, the database server ignores the
tables listed after the introductory keyword (either USING or FROM). That is,
the query performs as if the list of tables was not included.
Although you can use a second FROM keyword to introduce the list of tables,
Informix recommends that you use the USING keyword for more readable
code.
E/C When you use a delete join, the entire operation occurs as a single trans-
action. For example if a delete join query is supposed to delete 100 rows and
an error occurs after the 50th row, the first 50 rows that are already deleted
will reappear in the table. ♦
Restrictions
When you introduce a list of tables that you want to join in the WHERE clause,
the following restrictions for the DELETE statement exist:
■ You must list the target table (the one from which rows are to be
deleted) and any table that will be part of a join after the USING (or
second FROM) keyword.
■ The WHERE clause cannot contain outer joins.
■ The target table cannot be a static or external table.
■ The statement cannot contain cursors.
Example
The following example deletes those rows from the lineitem table whose
corresponding rows in the order table show that nothing was ordered (that
is, a qty of less than one).
DELETE FROM lineitem
USING order o, lineitem l
WHERE o.qty < 1 AND o.order_num = l.order_num
When to Use
A delete join makes it easier to incorporate new data into a database. For
example, you can:
In addition, you can use this syntax instead of deleting from the results of a
SELECT statement that includes a join.
E/C You can also use a collection variable to delete values in a collection column.
With a collection variable you can delete one or more individual elements in
SPL a collection. For more information, see “Collection Derived Table” on
page 4-9.♦
The database server also sets SQLSTATE and SQLCODE to these values if the
DELETE... WHERE... is a part of a multistatement prepare and the database
server returns no rows. ♦
Related Information
Related Statements: DECLARE, FETCH, GET DIAGNOSTICS, INSERT, OPEN,
SELECT, and UPDATE
For information on how to access row and collections with ESQL/C host
variables, see the chapter on complex data types in the Informix ESQL/C
Programmer’s Manual.
For a discussion of the GLS aspects of the DELETE statement, see the Informix
Guide to GLS Functionality.
+ DESCRIBE
E/C
Use the DESCRIBE statement to obtain information about a prepared
statement before you execute it.
Syntax
INTO sqlda_pointer
Usage
The DESCRIBE statement allows you to determine, at runtime, the following
information about a prepared statement:
With this information, you can write code to allocate memory to hold
retrieved values and display or process them after they are fetched.
You can test the number against the constant names that are defined. In
ESQL/C, the constant names are defined in the sqlstype.h header file.
The DESCRIBE statement uses the SQLCODE field differently from any other
statement, possibly returning a nonzero value when it executes successfully.
You can revise standard error-checking routines to accommodate this
behavior, if desired.
IDS ■ UPDATE
The IFX_UPDDESC environment variable must be set before you can
DESCRIBE an UPDATE statement. For more information, see the
Informix Guide to SQL: Reference. ♦
When you describe one of the previously mentioned statements into a system
descriptor area, the database server updates the system-descriptor area in the
following ways:
■ It sets the COUNT field in the system-descriptor area to the number
of values in the statement list. If COUNT is greater than the number
of item descriptors in the system-descriptor area, the system returns
an error.
■ It sets the TYPE, LENGTH, NAME, SCALE, PRECISION, and NULLABLE
fields in system-descriptor area.
IDS If the column has an opaque data type, the database server sets the
EXTYPEID, EXTYPENAME, EXTYPELENGTH, EXTYPEOWNER-
LENGTH, and EXTYPEOWNERNAME fields of the item descriptor. ♦
■ It allocates memory for the DATA field for each item descriptor, based
on the TYPE and LENGTH information.
You can use the system-descriptor area in statements that support a USING
SQL DESCRIPTOR clause, such as EXECUTE, FETCH, OPEN, and PUT.
The DESCRIBE statement sets the sqlda.sqld field to the number of values in
the statement list. The sqlda structure also contains an array of data
descriptors (sqlvar structures), one for each value in the statement list. After
a DESCRIBE statement is executed, the sqlda.sqlvar structure has the sqltype,
sqllen, and sqlname fields set.
IDS If the column has an opaque data type, DESCRIBE...INTO sets the sqlxid,
sqltypename, sqltypelen, sqlownerlen, and sqlownername fields of the
item descriptor. ♦
You must perform the DESCRIBE statement after you open the select or insert
cursor. Otherwise, DESCRIBE cannot get information about the collection
variable because it is the OPEN...USING statement that specifies the name of
the collection variable to use.
The following ESQL/C code fragment shows how to dynamically select the
elements of the :a_set collection variable into a system-descriptor area called
desc1:
EXEC SQL BEGIN DECLARE SECTION;
client collection a_set;
int i, set_count;
int element_type, element_value;
EXEC SQL END DECLARE SECTION;
do
{
EXEC SQL fetch set_curs using sql descriptor
'desc1';
...
EXEC SQL get descriptor 'desc1' :set_count =
count;
for (i = 1; i <= set_count; i++)
{
EXEC SQL get descriptor 'desc1' value :i
:element_type = TYPE;
switch
{
case SQLINTEGER:
EXEC SQL get descriptor 'desc1' value
:i
:element_value = data;
...
} /* end switch */
} /* end for */
} while (SQLCODE == 0);
Related Information
Related statements: ALLOCATE DESCRIPTOR, DEALLOCATE DESCRIPTOR,
DECLARE, EXECUTE, FETCH, GET DESCRIPTOR, OPEN, PREPARE, PUT, and
SET DESCRIPTOR
For more information about how to use a system-descriptor area and sqlda,
refer to the Informix ESQL/C Programmer’s Manual.
+
DISCONNECT
Use the DISCONNECT statement to terminate a connection between an appli-
cation and a database server.
Syntax
DISCONNECT CURRENT
E/C
DEFAULT
ALL
'connection '
connection_var
Usage
The DISCONNECT statement lets you terminate a connection to a database
server. If a database is open, it closes before the connection drops. Even if you
made a connection to a specific database only, that connection to the database
server is terminated by the DISCONNECT statement.
You cannot use the PREPARE statement for the DISCONNECT statement.
DEFAULT Option
Use the DEFAULT option to identify the default connection for a
DISCONNECT statement. The default connection is one of the following
connections:
You can use DISCONNECT to disconnect the default connection. For more
information, see “DEFAULT Option” on page 2-105 and “The Implicit
Connection with DATABASE Statements” on page 2-106.
CURRENT Keyword
Use the CURRENT keyword with the DISCONNECT statement as a shorthand
form of identifying the current connection. The CURRENT keyword replaces
the current connection name. For example, the DISCONNECT statement in the
following excerpt terminates the current connection to the database server
mydbsrvr:
CONNECT TO 'stores_demo@mydbsrvr'
.
.
.
DISCONNECT CURRENT
However, once a connection becomes dormant, any other thread can discon-
nect this connection unless an ongoing transaction is associated with the
dormant connection (the connection was established with the WITH CON-
CURRENT TRANSACTION clause of CONNECT). If the dormant connection
was not established with the WITH CONCURRENT TRANSACTION clause,
DISCONNECT generates an error when it tries to disconnect it.
E/C In ESQL/C, the ALL keyword has the same effect on multithreaded applica-
tions that it has on single-threaded applications. Execution of the
DISCONNECT ALL statement causes all connections in all threads to be termi-
nated. However, the DISCONNECT ALL statement fails if any of the
connections is in use or has an ongoing transaction associated with it. If either
of these conditions is true, none of the connections is disconnected. ♦
Related Information
Related statements: CONNECT, DATABASE, and SET CONNECTION
+ DROP AGGREGATE
IDS
Use the DROP AGGREGATE statement to drop a user-defined aggregate that
you created with the CREATE AGGREGATE statement.
Syntax
Owner
Name
p. 4-257
Usage
The support functions defined for a user-defined aggregate do not depend on
the aggregate for their existence. When you drop a user-defined aggregate,
you do not drop the support functions that you defined for the aggregate in
the CREATE AGGREGATE statement.
The database server does not track dependency of SQL statements on user-
defined aggregates that you use in the statements. For example, you can drop
a user-defined aggregate that is used in an SPL routine.
In the following example, the user drops the aggregate named my_avg.
DROP AGGREGATE my_avg
Related Information
Related statements: CREATE AGGREGATE
For a description of the sysaggregates system catalog table that holds infor-
mation about user-defined aggregates, see the Informix Guide to SQL:
Reference.
+ DROP CAST
IDS
Use the DROP CAST statement to remove a previously defined cast from the
database.
Syntax
Usage
You must be the owner of the cast or have the DBA privilege to use the DROP
CAST statement.
A cast that is defined on a particular data type can also be used on any
distinct types created from that type. When you drop the cast, you can no
longer invoke it for the distinct types. Dropping a cast that is defined for a
distinct type has no effect on casts for its source type.
When you create a distinct type, the database server automatically defines an
explicit cast from the distinct type to its source type and another explicit cast
from the source type to the distinct type. When you drop the distinct type, the
database server automatically drops these two casts.
Related Information
Related statements: CREATE CAST and DROP FUNCTION
For more information about data types, refer to the Informix Guide to SQL:
Reference.
+
DROP DATABASE
Use the DROP DATABASE statement to delete an entire database, including all
system catalog tables, indexes, and data.
Syntax
Usage
This statement is an extension to ANSI-standard syntax. The ANSI standard
does not provide any syntax for the destruction of a database.
You must have the DBA privilege or be user informix to run the DROP
DATABASE statement successfully. Otherwise, the database server issues an
error message and does not drop the database.
You cannot drop the current database or a database that is being used by
another user. All the database users must first execute the CLOSE DATABASE
statement.
DB In DB-Access, use this statement with caution. DB-Access does not prompt
you to verify that you want to delete the entire database. ♦
E/C You can use a simple database name in a program or host variable, or you can
use the full database server and database name. See “Database Name” on
page 4-47 for more information. ♦
Related Information
Related statements: CLOSE DATABASE, CREATE DATABASE, and CONNECT
+ DROP FUNCTION
IDS
Use the DROP FUNCTION statement to remove a user-defined function from
the database.
Syntax
Specific Name
IDS SPECIFIC FUNCTION p. 4-296
Usage
Dropping a user-defined function removes the text and executable versions
of the function from the database.
To use the DROP FUNCTION statement, you must be the owner of the user-
defined function or have the DBA privilege.
Examples
If you use parameter data types to identify a user-defined function, they
follow the function name, as in the following example:
DROP FUNCTION compare(int, int)
If you use the specific name for the user-defined function, you must use the
keyword SPECIFIC, as in the following example:
DROP SPECIFIC FUNCTION compare_point
You cannot drop an SPL function from within the same SPL function.
Related Information
Related statements: ALTER FUNCTION, CREATE FUNCTION, CREATE
FUNCTION FROM, DROP FUNCTION, DROP ROUTINE, and EXECUTE
FUNCTION
+
DROP INDEX
Use the DROP INDEX statement to remove an index.
Syntax
Usage
You must be the owner of the index or have the DBA privilege to use the
DROP INDEX statement.
The following example drops the index o_num_ix that joed owns. The
stores_demo database must be the current database.
DROP INDEX stores_demo:joed.o_num_ix
In this example, tabid and constraint_id are from the systables and
sysconstraints system catalog tables, respectively. The idxname (index
name) column in the sysconstraints table is then updated to reflect this
change. For example, the renamed index name might be something like:
“121_13” (quotes used to show the spaces).
If this index is a unique index with only referential constraints sharing it, the
index is downgraded to a duplicate index after it is renamed.
Related Information
Related statements: ALTER TABLE, CREATE INDEX, and CREATE TABLE
+ DROP OPCLASS
IDS
Use the DROP OPCLASS statement to remove an existing operator class from
the database.
Syntax
Usage
You must be the owner of the operator class or have the DBA privilege to use
the DROP OPCLASS statement.
The RESTRICT keyword causes DROP OPCLASS to fail if the database contains
indexes defined on the operator class you plan to drop. Therefore, before you
drop the operator class, you must use DROP INDEX to drop dependent
indexes.
Related Information
Related statement: CREATE OPCLASS
+
DROP PROCEDURE
Use the DROP PROCEDURE statement to remove a user-defined procedure
from the database.
Syntax
Usage
Dropping a user-defined procedure removes the text and executable versions
of the procedure.
To use the DROP PROCEDURE statement, you must be the owner of the
procedure or have the DBA privilege.
XPS In Extended Parallel Server, use the DROP PROCEDURE statement to drop
any SPL routine. Extended Parallel Server does not support the DROP
FUNCTION statement. ♦
IDS In Dynamic Server, for backward compatibility, you can use the DROP
PROCEDURE statement to drop an SPL function that was created with the
CREATE PROCEDURE statement.
Examples
If you use parameter data types to identify a user-defined procedure, they
follow the procedure name, as in the following example:
DROP PROCEDURE compare(int, int)
If you use the specific name for the user-defined procedure, you must use the
keyword SPECIFIC, as in the following example:
DROP SPECIFIC PROCEDURE compare_point
You cannot drop an SPL procedure from within the same SPL procedure.
IDS For backward compatibility, you can use this statement to drop an SPL
function that was created with the CREATE PROCEDURE statement. ♦
Related Information
Related statements: CREATE PROCEDURE, CREATE PROCEDURE FROM, DROP
FUNCTION, DROP ROUTINE, and EXECUTE PROCEDURE
+ DROP ROLE
IDS
Use the DROP ROLE statement to remove a previously created role.
Syntax
Usage
Either the DBA or a user to whom the role was granted with the WITH GRANT
OPTION can issue the DROP ROLE statement.
After a role is dropped, the privileges associated with that role, such as table-
level privileges or fragment-level privileges, are dropped, and a user cannot
grant or enable a role. If a user is using the privileges of a role when the role
is dropped, the user automatically loses those privileges.
Related Information
Related statements: CREATE ROLE, GRANT, REVOKE, and SET ROLE
For a discussion of how to use roles, see the Informix Guide to SQL: Tutorial.
+ DROP ROUTINE
IDS
Use the DROP ROUTINE statement to remove a user-defined routine (UDR)
from the database.
Syntax
Specific Name
SPECIFIC ROUTINE p. 4-296
Usage
Dropping a UDR removes the text and executable versions of the UDR from
the database.
This statement is useful when you do not know whether a UDR is a user-
defined function or a user-defined procedure. When you use this statement,
the database server drops the appropriate user-defined function or user-
defined procedure.
To use the DROP ROUTINE statement, you must be the owner of the UDR or
have the DBA privilege.
Restrictions
When you use this statement, the type of UDR cannot be ambiguous. The
UDR that you specify must refer to either a user-defined function or a user-
defined procedure. If either of the following conditions exist, the database
server returns an error:
■ The name (and parameters) that you specify apply to both a user-
defined procedure and a user-defined function
■ The specific name that you specify applies to both a user-defined
function and a user-defined procedure
Examples
If you use parameter data types to identify a UDR, they follow the UDR name,
as in the following example:
DROP ROUTINE compare(int, int)
If you use the specific name for the UDR, you must use the keyword SPECIFIC,
as in the following example:
DROP SPECIFIC ROUTINE compare_point
You cannot drop an SPL routine from within the same SPL routine.
Related Information
Related statements: CREATE FUNCTION, CREATE PROCEDURE, DROP
FUNCTION, DROP PROCEDURE, EXECUTE FUNCTION, and EXECUTE
PROCEDURE
Syntax
Usage
You must be the owner of the row type or have the DBA privilege to use the
DROP ROW TYPE statement.
You cannot drop a named-row type if the row type name is in use. You cannot
drop a named-row type when any of the following conditions are true:
The DROP ROW TYPE statement does not drop unnamed-row types.
The DROP ROW TYPE statement fails and returns an error message if:
Example
The following statement drops the row type named employee_t:
DROP ROW TYPE employee_t RESTRICT
Related Information
Related statement: CREATE ROW TYPE
For a description of the system catalog tables, see the Informix Guide to SQL:
Reference.
For a discussion of named-row types, see the Informix Guide to SQL: Tutorial.
+
DROP SYNONYM
Use the DROP SYNONYM statement to remove a previously defined
synonym.
Syntax
Usage
You must be the owner of the synonym or have the DBA privilege to use the
DROP SYNONYM statement.
The following statement drops the synonym nj_cust, which cathyg owns:
DROP SYNONYM cathyg.nj_cust
If a table is dropped, any synonyms that are in the same database as the table
and that refer to the table are also dropped.
Related Information
Related statement: CREATE SYNONYM
+
DROP TABLE
Use the DROP TABLE statement to remove a table, along with its associated
indexes and data.
Syntax
synonym CASCADE
RESTRICT
Usage
You must be the owner of the table or have the DBA privilege to use the DROP
TABLE statement.
XPS If you are using Extended Parallel Server, you cannot drop a table that
includes a dependent GK index unless the dependent index is entirely
dependent on the affected table. ♦
DB If you issue a DROP TABLE statement, DB-Access does not prompt you to
verify that you want to delete an entire table. ♦
When you drop a table, you do not remove any synonyms for the table that
were created in an external database. If you want to remove external
synonyms to the dropped table, you must do so manually with the DROP
SYNONYM statement.
IDS If the table is the supertable in an inheritance hierarchy, CASCADE drops all
of the subtables as well as the supertable. ♦
The CASCADE mode is the default mode of the DROP TABLE statement. You
can also specify this mode explicitly with the CASCADE keyword.
IDS Dropping a Table with Rows That Contain Opaque Data Types
Some opaque data types require special processing when they are deleted.
For example, if an opaque data type contains spatial or multi-
representational data, it might provide a choice of how to store the data:
inside the internal structure or, for very large objects, in a smart large object.
Related Information
Related statements: CREATE TABLE and DROP DATABASE
For a discussion of the data integrity of tables, see the Informix Guide to SQL:
Tutorial.
For a discussion of how to create a table, see the Informix Guide to Database
Design and Implementation.
+
DROP TRIGGER
Use the DROP TRIGGER statement to remove a trigger definition from a
database.
Syntax
Usage
You must be the owner of the trigger or have the DBA privilege to drop the
trigger.
Dropping a trigger removes the text of the trigger definition and the
executable trigger from the database.
Related Information
Related statements: CREATE TRIGGER
+ DROP TYPE
IDS
Use the DROP TYPE statement to remove an existing distinct or opaque data
type from the database.
Syntax
Usage
To drop a distinct or opaque type with the DROP TYPE statement, you must
be the owner of the data type or have the DBA privilege.
When you use the DROP TYPE statement, you remove the type definition
from the database (in the sysxtdtypes system catalog table). In general, this
statement does not remove any definitions for casts or support functions
associated with that data type.
Important: When you drop a distinct type, the database server automatically drops
the two explicit casts between the distinct type and the type on which it is based.
You cannot drop a distinct or opaque type if the database contains any casts,
columns, or user-defined functions whose definitions reference the type.
Related Information
Related statements: CREATE DISTINCT TYPE, CREATE OPAQUE TYPE, CREATE
ROW TYPE, DROP ROW TYPE, and CREATE TABLE
+
DROP VIEW
Use the DROP VIEW statement to remove a view from a database.
Syntax
Usage
You must be the owner of the view or have the DBA privilege to drop the
view.
When you drop a view or its synonym, you also drop all views that were
defined in terms of that view. You can also specify this default condition with
the CASCADE keyword.
When you use the RESTRICT keyword in the DROP VIEW statement, the drop
operation fails if any existing views are defined on view, which would be
abandoned in the drop operation.
You can query the sysdepend system catalog table to determine which views,
if any, depend on another view.
Related Information
Related statements: CREATE VIEW and DROP TABLE
E/C EXECUTE
IDS
Use the EXECUTE statement to run a previously prepared statement or set of
statements.
Syntax
EXECUTE statement_id
Usage
The EXECUTE statement passes a prepared SQL statement to the database
server for execution. The following example shows an EXECUTE statement
within an ESQL/C program:
EXEC SQL prepare del_1 from
'delete from customer
where customer_num = 119';
EXEC SQL execute del_1;
If the statement contained question mark (?) placeholders, you use the USING
clause to provide specific values for them before execution. For more infor-
mation, see the “USING Clause” on page 2-430.
You can execute any prepared statement except those in the following list:
■ The sqlca can reflect an error within the EXECUTE statement. For
example, when an UPDATE …WHERE… statement within a prepared
statement processes zero rows, the database server sets sqlca to 100.
■ The sqlca can reflect the success or failure of the executed statement.
Error Conditions with EXECUTE
If a prepared statement fails to access any rows, the database server returns
zero (0). In a multistatement prepare, if any statement in the following list
fails to access rows, the database server returns SQLNOTFOUND (100):
ANSI In an ANSI-compliant database, if you prepare and execute any of the state-
ments in the preceding list, and no rows are returned, the database server
returns SQLNOTFOUND (100). ♦
INTO Clause
Use the INTO clause to save the return values of the following SQL
statements:
INTO output_var
+ : indicator_var
INDICATOR indicator_var
DESCRIPTOR sqlda_pointer
The INTO clause provides a concise and efficient alternative to more compli-
cated and lengthy syntax. In addition, by placing values into variables that
can be displayed, the INTO clause simplifies and enhances your ability to
retrieve and display data values. For example, if you use the INTO clause, you
do not have to use a cursor to retrieve values from a table.
You can store the returned values into output variables, output SQL
descriptors, or output sqlda pointers.
You cannot select a null value from a table column and place that value into
an output variable. If you know in advance that a table column contains a
null value, after you select the data, check the indicator variable that is
associated with the column to determine if the value is null.
The following list describes the procedure for how to use the INTO clause
with the EXECUTE statement:
■ A host variable name (if the number and data type of the question
marks are known at compile time)
■ A system descriptor that identifies a system
■ A descriptor that is a pointer to an sqlda structure
Saving Values In Host or Program Variables
If you know the number of return values to be supplied at runtime and their
data types, you can define the values that the SELECT or EXECUTE FUNCTION
(or EXECUTE PROCEDURE) statement returns as host variables in your
program. You use these host variables with the INTO keyword, followed by
the names of the variables. These variables are matched with the return
values in a one-to-one correspondence, from left to right.
You must supply one variable name for each value that the SELECT or
EXECUTE FUNCTION (or EXECUTE PROCEDURE) returns. The data type of
each variable must be compatible with the corresponding return value of the
prepared statement.
The COUNT field corresponds to the number of values that the prepared
statement returns. The value of COUNT must be less than or equal to the
value of the occurrences that were specified when the system-descriptor area
was allocated with the ALLOCATE DESCRIPTOR statement. You can obtain the
value of a field with the GET DESCRIPTOR statement and set the value with
the SET DESCRIPTOR statement.
The sqld value specifies the number of output values that are described in
occurrences of sqlvar. This number must correspond to the number of values
that the SELECT or EXECUTE FUNCTION (or EXECUTE PROCEDURE)
statement returns.
For more information, refer to the sqlda discussion in the Informix ESQL/C
Programmer’s Manual.
Examples
The following example shows how to use the INTO clause with an EXECUTE
statement in ESQL/C:
EXEC SQL prepare sel1 from 'select fname, lname from customer
where customer_num =123';
EXEC SQL execute sel1 into :fname, :lname using :cust_num;
The following example shows how to use the INTO clause to return multiple
rows of data:
EXEC SQL BEGIN DECLARE SECTION;
int customer_num =100;
char fname[25];
EXEC SQL END DECLARE SECTION;
USING Clause
Use the USING clause to specify the values that are to replace question-mark
(?) placeholders in the prepared statement. Providing values in the EXECUTE
statement that replace the question-mark placeholders in the prepared
statement is sometimes called parameterizing the prepared statement.
USING parameter_var
+ : indicator_var
INDICATOR indicator_var
DESCRIPTOR sqlda_pointer
Each time that the EXECUTE statement is run, the values that the system-
descriptor area describes are used to replace question-mark (?) placeholders
in the PREPARE statement.
Each time the EXECUTE statement is run, the values that the descriptor
structure describes are used to replace question-mark (?) placeholders in the
PREPARE statement.
The sqld value specifies the number of input values that are described in
occurrences of sqlvar. This number must correspond to the number of
dynamic parameters in the prepared statement.
Related Information
Related statements: ALLOCATE DESCRIPTOR, DEALLOCATE DESCRIPTOR,
DECLARE, EXECUTE IMMEDIATE, FETCH, GET DESCRIPTOR, PREPARE, PUT,
and SET DESCRIPTOR
+
EXECUTE FUNCTION
Use the EXECUTE FUNCTION statement to execute a user-defined function.
Syntax
Usage
The EXECUTE FUNCTION statement invokes the named user-defined
function, specifies its arguments, and determines where the results are
returned.
Privileges
You must have the Execute privilege on the user-defined function.
INTO Clause
INTO data_var
E/C
: indicator_var
+
$ indicator_var
INDICATOR indicator_var
data_structure
You must specify an INTO clause with EXECUTE FUNCTION to name the
variables that receive the values that a user-defined function returns. If the
function returns more than one value, the values are returned into the list of
variables in the order in which you specify them.
If the EXECUTE FUNCTION statement stands alone (that is, it is not part of a
DECLARE statement and does not use the INTO clause), it must execute a
noncursor function. A noncursor function returns only one row of values.
The following example shows a SELECT statement in Informix ESQL/C:
EXEC SQL execute function cust_num(fname, lname,
company_name)
into :c_num;
If the SPL function returns more than one row or a collection data type, you
must access the rows or collection elements with a cursor.
Ext
To return more than one row of values, an external function must be defined
as an iterator function. For more information on how to write iterator
functions, see the DataBlade API Programmer’s Manual. ♦
SPL To return more than one row of values, an SPL function must include the
WITH RESUME keywords in its RETURN statement. For more information on
how to write SPL functions, see the Informix Guide to SQL: Tutorial. ♦
E/C In an Informix ESQL/C program, use the DECLARE statement to declare the
function cursor and the FETCH statement to fetch the rows individually from
the function cursor. You can put the INTO clause in the FETCH statement
rather than in the EXECUTE FUNCTION statement, but you cannot put it in
both. The following Informix ESQL/C code examples show different ways
you can use the INTO clause:
SPL In an SPL routine, if a SELECT returns more than one row, you must use the
FOREACH statement to access the rows individually. The INTO clause of the
SELECT statement holds the fetched values. For more information, see
“FOREACH” on page 3-30. ♦
Alternatively, you can declare a cursor for the EXECUTE FUNCTION statement
without first preparing the statement and include the INTO clause in the
EXECUTE FUNCTION when you declare the cursor. Then open the cursor, and
fetch the return values from the cursor without using the INTO clause of the
FETCH statement.
For more information about how to execute SPL functions dynamically, see
the Informix Guide to SQL: Tutorial.
THREADS
You must associate this function with the equivalent of a cursor in the Java
language.
Related Information
Related statements: CALL, CREATE FUNCTION, CREATE FUNCTION FROM,
DROP FUNCTION, DROP ROUTINE, EXECUTE PROCEDURE, and FOREACH
+ EXECUTE IMMEDIATE
E/C
Use the EXECUTE IMMEDIATE statement to perform the functions of the
PREPARE, EXECUTE, and FREE statements.
Syntax
Quoted
EXECUTE IMMEDIATE String
p. 4-260
statement_var
Usage
The EXECUTE IMMEDIATE statement makes it easy to execute dynamically a
single simple SQL statement that is constructed during program execution.
For example, you can obtain the name of a database from program input,
construct the DATABASE statement as a program variable, and then use
EXECUTE IMMEDIATE to execute the statement, which opens the database.
The quoted string is a character string that includes one or more SQL
statements. The string, or the contents of statement_var, is parsed and
executed if correct; then all data structures and memory resources are
released immediately. In the usual method of dynamic execution, these
functions are distributed among the PREPARE, EXECUTE, and FREE
statements.
Related Information
Related statements: EXECUTE, FREE, and PREPARE
For a discussion of quick execution, see the Informix Guide to SQL: Tutorial.
+ EXECUTE PROCEDURE
Use the EXECUTE PROCEDURE statement to execute a user-defined
procedure.
Syntax
IDS
SQLJ Built-In Procedures
Java p. 2-446
Usage
The EXECUTE PROCEDURE statement invokes the named user-defined
procedure and specifies its arguments.
IDS In Dynamic Server, for backward compatibility, you can use the EXECUTE
PROCEDURE statement to execute an SPL function that was created with the
CREATE PROCEDURE statement. ♦
E/C In ESQL/C, if the EXECUTE PROCEDURE statement returns more than one
row, it must be enclosed within an SPL FOREACH loop or accessed through a
cursor. ♦
If an SPL function returns more than one value, the values are returned into
the list of variables in the order in which you specify them. If an SPL function
returns more than one row or a collection data type, you must access the rows
or collection elements with a cursor.
If the SPL variable names an SPL routine that returns a value (an SPL
function), include the INTO clause of EXECUTE PROCEDURE to specify a
receiving variable (or variables) to hold the value (or values) that the SPL
function returns.
For more information on how to execute SPL procedures dynamically, see the
Informix Guide to SQL: Tutorial. ♦
Causes of Errors
The EXECUTE PROCEDURE statement returns an error under the following
conditions:
SQLJ.INSTALL_JAR
p. 2-447
SQLJ.REPLACE_JAR
p. 2-449
SQLJ.REMOVE_JAR
p. 2-450
SQLJ.ALTER_JAVA_PATH
p. 2-451
SQLJ.SETUDTEXTNAME
p. 2-453
SQLJ.UNSETUDTEXTNAME
p. 2-454
The SQLJ built-in procedures are stored in the sysprocedures catalog table.
They are grouped under the sqlj schema.
Tip: For any Java static method, the first built-in procedure that you execute must be
the install_jar() procedure. You must install the jar file before you can create a UDR
or map a user-defined data type to a Java type. Similarly, you cannot use any of the
other SQLJ built-in procedures until you have used install_jar().
sqlj.install_jar
Use the install_jar() procedure to install a Java jar file in the current database
and assign it a jar identifier.
For example, consider a Java class Chemistry which contains the following
static method explosiveReaction():
public static int explosiveReaction(int ingredient);
Suppose that the Chemistry class resides in the following jar file on the server
computer:
/students/data/Courses.jar
You can install all classes in the Courses.jar jar file in the current database
with the following call to the install_jar() procedure:
EXECUTE PROCEDURE
sqlj.install_jar("file://students/data/Courses.jar",
"course_jar")
The install_jar() procedure assigns the jar ID, course_jar, to the Courses.jar
file that it has installed in the current database.
After you define jar ID in the database, you can use that jar ID when you
create and execute a UDR written in Java.
sqlj.replace_jar
Use the replace_jar() procedure to replace a previously installed jar file with
a new version. When you use this syntax, you provide only the new jar file
and assign it to the jar ID for which you want to replace the file.
If you attempt to replace a jar file that is referenced by one or more UDRs, the
database server generates an error. You must drop the referencing UDRs
before replacing the jar file.
For example, the following call replaces the Courses.jar file, which had previ-
ously been installed for the course_jar identifier, with the Subjects.jar file:
EXECUTE PROCEDURE
sqlj.replace_jar("file://students/data/Subjects.jar",
"course_jar")
Before you replace the Course.jar file, you must drop the user-defined
function sql_explosive_reaction() with the DROP FUNCTION (or DROP
ROUTINE) statement.
sqlj.remove_jar
Use the remove_jar() procedure to remove a previously installed jar file from
the current database.
deploy
If you attempt to remove a jar file that is referenced by one or more UDRs, the
database server generates an error. You must drop the referencing UDRs
before replacing the jar file.
For example, the following SQL statements remove the jar file associated with
the course_jar jar id:
DROP FUNCTION sql_explosive_reaction;
EXECUTE PROCEDURE sqlj.remove_jar("course_jar")
sqlj.alter_java_path
Use the alter_java_path() procedure to specify the jar-file path to use when the
routine manager resolves related Java classes for the jar file of a UDR written
in Java.
SQLJ.ALTER_JAVA_PATH
The jar IDs that you specify, (the jar ID for which you are altering the jar-file
path and the resolution jar ID) must have been installed with the
sqlj.install_jar procedure.
When you invoke a UDR written in Java, the routine manager attempts to
load the Java class in which the UDR resides. At this time, it must resolve the
references that this Java class makes to other Java classes. The three types of
such class references are:
The routine manager checks the jar-file path for class references after it
performs the implicit type 1 and type 2 resolutions. If you want a Java class
to be loaded from the jar file that the jar-file path specifies, make sure the Java
class is not present in the JVPCLASSPATH configuration parameter.
Otherwise, the system loader picks up that Java class first, which might result
in a different class being loaded than what you expect.
The routine manager attempts to load the class Chemistry. It uses the path
that the call to alter_java_path() specifies to resolve any class references.
Therefore, it checks the classes that are in the professor package of the jar file
that prof_jar identifies.
sqlj.setUDTExtName
Use the setUDTExtName() procedure to define the mapping between a user-
defined data type and a Java class.
package_id .
To look up the Java class for a user-defined data type, the database server
searches in the jar-file path, which the alter_java_path() procedure has
specified. For more information on the jar-file path, see“sqlj.alter_java_path”
on page 2-451.
On the client side, the driver looks into the CLASSPATH path on the client
environment before it asks the database server for the name of the Java class.
sqlj.unsetUDTExtName
Use the remove_jar() procedure to remove the mapping from a user-defined
data type to a Java class.
SQLJ.SETUDTEXTNAME ( data_type )
Related Information
Related statements: CREATE FUNCTION, CREATE PROCEDURE, EXECUTE
FUNCTION, GRANT, CALL, FOREACH, and LET
E/C
FETCH
Use the FETCH statement to move a cursor to a new row in the active set and
to retrieve the row values from memory.
Syntax
FIRST data_structure
LAST
CURRENT
USING SQL DESCRIPTOR 'descriptor'
RELATIVE position_num
descriptor_var
+ DESCRIPTOR sqlda_pointer
-
position_num_var
ABSOLUTE row_position
row_position_var
Usage
The way the database server creates and stores members of the active set and
then fetches rows from the active set differs depending on whether the cursor
is a sequential cursor or a scroll cursor.
When the program opens a sequential cursor, the database server processes
the query to the point of locating or constructing the first row of data. The
goal of the database server is to tie up as few resources as possible.
Because the sequential cursor can retrieve only the next row, the database
server can frequently create the active set one row at a time. On each FETCH
operation, the database server returns the contents of the current row and
locates the next row. This one-row-at-a-time strategy is not possible if the
database server must create the entire active set to determine which row is
the first row (as would be the case if the SELECT statement included an
ORDER BY clause).
CURRENT Retrieves the current row in the active set (the same row as
returned by the preceding FETCH statement from the scroll
cursor)
RELATIVE Retrieves the nth row, relative to the current cursor position
in the active set, where position_num (or position_num_var)
supplies n
A negative value indicates the nth row prior to the current
cursor position. If position_num is 0, the current row is
fetched.
ABSOLUTE Retrieves the nth row in the active set, where row_position
(or row_position_var) supplies n
Absolute row positions are numbered from 1.
The following ESQL/C examples illustrate the FETCH statement with a scroll
cursor:
EXEC SQL fetch previous q_curs into :orders;
Tip: Do not confuse row-position values with rowid values. A rowid value is based
on the position of a row in its table and remains valid until the table is rebuilt. A row-
position value (a value introduced by the ABSOLUTE keyword) is based on the
position of the row in the active set of the cursor; the next time the cursor is opened,
different rows might be selected.
The first time a row is fetched, the database server copies it into the
temporary table as well as returning it to the program. When a row is fetched
for the second time, it can be taken from the temporary table. This scheme
uses the fewest resources in case the program abandons the query before it
fetches all the rows. Rows that are never fetched are usually not created or are
saved in a temporary table.
You can use this method only when you write the SELECT or EXECUTE
FUNCTION (or EXECUTE PROCEDURE) statement as part of the cursor decla-
ration (see “DECLARE” on page 2-349).
If you prepare a SELECT statement, the SELECT cannot include the INTO clause
so you must use the INTO clause of the FETCH statement.
When you create a SELECT statement dynamically, you cannot use an INTO
clause because you cannot name host variables in a prepared statement. If
you are certain of the number and data type of values in the select list, you
can use an INTO clause in the FETCH statement. However, if user input
generated the query, you might not be certain of the number and data type of
values that are being selected. In this case, you must use a system descriptor
or sqlda pointer structure
main()
{
EXEC SQL connect to'stores_demo';
printf("Enter 2-letter state code: ");
scanf ("%s", wanted_state);
row_count++;
EXEC SQL fetch cust into :cust_rec[row_count];
}
printf ("\n");
EXEC SQL close cust;
EXEC SQL free cust;
}
You can fetch into a program-array element only by using an INTO clause in
the FETCH statement. When you are declaring a cursor, do not refer to an
array element within the SQL statement.
Tip: If you are certain of the number and data type of values in the select list, you can
use an INTO clause in the FETCH statement.
The keywords USING SQL DESCRIPTOR introduce the name of the system-
descriptor area into which you fetch the contents of a row or the return values
of a user-defined function. You can then use the GET DESCRIPTOR statement
to transfer the values that the FETCH statement returns from the system-
descriptor area into host variables.
Tip: If you are certain of the number and data type of values in the select list, you can
use an INTO clause in the FETCH statement. For more information, see “Using the
INTO Clause of FETCH” on page 2-462.
The sqld value specifies the number of output values that are described in
occurrences of the sqlvar structures of the sqlda structure. This number must
correspond to the number of return values from the prepared statement.
■ When you set the isolation level to Repeatable Read, each row you
fetch is locked with a read lock to keep it from changing until the
cursor closes or the current transaction ends. Other programs can
also read the locked rows.
■ When you set the isolation level to Cursor Stability, the current row
is locked.
ANSI ■ In an ANSI-compliant database, an isolation level of Repeatable Read
is the default; you can set it to something else. ♦
■ When you are fetching through an update cursor (one that is
declared FOR UPDATE), each row you fetch is locked with a
promotable lock. Other programs can read the locked row, but no
other program can place a promotable or write lock; therefore, the
row is unchanged if another user tries to modify it using the WHERE
CURRENT OF clause of an UPDATE or DELETE statement.
When you modify a row, the lock is upgraded to a write lock and remains
until the cursor is closed or the transaction ends. If you do not modify the
row, the behavior of the database server depends on the isolation level you
have set. The database server releases the lock on an unchanged row as soon
as another row is fetched, unless you are using Repeatable Read isolation (see
“SET ISOLATION” on page 2-736).
Important: You can hold locks on additional rows even when Repeatable Read
isolation is not in use or is unavailable. Update the row with unchanged data to hold
it locked while your program is reading other rows. You must evaluate the effect of
this technique on performance in the context of your application, and you must be
aware of the increased potential for deadlock.
When you use explicit transactions, be sure that a row is both fetched and
modified within a single transaction; that is, both the FETCH statement and
the subsequent UPDATE or DELETE statement must fall between a BEGIN
WORK statement and the next COMMIT WORK statement.
To fetch elements, one at a time, from a collection cursor, use the FETCH
statement and the INTO clause. The FETCH statement identifies the collection
cursor that is associated with the collection variable. The INTO clause
identifies the host variable that holds the element value that is fetched from
the collection cursor. The data type of the host variable in the INTO clause
must match the element type of the collection.
Suppose you have a table called children with the following structure:
CREATE TABLE children
(
age SMALLINT,
name VARCHAR(30),
fav_colors SET(VARCHAR(20) NOT NULL),
)
The following ESQL/C code fragment shows how to fetch elements from the
child_colors collection variable:
EXEC SQL BEGIN DECLARE SECTION;
client collection child_colors;
varchar one_favorite[21];
char child_name[31] = "marybeth";
EXEC SQL END DECLARE SECTION;
do
{
EXEC SQL fetch colors_curs into :one_favorite;
...
} while (SQLCODE == 0)
Once you have fetched a collection element, you can modify the element with
the UPDATE or DELETE statements. For more information, see the UPDATE
and DELETE statements in this manual. You can also insert new elements into
the collection variable with an INSERT statement. For more information, see
the INSERT statement.
You can also use SQLCODE of sqlca to determine the same results.
Related Information
Related statements: ALLOCATE DESCRIPTOR, CLOSE, DEALLOCATE
DESCRIPTOR, DECLARE, DESCRIBE, GET DESCRIPTOR, OPEN, PREPARE, SET
DEFERRED_PREPARE, and SET DESCRIPTOR
For a task-oriented discussion of the FETCH statement, see the Informix Guide
to SQL: Tutorial.
For more information about concepts relating to the FETCH statement, see the
Informix ESQL/C Programmer’s Manual.
+ FLUSH
E/C
Use the FLUSH statement to force rows that a PUT statement buffered to be
written to the database.
Syntax
FLUSH cursor_id
cursor_id_var
Usage
The PUT statement adds a row to a buffer, and the buffer is written to the
database when it is full. Use the FLUSH statement to force the insertion when
the buffer is not full.
If the program terminates without closing the cursor, the buffer is left
unflushed. Rows placed into the buffer since the last flush are lost. Do not
expect the end of the program to close the cursor and flush the buffer
automatically.
When you use data buffering with an insert cursor, you do not discover
errors until the buffer is flushed. For example, an input value that is incom-
patible with the data type of the column for which it is intended is discovered
only when the buffer is flushed. When an error is discovered, rows in the
buffer that are located after the error are not inserted; they are lost from
memory.
The SQLCODE field is set either to an error code or to zero (0) if no error
occurs. The third element of the sqlerrd array is set to the number of rows
that are successfully inserted into the database:
Related Information
Related statements: CLOSE, DECLARE, OPEN, and PREPARE
For information about the sqlca structure, see the Informix ESQL/C
Programmer’s Manual.
+ FREE
E/C
Use the FREE statement to release resources that are allocated to a prepared
statement or to a cursor.
Syntax
FREE cursor_id
cursor_id_var
statement_id
statement_id_var
Usage
The FREE statement releases the resources that the database server and appli-
cation-development tool allocated for a prepared statement or a declared
cursor.
Freeing a Statement
If you prepared a statement (but did not declare a cursor for it), FREE
statement_id (or statement_id_var) releases the resources in both the
application development tool and the database server.
After you free a statement, you cannot execute it or declare a cursor for it
until you prepare it again.
The following ESQL/C example shows the sequence of statements that are
used to release the resources of an explicitly prepared statement. The first
FREE statement in this example frees the cursor. The second FREE statement
in this example frees the prepared statement.
sprintf(demoselect, "%s %s",
"select * from customer ",
"where customer_num between 100 and 200");
EXEC SQL prepare sel_stmt from :demoselect;
EXEC SQL declare sel_curs cursor for sel_stmt;
EXEC SQL open sel_curs;
.
.
.
EXEC SQL close sel_curs;
EXEC SQL free sel_curs;
EXEC SQL free sel_stmt;
Freeing a Cursor
If you declared a cursor for a prepared statement, freeing the cursor releases
only the resources in the database server. To release the resources for the
statement in the application-development tool, use FREE statement_id (or
statement_id_var).
If a cursor is not declared for a prepared statement, freeing the cursor releases
the resources in both the application-development tool and the database
server.
For an example of a FREE statement that frees a cursor, see the second
example in “Freeing a Statement” on page 2-473.
Related Information
Related statements: CLOSE, DECLARE, EXECUTE, EXECUTE IMMEDIATE,
OPEN, PREPARE, and SET AUTOFREE
For a task-oriented discussion of the FREE statement, see the Informix Guide to
SQL: Tutorial.
+ GET DESCRIPTOR
E/C
Use the GET DESCRIPTOR statement to accomplish the following separate
tasks:
Syntax
descriptor_var
,
VALUE item_num Described
Item Info
item_num_var
Described
Item Info
field_var = TYPE
LENGTH
PRECISION
SCALE
NULLABLE
INDICATOR
NAME
DATA
IDATA
ITYPE
ILENGTH
+
IDS
EXTYPEID
EXTYPENAME
EXTYPEOWNERNAME
EXTYPELENGTH
EXTYPEOWNERLENGTH
SOURCEID
SOURCETYPE
Usage
IDS Use the GET DESCRIPTOR statement after you have described EXECUTE
FUNCTION, INSERT, SELECT, or UPDATE statements with the
DESCRIBE...USING SQL DESCRIPTOR statement. ♦
XPS Use the GET DESCRIPTOR statement after you have described EXECUTE
PROCEDURE, INSERT, or SELECT statements with the DESCRIBE...USING SQL
DESCRIPTOR statement. ♦
The host variables that are used in the GET DESCRIPTOR statement must be
declared in the BEGIN DECLARE SECTION of a program.
If an error occurs during the assignment to any identified host variable, the
contents of the host variable are undefined.
The item_num must be greater than zero (0) and less than the number of item
descriptors that were specified when the system-descriptor area was
allocated with the ALLOCATE DESCRIPTOR statement.
The value that the database server returns into the TYPE field is a defined
integer. To evaluate the data type that is returned, test for a specific integer
value. For additional information about integer data type values, see “Setting
the TYPE or ITYPE Field” on page 2-724.
X/O In X/Open mode, the X/Open code is returned to the TYPE field. You cannot
mix the two modes because errors can result. For example, if a particular data
type is not defined under X/Open mode but is defined for Informix products,
executing a GET DESCRIPTOR statement can result in an error.
The following ESQL/C example shows how you can copy data from the
DATA field into a host variable (result) after a fetch. For this example, it is
predetermined that all returned values are the same data type.
EXEC SQL get descriptor 'demodesc' :desc_count = count;
.
.
.
EXEC SQL fetch democursor using sql descriptor 'demodesc';
for (i = 1; i <= desc_count; i++)
{
if (sqlca.sqlcode != 0) break;
EXEC SQL get descriptor 'demodesc' value :i :result = DATA;
printf("%s ", result);
}
printf("\n");
This information is identical for ILENGTH. Use ILENGTH when you create a
dynamic program that does not comply with the X/Open standard.
■ The EXTYPEID field stores the extended ID for the opaque type.
This integer value corresponds to a value in the extended_id column
of the sysxtdtypes system catalog table.
■ The EXTYPENAME field stores the name of the opaque type.
This character value corresponds to a value in the name column of
the row with the matching extended_id value in the sysxtdtypes
system catalog table.
■ The EXTYPELENGTH field stores the length of the opaque-type name.
This integer value is the length, in bytes, of the name of the opaque
type.
■ The EXTYPEOWNERNAME field stores the name of the opaque-type
owner.
This character value corresponds to a value in the owner column of
the row with the matching extended_id value in the sysxtdtypes
system catalog table.
■ The EXTYPEOWNERLENGTH field stores the length of the value in
the EXTTYPEOWNERNAME field.
This integer value is the length, in bytes, of the owner name for the
opaque type.
Use these field names with the GET DESCRIPTOR statement to obtain infor-
mation about an opaque column.
■ The SOURCEID field stores the extended identifier for the source data
type.
This integer value corresponds to a value in the source column for
the row of the sysxtdtypes system catalog table whose extended_id
value matches that of the distinct type you are setting. This field is
only set if the source data type is an opaque data type.
■ The SOURCETYPE field stores the data type constant for the source
data type.
This value is the data type constant (from the sqltypes.h file) for the
data type of the source type for the distinct type. The codes for the
SOURCETYPE field are listed in the description of the TYPE field in the
SET DESCRIPTOR statement. (For more information, see “Setting the
TYPE or ITYPE Field” on page 2-724). This integer value must corre-
spond to the value in the type column for the row of the sysxtdtypes
system catalog table whose extended_id value matches that of the
distinct type you are setting.
Use these field names with the GET DESCRIPTOR statement to obtain infor-
mation about a distinct-type column.
Related Information
Related statements: ALLOCATE DESCRIPTOR, DEALLOCATE DESCRIPTOR,
DECLARE, DESCRIBE, EXECUTE, FETCH, OPEN, PREPARE, PUT, and SET
DESCRIPTOR
For more information on the sysxtdtypes system catalog table, see of the
Informix Guide to SQL: Reference.
+ GET DIAGNOSTICS
E/C Use the GET DIAGNOSTICS statement to return diagnostic information about
executing an SQL statement. The GET DIAGNOSTICS statement uses one of
two clauses, as described in the following list:
Syntax
Statement
GET DIAGNOSTICS Clause
p. 2-489
EXCEPTION
Clause
p. 2-491
Usage
The GET DIAGNOSTICS statement retrieves selected status information from
the diagnostics area and retrieves either count and overflow information or
information on a specific exception.
The first two characters of the SQLSTATE status code indicate a class. The last
three characters of the SQLSTATE code indicate a subclass. Figure 2-1 shows
the structure of the SQLSTATE code. This example uses the value 08001,
where 08 is the class code and 001 is the subclass code. The value 08001
represents the error unable to connect with database environment.
Figure 2-1
0 8 0 0 1 Structure of the
SQLSTATE Code
The following table is a quick reference for interpreting class code values.
00 Success
02 No data found
00 000 Success
Statement Clause
status_var = MORE
NUMBER
ROW_COUNT
ESQL/C
Host Variable
Field Name Keyword Field Data Type Field Contents Data Type
EXCEPTION Clause
exception_var
CONNECTION_ALIAS
MESSAGE_LENGTH
MESSAGE_TEXT
RETURNED_SQLSTATE
SERVER_NAME
SUBCLASS_ORIGIN
The host-variable data type must be the same as that of the requested field.
The seven exception information fields are represented by the keywords
described in the following table.
ESQL/C
Host Variable
Field Name Keyword Field Data Type Field Contents Data Type
The SERVER_NAME field retains the value set in the previous SQL statement.
If any of the preceding conditions occur on the first SQL statement that
executes, the SERVER_NAME field is blank.
SET CONNECTION Contains the name of the database server to which you
switch or fail to switch
DISCONNECT Contains the name of the database server from which you
disconnect or fail to disconnect
If you disconnect and then you execute a DISCONNECT
statement for a connection that is not current, the
SERVER_NAME field remains unchanged.
The CONNECTION_NAME field retains the value set in the previous SQL
statement. If any of the preceding conditions occur on the first SQL statement
that executes, the CONNECTION_NAME field is blank.
DATABASE Statement
When you execute a DATABASE statement, the CONNECTION_NAME field is
blank.
printf("---------------------------------");
printf("-------------------------\n");
printf("SQLSTATE: %s\n",SQLSTATE);
printf("SQLCODE: %d\n", SQLCODE);
printf("\n");
{
EXEC SQL get diagnostics exception :i
:sqlstate_code = RETURNED_SQLSTATE,
:class_id = CLASS_ORIGIN, :subclass_id = SUBCLASS_ORIGIN,
:message = MESSAGE_TEXT, :messlen = MESSAGE_LENGTH;
printf("- - - - - - - - - - - - - - - - - - - -\n");
printf("EXCEPTION %d: SQLSTATE=%s\n", i,
sqlstate_code);
message[messlen-1] ='\0';
printf("MESSAGE TEXT: %s\n", message);
j = stleng(class_id);
while((class_id[j] == '\0') ||
(class_id[j] == ' '))
j--;
class_id[j+1] = '\0';
printf("CLASS ORIGIN: %s\n",class_id);
j = stleng(subclass_id);
while((subclass_id[j] == '\0') ||
(subclass_id[j] == ' '))
j--;
subclass_id[j+1] = '\0';
printf("SUBCLASS ORIGIN: %s\n",subclass_id);
}
printf("---------------------------------");
printf("-------------------------\n");
}
Related Information
For a task-oriented discussion of error handling and the SQLSTATE variable,
see the Informix Guide to SQL: Tutorial.
GRANT
Use the GRANT statement to:
Syntax
Routine-Level
Privileges
p. 2-513
Language-Level
IDS Privileges
p. 2-516
Role
IDS Name
p. 2-518
Usage
The GRANT statement extends privileges to other users that would normally
accrue only to the DBA or to the creator of an object. Later GRANT statements
do not affect privileges already granted to a user.
You can grant privileges to a previously created role. You can grant a role to
individual users or to another role.
Privileges you grant remain in effect until you cancel them with a REVOKE
statement. Only the grantor of a privilege can revoke that privilege. The
grantor is normally the person who issues the GRANT statement. To transfer
the right to revoke, name another user as grantor when you issue a GRANT
statement.
The keyword PUBLIC extends a GRANT to all users. If you want to restrict
privileges to a particular user that public already has, you must first revoke
the right of public to those privileges.
Database-Level Privileges
CONNECT
RESOURCE
DBA
When you create a database with the CREATE DATABASE statement, you are
the owner. As the database owner, you automatically receive all database-
level privileges. The database remains inaccessible to other users until you,
as DBA, grant database privileges.
Database access levels are, from lowest to highest, Connect, Resource, and
DBA. Use the corresponding keyword to grant a level of access privilege.
Privilege Functions
CONNECT Lets you query and modify data. You can modify the database
schema if you own the database object you want to modify. Any
user with the Connect privilege can perform the following
functions:
■ Connect to the database with the CONNECT statement or
another connection statement
■ Execute SELECT, INSERT, UPDATE, and DELETE statements,
provided the user has the necessary table-level privileges
■ Create views, provided the user has the Select privilege on the
underlying tables
■ Create synonyms
■ Create temporary tables and create indexes on the temporary
tables
■ Alter or drop a table or an index, provided the user owns the
table or index (or has Alter, Index, or References privileges on
the table)
■ Grant privileges on a table or view, provided the user owns the
table (or was given privileges on the table with the WITH
GRANT OPTION keyword)
RESOURCE Lets you extend the structure of the database. In addition to the
capabilities of the Connect privilege, the holder of the Resource
privilege can perform the following functions:
■ Create new tables
■ Create new indexes
■ Create new UDRs
■ Create new data types
(1 of 2)
Privilege Functions
DBA Has all the capabilities of the Resource privilege and can perform
the following functions:
■ Grant any database-level privilege, including the DBA privilege,
to another user
■ Grant any table-level privilege to another user
■ Grant any table-level privilege to a role
■ Grant a role to a user or to another role
■ Execute the SET SESSION AUTHORIZATION statement
■ Use the NEXT SIZE keywords to alter extent sizes in the system
catalog
■ Insert, delete, or update rows of any system catalog table except
systables
■ Drop any database object, regardless of its owner
■ Create tables, views, and indexes, and specify another user as
owner of the database objects
■ Restrict the Execute privilege to DBAs when registering a UDR
■ Execute the DROP DATABASE statement
■ Execute the DROP DISTRIBUTIONS option of the UPDATE
STATISTICS statement
(2 of 2)
User informix has the privilege required to alter tables in the system catalog,
including the systables table.
Warning: Although the user informix and DBAs can modify most system catalog
tables (only user informix can modify systables), Informix strongly recommends
that you do not update, delete, or alter any rows in them. Modifying the system
catalog tables can destroy the integrity of the database.
The following example uses the PUBLIC keyword to grant the Connect
privilege on the currently active database to all users:
GRANT CONNECT TO PUBLIC
Table-Level Privileges
When you create a table with the CREATE TABLE statement, you are the table
owner and automatically receive all table-level privileges. You cannot
transfer table ownership to another user, but you can grant table-level privi-
leges to another user or to a role.
Table
ALL ON Reference
p. 2-509
PRIVILEGES
,
INSERT
DELETE
SELECT
,
+
( column )
UPDATE
,
+
( column )
REFERENCES
,
+
( column )
INDEX
ALTER
IDS
UNDER
The table that follows lists keywords for granting table-level privileges.
Privilege Purpose
Privilege Purpose
ALTER Lets you add or delete columns, modify column data types,
add or delete constraints, change the locking mode of the table
from PAGE to ROW, or add or drop a corresponding row type
name for your table.
Also lets you set the database object mode of unique indexes
and constraints to the enabled, disabled, or filtering mode. In
addition, this privilege lets you set the database object mode
of nonunique indexes and triggers to the enabled or disabled
modes.
You must have the Resource privilege to use the Alter
privilege. In addition, you also need the Usage privilege for
any user-defined type affected by the ALTER TABLE
statement.
Examples
Some simple examples can help to illustrate how table-level privileges are
granted with the GRANT statement.
To grant the same privileges as those above to all authorized users, use the
keyword PUBLIC as shown in the following example:
GRANT DELETE, SELECT, UPDATE (customer_num, fname, lname)
ON customer TO PUBLIC
After receiving the UNDER privilege on table tab1, user john can create one
or more subtables under tab1.
For example, assume that the user ted has the Select and Insert privileges on
the customer table with the authority to grant those privileges to other users.
User ted wants to grant all table-level privileges to user tania. So user ted
issues the following GRANT statement:
GRANT ALL ON customer TO tania
This statement executes successfully but returns SQLSTATE code 01007 for
the following reasons:
If the table owner grants ALL privileges on a traditional relational table and
later changes that table to a typed table, the table owner must explicitly grant
the Under privilege to allow other users to create subtables under it.
Table Reference
You grant table-level privileges directly by referencing the table name or an
existing synonym. You can also grant table-level privileges on a view.
table
view
synonym
The table, view, or synonym on which you grant privileges must reside in the
current database.
To allow access to only certain users, explicitly revoke those privileges public
automatically receives and then grant only those you want, as the following
example shows:
REVOKE ALL ON customer FROM PUBLIC;
GRANT ALL ON customer TO john, mary;
GRANT SELECT (fname, lname, company, city)
ON customer TO PUBLIC
ANSI If you create a table in an ANSI-compliant database, only you, as table owner,
have any table-level privileges until you explicitly grant privileges to
others. ♦
Privileges on a View
You must have at least the Select privilege on a table or columns to create a
view on that table.
For views that reference only tables in the current database, if the owner of a
view loses the Select privilege on any table underlying the view, the view is
dropped.
You have the same privileges for the view that you have for the table or tables
contributing data to the view. For example, if you create a view from a table
to which you have only Select privileges, you can select data from your view
but you cannot delete or update data.
When you create a view, only you have access to table data through that view.
Even users who have privileges on the base table of the view do not automat-
ically receive privileges for the view.
You can grant (or revoke) privileges on a view only if you are the owner of
the underlying tables or if you received these privileges on the table with the
right to grant them (the WITH GRANT OPTION keyword). You must explicitly
grant those privileges within your authority; public does not automatically
receive privileges on a view.
The creator of a view can explicitly grant Select, Insert, Delete, and Update
privileges for the view to other users or to a role name. You cannot grant
Index, Alter, Under, or References privileges on a view (or the All privilege
because All includes Index, References, and Alter).
To find out what privileges exist on a particular type, check the sysxtdtypes
system catalog table for the owner name and the sysxtdtypeauth system
catalog table for additional type privileges that might have been granted. For
more information on system catalog tables, see the Informix Guide to SQL:
Reference.
USAGE Privilege
You own a user-defined data type that you create. As owner, you automati-
cally receive the Usage privilege on that data type and can grant the Usage
privilege to others so that they can reference the type name or reference data
of that type in SQL statements. DBAs can also grant the Usage privilege for
user-defined data types.
If you grant the Usage privilege to a user or role that has Alter privileges, that
person can add a column to the table that contains data of your user-defined
type.
Without a GRANT statement, any user can create SQL statements that contain
built-in data types. By contrast, a user must receive an explicit Usage
privilege from a GRANT statement to use a distinct data type, even if the
distinct type is based on a built-in type.
UNDER Privilege
You own a named-row type that you create. If you want other users to be able
to create subtypes under this named-row type, you must grant these users
the Under privilege on your named-row type.
For example, suppose that you have created a row type named rtype1:
CREATE ROW TYPE rtype1
(cola INT, colb INT)
If you want another user named kathy to be able to create a subtype under
this named-row type, you must grant the Under privilege on this named-row
type to user kathy:
GRANT UNDER on rtype1 to kathy
Now user kathy can create another row type under the rtype1 row type even
though kathy is not the owner of the rtype1 row type:
CREATE ROW TYPE rtype2
(colc INT, cold INT)
UNDER rtype1
For more information about named-row types, see “CREATE ROW TYPE”
on page 2-216, the discussion of data types in the Informix Guide to SQL:
Reference, and the discussion of data types in the Informix Guide to Database
Design and Implementation.
Routine-Level Privileges
When you create a user-defined routine (UDR) with the CREATE FUNCTION
or CREATE PROCEDURE statement, you own, and automatically receive the
Execute privilege on that UDR.
The Execute privilege allows you to invoke the UDR with an EXECUTE
FUNCTION or EXECUTE PROCEDURE statement, whichever is appropriate, or
with a CALL statement in an SPL routine. The Execute privilege also allows
you to use a user-defined function in an expression, as in the following
example:
SELECT * FROM table WHERE in_stock(partnum) < 20
EXECUTE ON SPL_routine
IDS
PROCEDURE routine ( )
FUNCTION
Routine Parameter List
ROUTINE p. 4-286
Specific Name
SPECIFIC PROCEDURE p. 4-296
FUNCTION
ROUTINE
■ If you have DBA-level privileges, you can use the DBA keyword of
CREATE FUNCTION or CREATE PROCEDURE to restrict the default
Execute privilege to users with the DBA database-level privilege. You
must explicitly grant the Execute privilege on that UDR to users who
do not have the DBA privilege.
■ If you have the Resource database-level privilege, but not the DBA
privilege, you cannot use the DBA keyword when you create a UDR:
❑ When you create a UDR in a database that is not ANSI compliant,
public can execute that UDR. You do not need to issue a GRANT
statement for the Execute privilege.
❑ The NODEFDAC environment variable, when set to yes,
prevents public from executing your UDR until you explicitly
grant the Execute privilege.
ANSI ■ In an ANSI-compliant database, the creator of a UDR must explicitly
grant the Execute privilege on that UDR. ♦
IDS Because of routine overloading, you can grant the Execute privilege on more
than one UDR at a time. The following table explains the purpose of the
keywords that you specify.
KEYWORD Purpose
SPECIFIC Grants the Execute privilege for the UDR identified by specific
name
To limit the Execute privilege to a UDR that accepts particular data types as
arguments, include the routine parameter list or use the SPECIFIC keyword to
introduce the specific name of a particular UDR.
Tip: If an external function has a negator function, you must grant the Execute
privilege on both the external function and its negator function before users can
execute the external function.
♦
USAGE ON LANGUAGE C
JAVA
SPL
In the following example, user informix grants the Usage privilege on both
available external languages (C and Java) to user joy:
GRANT USAGE ON LANGUAGE C TO joy;
GRANT USAGE ON LANGUAGE JAVA TO joy;
In the following example, assume that the default Usage privilege on SPL was
revoked from PUBLIC and the DBA wants to grant the Usage privilege on SPL
to the role named developers:
GRANT USAGE ON LANGUAGE SPL TO developers
User List
You can grant privileges to an individual user or a list of users. You can also
use the PUBLIC keyword to grant privileges to all users.
PUBLIC
,
user
'user '
The following example grants the table-level privilege Insert on table1 to the
user named mary in a database that is not ANSI compliant:
GRANT INSERT ON table1 TO mary
ANSI In an ANSI-compliant database, if you do not use quotes around user, the
name of the user is stored in uppercase letters. ♦
After you create and grant a role, you can grant certain privileges to the one
or more users associated with that role name.
role name
A DBA has the authority to grant a new role to another user. If a user receives
a role WITH GRANT OPTION, that user can grant the role to other users or to
another role. Users keep a role granted to them until a REVOKE statement
breaks the association between their login names and the role name.
Important: CREATE ROLE and GRANT do not activate the role. A role has no effect
until the SET ROLE statement enables it. A role grantor or a role grantee can issue
the SET ROLE.
The following example shows the sequence required to grant and activate the
role payables to a group of employees who perform account payables
functions. First the DBA creates role payables, then grants it to maryf.
CREATE ROLE payables;
GRANT payables TO maryf WITH GRANT OPTION
The DBA or maryf can activate the role with the following statement:
SET ROLE payables
User maryf has the WITH GRANT OPTION authorization to grant payables to
other employees who pay accounts.
GRANT payables TO charly, gene, marvin, raoul
If you grant privileges for one role to another role, the recipient role has a
combined set of privileges. The following example grants the role petty_cash
to the role payables:
CREATE ROLE petty_cash;
SET ROLE petty_cash;
GRANT petty_cash TO payables
The following example grants the table-level privilege Insert on the supplier
table to the role payables:
GRANT INSERT ON supplier TO payables
Anyone granted the role of payables can now insert into supplier.
If you revoke from user the privilege that you granted using the WITH GRANT
OPTION keyword, you sever the chain of privileges. That is, when you revoke
privileges from user, you automatically revoke the privileges of all users who
received privileges from user or from the chain that user created (unless user,
or the users who received privileges from user, were granted the same set of
privileges by someone else). The following examples illustrate this situation.
You, as the owner of the table items, issue the following statements to grant
access to the user mary:
REVOKE ALL ON items FROM PUBLIC;
GRANT SELECT, UPDATE ON items TO mary WITH GRANT OPTION
The user mary uses her new privilege to grant users cathy and paul access to
the table.
GRANT SELECT, UPDATE ON items TO cathy;
GRANT SELECT ON items TO paul
Later you issue the following statement to cancel access privileges for the
user mary on the items table:
REVOKE SELECT, UPDATE ON items FROM mary
This single statement effectively revokes all privileges on the items table
from the users mary, cathy, and paul.
If you want to create a chain of privileges with another user as the source of
the privilege, use the AS grantor clause.
AS grantor Clause
When you grant privileges, by default, you are the one who can revoke those
privileges. The AS grantor clause lets you establish another user as the source
of the privileges you are granting. When you use this clause, the login
provided in the AS grantor clause replaces your login in the appropriate
system catalog table.
You can use this clause only if you have the DBA privilege on the database.
Once you use this clause, only the specified grantor can REVOKE the effects of
the current GRANT. Even a DBA cannot revoke a privilege unless that DBA is
listed in the appropriate system catalog table as the source who granted the
privilege.
The following example illustrates this situation. You are the DBA and you
grant all privileges on the items table to the user tom, along with the right to
grant all privileges:
REVOKE ALL ON items FROM PUBLIC;
GRANT ALL ON items TO tom WITH GRANT OPTION
The following example illustrates a different situation. You also grant Select
and Update privileges to the user jim, but you specify that the grant is made
as the user tom. (The records of the database server show that the user tom is
the grantor of the grant in the systabauth system catalog table, rather than
you.)
GRANT SELECT, UPDATE ON items TO jim AS tom
Later, you decide to revoke privileges on the items table from the user tom,
so you issue the following statement:
REVOKE ALL ON items FROM tom
When you try to revoke privileges from the user jim with a similar statement,
however, the database server returns an error, as the following example
shows:
REVOKE SELECT, UPDATE ON items FROM jim
You get an error because the database server record shows the original
grantor as the user tom, and you cannot revoke the privilege. Although you
are the DBA, you cannot revoke a privilege that another user granted.
Related Information
Related statements: GRANT FRAGMENT, REVOKE, AND REVOKE FRAGMENT
For information about roles, see the following statements: CREATE ROLE,
DROP ROLE, and SET ROLE.
In the Informix Guide to Database Design and Implementation, see the discussion
of privileges.
+ GRANT FRAGMENT
IDS
Use the GRANT FRAGMENT statement to grant Insert, Update, and Delete
privileges on individual fragments of a fragmented table.
Syntax
,
Fragment-Level
GRANT FRAGMENT Privileges ON table ( dbspace )
p. 2-525
TO user
Usage
The GRANT FRAGMENT statement is similar to the GRANT statement. Both
statements grant privileges to users. The difference between the two state-
ments is that you use GRANT to grant privileges on a table while you use
GRANT FRAGMENT to grant privileges on table fragments.
Use the GRANT FRAGMENT statement to grant the Insert, Update, or Delete
privilege on one or more fragments of a table to one or more users.
The GRANT FRAGMENT statement is valid only for tables that are fragmented
according to an expression-based distribution scheme. For an explanation of
expression-based distribution schemes, see “Syntax” on page 2-12.
Fragment-Level Privileges
ALL
,
INSERT
DELETE
UPDATE
Privilege Purpose
UPDATE Lets you update rows in the fragment and to name any column of
the table in an UPDATE statement
A user who has table privileges on a fragmented table has the privileges
implicitly on all fragments of the table. These privileges are not recorded in
the sysfragauth system catalog table.
Whether or not the database is ANSI compliant, you can use the GRANT
FRAGMENT statement to grant explicit Insert, Update, and Delete privileges
on one or more fragments of a table that is fragmented by expression. The
privileges granted by the GRANT FRAGMENT statement are explicitly
recorded in the sysfragauth system catalog table.
The Insert, Update, and Delete privileges that are conferred on table
fragments by the GRANT FRAGMENT statement are collectively known as
fragment-level privileges or fragment-level authority.
The following statement grants the Update privilege on the fragment of the
customer table in dbsp3 to the user george and gives this user the right to
grant the Update privilege on the same fragment to other users:
GRANT FRAGMENT UPDATE ON customer (dbsp3) TO george
WITH GRANT OPTION
AS grantor Clause
The AS grantor clause is optional in a GRANT FRAGMENT statement. Use this
clause to specify the grantor of the privilege.
In the following example, the DBA grants the Delete privilege on the
fragment of the customer table in dbsp3 to the user martha. In the GRANT
FRAGMENT statement, the DBA uses the AS grantor clause to specify that the
user jack is listed as the grantor of the privilege in the sysfragauth system
catalog table.
GRANT FRAGMENT DELETE ON customer (dbsp3) TO martha AS jack
In the following example, the user grants the Update privilege on the
fragment of the customer table in dbsp3 to the user fred. Because this
statement does not specify the AS grantor clause, the user who issues the
statement is listed by default as the grantor of the privilege in the sysfragauth
system catalog table.
GRANT FRAGMENT UPDATE ON customer (dbsp3) TO fred
For example, if you grant the Delete privilege on the fragment of the
customer table in dbsp3 to user martha but specify user jack as the grantor
of the privilege, user jack can revoke that privilege from user martha, but you
cannot revoke that privilege from user martha.
Related Information
Related statements: GRANT and REVOKE FRAGMENT
+ INFO
DB
Use the INFO statement to display a variety of information about databases
and tables.
Syntax
INFO TABLES
INDEXES
ACCESS
PRIVILEGES
REFERENCES
STATUS
FRAGMENTS
Usage
You can use the keywords of the INFO statement to display the following
types of information.
TABLES Keyword
Use the TABLES keyword to display a list of the tables in the current database.
The TABLES keyword does not display the system catalog tables.
COLUMNS Keyword
Use the COLUMNS keyword to display the names and data types of the
columns in a specified table and whether null values are allowed.
INDEXES Keyword
Use the INDEXES keyword to display the name, owner, and type of each
index in a specified table, whether the index is clustered, and the names of
the columns that are indexed.
FRAGMENTS Keyword
Use the FRAGMENTS keyword to display the dbspace names where
fragments are located for a specified table. If the table is fragmented with an
expression-based distribution scheme, the INFO statement also shows the
expressions.
ACCESS Keyword
Use the ACCESS or PRIVILEGES keywords to display user-access privileges
for a specified table.
REFERENCES Keyword
Use the REFERENCES keyword to display the References privilege for users
for the columns of a specified table.
STATUS Keyword
Use the STATUS keyword to display information about the owner, row length,
number of rows and columns, creation date, and status of audit trails for a
specified table.
Related Information
Related statements: GRANT and REVOKE
For a description of the Info option on the SQL menu or the TABLE menu in
DB-Access, see the DB-Access User’s Manual.
INSERT
Use the INSERT statement to insert one or more new rows into a table or view
or one or more elements into an SPL or ESQL/C collection variable.
Syntax
external_table
,
Subset of
( column ) SELECT
Statement
+ p. 2-548
IDS
Usage
To insert data into a table, you must either own the table or have the Insert
privilege for the table (see “GRANT” on page 2-500). To insert data into a
view, you must have the required Insert privilege, and the view must meet
the requirements explained in “Inserting Rows Through a View.”
If you insert data into a table that has data integrity constraints associated
with it, the inserted data must meet the constraint criteria. If it does not, the
database server returns an error.
If you are using effective checking, and the checking mode is set to
IMMEDIATE, all specified constraints are checked at the end of each INSERT
statement. If the checking mode is set to DEFERRED, all specified constraints
are not checked until the transaction is committed.
Specifying Columns
If you do not explicitly specify one or more columns, data is inserted into
columns using the column order that was established when the table was
created or last altered. The column order is listed in the syscolumns system
catalog table.
E/C In ESQL/C, you can use the DESCRIBE statement with an INSERT statement to
determine the column order and the data type of the columns in a table. ♦
The number of columns specified in the INSERT INTO clause must equal the
number of values supplied in the VALUES clause or by the SELECT statement,
either implicitly or explicitly. If you specify columns, the columns receive
data in the order in which you list them. The first value following the VALUES
keyword is inserted into the first column listed, the second value is inserted
into the second column listed, and so on.
The following SPL example shows how you can insert a value at a specific
position in a list:
CREATE PROCEDURE test3()
UPDATE table1
VALUES list_col = a_list
WHERE id = 201;
END PROCEDURE;
Suppose that before this INSERT, a_list contained the elements {1,8,4,5,2}.
After this INSERT, a_list contains the elements {1,8,9,4,5,2}. The new
element 9 was inserted at position 3 in the list. For more information on
inserting values into collection variables, see “Collection Derived Table” on
page 4-9.
■ DISTINCT keyword
■ GROUP BY clause
■ Derived value (also referred to as a virtual column)
■ Aggregate value
Columns in the underlying table that are unspecified in the view receive
either a default value or a null value if no default is specified. If one of these
columns does not specify a default value, and a null value is not allowed, the
insert fails.
You can use data-integrity constraints to prevent users from inserting values
into the underlying table that do not fit the view-defining SELECT statement.
For further information, see “WITH CHECK OPTION Keywords” on
page 2-338.
If several users are entering sensitive information into a single table, the
built-in USER function can limit their view to only the specific rows that each
user inserted. The following example contains a view and an INSERT
statement that achieve this effect:
CREATE VIEW salary_view AS
SELECT lname, fname, current_salary
FROM salary
WHERE entered_by = USER
If you are using a cursor that is associated with an INSERT statement, the rows
are buffered before they are written to the disk. The insert buffer is flushed
under the following conditions:
ANSI If you are inserting rows into an ANSI-compliant database, transactions are
implicit, and all database modifications take place within a transaction. In
this case, if an INSERT statement fails, use the ROLLBACK WORK statement to
undo the insertions.
If you are using an explicit transaction, and the update fails, the database
server automatically undoes the effects of the update. ♦
XPS If you are using Extended Parallel Server, tables that you create with the RAW
usage type are never logged. Thus, raw tables are not recoverable, even
though the database uses logging. For information about raw tables, refer to
the Informix Guide to SQL: Reference. ♦
Rows that you insert with a transaction remain locked until the end of the
transaction. The end of a transaction is either a COMMIT WORK statement,
where all modifications are made to the database, or a ROLLBACK WORK
statement, where none of the modifications are made to the database. If many
rows are affected by a single INSERT statement, you can exceed the maximum
number of simultaneous locks permitted. To prevent this situation, either
insert fewer rows per transaction or lock the page (or the entire table) before
you execute the INSERT statement.
VALUES Clause
VALUES ( input_var )
E/C
: indicator_var
+
$ indicator_var
NULL
USER
Literal Number
p. 4-237
Quoted String
p. 4-260
+
Literal DATETIME
p. 4-231
Literal INTERVAL
p. 4-234
Expression
p. 4-73
IDS
Literal Collection
p. 4-227
Literal Row
p. 4-239
When you use the VALUES clause, you can insert only one row at a time. Each
value that follows the VALUES keyword is assigned to the corresponding
column listed in the INSERT INTO clause (or in column order if a list of
columns is not specified).
If you are inserting a quoted string into a column, the maximum length of the
string is 256 bytes. If you insert a quoted string that is longer than 256 bytes,
the database server returns an error.
E/C In ESQL/C, if you are using variables, you can insert quoted strings longer
than 256 bytes into a table. ♦
For discussions on the keywords that you can use in the VALUES clause, refer
to “Constant Expressions” on page 4-108.
The database server makes every effort to perform data conversion. If the
data cannot be converted, the INSERT operation fails.
Data conversion also fails if the target data type cannot hold the value that is
specified. For example, you cannot insert the integer 123456 into a column
defined as a SMALLINT data type because this data type cannot hold a
number that large.
For a summary of the casting that the database server provides, see the
Informix Guide to SQL: Reference. For information on how to create a user-
defined cast, see the CREATE CAST statement in this manual and Extending
Informix Dynamic Server 2000.
IDS If you are inserting a serial value into a table that is part of a table hierarchy,
the database server updates all tables in the hierarchy that contain the serial
counter with the value that you insert (either a zero (0) for the next highest
value or a specific number). ♦
E/C You can also use a collection variable to insert values into a collection column.
With a collection variable you can insert one or more individual elements in
SPL a collection. For more information, see “Collection Derived Table” on
page 4-9. ♦
Regardless of what method you use to insert values into a collection column,
you cannot insert null elements into the collection column. Thus expressions
that you use cannot evaluate to null. If the collection that you are attempting
to insert contains a null element, the database server returns an error.
Example
For example, suppose you define the tab1 table as follows:
CREATE TABLE tab1
(
int1 INTEGER,
list1 LIST(ROW(a INTEGER, b CHAR(5)) NOT NULL),
dec1 DECIMAL(5,2)
)
The collection column, list1, in this example has three elements. Each element
is an unnamed row type with an INTEGER field and a CHAR(5) field. The first
element is composed of two literal values, an integer (1) and a quoted string
(abcde). The second and third elements also use a quoted string to indicate
the value for the second field. However, they each designate the value for the
first field with an expression rather than a literal value.
The following INSERT statement inserts literal values in the name and
address columns of the employee table:
INSERT INTO employee VALUES
(
ROW('John', 'Williams'),
ROW('103 Baker St', 'Tracy','CA', 94060)::address_t
)
The INSERT statement uses ROW constructors to generate values for the name
column (an unnamed row type) and the address column (a named row type).
When you specify a value for a named row type, you must use the CAST AS
keyword or the double colon (::) operator, in conjunction with the name of the
named row type, to cast the value to the named row type.
For more information on the syntax for ROW constructors, see “Constructor
Expressions” on page 4-116 in the Expression segment. For information on
literal values for named row types and unnamed row types, see “Literal
Row” on page 4-239.
E/C You can use ESQL/C host variables to insert non-literal values as:
When you use a row variable in the VALUES clause, the row variable must
contain values for each field value. For information on how to insert values
in a row variable, see “Inserting into a Row Variable” on page 2-551. ♦
The TODAY keyword returns the system date. The CURRENT keyword
returns the system date and time. The USER keyword returns a string that
contains the login account name of the current user. The SITENAME or
DBSERVERNAME keyword returns the database server name where the
current database resides. The following example shows how to use built-in
functions to insert data:
INSERT INTO cust_calls (customer_num, call_dtime, user_id,
call_code, call_descr)
VALUES (212, CURRENT, USER, 'L', '2 days')
■ FIRST
■ INTO TEMP
IDS ■ ORDER BY
■ UNION ♦
If this statement has a WHERE clause that does not return rows, sqlca returns
SQLNOTFOUND (100) for ANSI-compliant databases. In databases that are not
ANSI compliant, sqlca returns (0). When you insert as a part of a multi-
statement prepare, and no rows are inserted, sqlca returns SQLNOTFOUND
(100) for both ANSI databases and databases that are not ANSI compliant.
IDS If you are inserting values into a supertable in a table hierarchy, the subquery
can reference a subtable.
If you are inserting values into a subtable in a table hierarchy, the subquery
can reference the supertable if it references only the supertable. That is, the
subquery must use the SELECT…FROM ONLY (supertable)…syntax. ♦
When you move data from a database into an external table, the SELECT
statement must define all columns in the external table. The SELECT
statement must not contain a FIRST, FOR UPDATE, INTO, INTO SCRATCH, or
INTO TEMP clause. However, you can use an ORDER BY clause to produce
files that are ordered within themselves.
When you use a user-defined function to insert column values, the return
values of the function must have a one-to-one correspondence with the listed
columns. That is, each value that the function returns must be of the data type
expected by the corresponding column in the column list.
IDS For backward compatibility, you can use the EXECUTE PROCEDURE
keywords to execute an SPL function that was created with the CREATE
PROCEDURE statement. ♦
If the called SPL routine scans or updates the target table of the insert, the
database returns an error. That is, the SPL routine cannot select data from the
table into which you are inserting rows.
If a called SPL routine contains certain SQL statements, the database server
returns an error. For information on which SQL statements cannot be used in
an SPL routine that is called within a data manipulation statement, see
“Restrictions on an SPL Routine Called in a Data Manipulation Statement”
on page 4-302.
Ext An external function can only return one value. Make sure that you specify
only one column in the column list of the INSERT statement. This column
must have a compatible data type with the value that the external function
returns.The external function can be an iterator function. ♦
Example
The following example shows how to insert data into a temporary table
called result_tmp in order to output to a file the results of a user-defined
function (f_one) that returns multiple rows.
CREATE TEMP TABLE result_tmp( ... );
INSERT INTO result_tmp EXECUTE FUNCTION f_one();
UNLOAD TO 'file' SELECT * FROM foo_tmp;
...
EXEC SQL update table(:myrect)
set x=7, y=3, length=6, width=2;
EXEC SQL insert into rectangles values (12, :myrect);
Related Information
Related statements: CLOSE, CREATE EXTERNAL TABLE, DECLARE, DESCRIBE,
EXECUTE, FLUSH, FOREACH, OPEN, PREPARE, PUT, and SELECT
For a task-oriented discussion of inserting data into tables and for infor-
mation on how to access row and collections with SPL variables, see the
Informix Guide to SQL: Tutorial.
For a discussion of the GLS aspects of the INSERT statement, see the Informix
Guide to GLS Functionality.
For information on how to access row and collections with ESQL/C host
variables, see the chapter on complex types in the Informix ESQL/C
Programmer’s Manual.
+ LOAD
DB
Use the LOAD statement to insert data from an operating-system file into an
SQLE existing table or view.
Syntax
Usage
The LOAD statement appends new rows to the table. It does not overwrite
existing data.
You cannot add a row that has the same key as an existing row.
To use the LOAD statement, you must have Insert privileges for the table
where you want to insert data. For information on database-level and table-
level privileges, see the GRANT statement.
If you do not include a list of columns in the INSERT INTO clause, the fields
in the file must match the columns that are specified for the table in number,
order, and data type.
Each line of the file must have the same number of fields. You must define
field lengths that are less than or equal to the length that is specified for the
corresponding column. Specify only values that can convert to the data type
of the corresponding column. The following table indicates how the database
server expects you to represent the data types in the LOAD FROM file (when
you use the default locale, U.S. English).
row types Row type must have its values surrounded by parentheses
(named and and a field delimiter separating each element.
unnamed) For more information, see “Loading Complex Types” on
page 2-559.
simple large objects TEXT and BYTE columns are loaded directly from the
(TEXT, BYTE) LOAD TO file.
For more information, see “Loading Simple Large Objects”
on page 2-558.
smart large objects CLOB and BLOB columns are loaded from a separate
(CLOB, BLOB) operating-system file. The field for the CLOB or BLOB
column in the LOAD FROM file contains the name of this
separate file.
For more information, see “Loading Smart Large Objects”
on page 2-559.
GLS If you are using a nondefault locale, the formats of DATE, DATETIME, MONEY,
and numeric column values in the LOAD FROM file must be compatible with
the formats that the locale supports for these data types. For more infor-
mation, see the Informix Guide to GLS Functionality. ♦
The following example shows the contents of a hypothetical input file named
new_custs:
0|Jeffery|Padgett|Wheel Thrills|3450 El Camino|Suite 10|Palo
Alto|CA|94306||
0|Linda|Lane|Palo Alto Bicycles|2344 University||Palo
Alto|CA|94301|(415)323-6440
The following statement loads the values from the new_custs file into the
customer table owned by jason:
LOAD FROM 'new_custs' INSERT INTO jason.customer
If you include any of the following special characters as part of the value of a
field, you must precede the character with a backslash (\):
■ Backslash
■ Delimiter
■ Newline character anywhere in the value of a VARCHAR or
NVARCHAR column
■ Newline character at end of a value for a TEXT value
If you are loading files that contain VARCHAR data types, note the following
information:
■ If you give the LOAD statement data in which the character fields
(including VARCHAR) are longer than the column size, the excess
characters are disregarded.
■ Use the backslash (\) to escape embedded delimiter and backslash
characters in all character fields, including VARCHAR.
■ Do not use the following characters as delimiting characters in the
LOAD FROM file: 0 to 9, a to f, A to F, backslash, newline character.
GLS For TEXT columns, the database server handles any required code-set conver-
sions for the data. For more information, see the Informix Guide to GLS
Functionality. ♦
If you are unloading files that contain simple-large-object data types, objects
smaller than 10 kilobytes are stored temporarily in memory. You can adjust
the 10-kilobyte setting to a larger setting with the DBBLOBBUF environment
variable. Simple large objects that are larger than the default or the setting of
the DBBLOBBUF environment variable are stored in a temporary file. For
additional information about the DBBLOBBUF environment variable, see the
Informix Guide to SQL: Reference.
In this format, start_off is the starting offset (in hexadecimal) of the smart-
large-object value within the client file, length is the length (in hexadecimal)
of the BLOB or CLOB value, and client_path is the pathname for the client file.
No spaces can appear between these values.
For example, to load a CLOB value that is 512 bytes long and is at offset 256
in the /usr/apps/clob9ce7.318 file, the database server expects the CLOB value
to appear as follows in the LOAD FROM file:
|100,200,/usr/apps/clob9ce7.318|
If the whole client file is to be loaded, a CLOB or BLOB column value appears
as follows in the LOAD FROM file:
client_path
For example, to load a CLOB value that occupies the entire file
/usr/apps/clob9ce7.318, the database server expects the CLOB value to appear
as follows in the LOAD FROM file:
|/usr/apps/clob9ce7.318|
GLS For CLOB columns, the database server handles any required code-set
conversions for the data. For more information, see the Informix Guide to GLS
Functionality. ♦
DELIMITER Clause
Use the DELIMITER clause to specify the delimiter that separates the data
contained in each column in a row in the input file. You can specify TAB
(CTRL-I) or <blank> (= ASCII 32) as the delimiter symbol. You cannot use the
following items as the delimiter symbol:
■ Backslash (\)
■ Newline character (CTRL-J)
■ Hexadecimal numbers (0 to 9, a to f, A to F)
If you omit this clause, the database server checks the DBDELIMITER
environment variable. For information about how to set the DBDELIMITER
environment variable, see the Informix Guide to SQL: Reference.
If the DBDELIMITER environment variable has not been set, the default
delimiter is the pipe (|).
The following example identifies the semicolon (;) as the delimiting character.
The example uses Windows NT file-naming conventions.
LOAD FROM 'C:\data\loadfile' DELIMITER ';'
INSERT INTO orders
The following example identifies the price and discount columns as the only
columns in which to add data. The example uses Windows NT file-naming
conventions.
LOAD FROM 'C:\tmp\prices' DELIMITER ','
INSERT INTO norman.worktab(price,discount)
Related Information
Related statements: UNLOAD and INSERT
For a task-oriented discussion of the LOAD statement and other utilities for
moving data, see the Informix Migration Guide.
For a discussion of the GLS aspects of the LOAD statement, see the Informix
Guide to GLS Functionality.
+
LOCK TABLE
Use the LOCK TABLE statement to control access to a table by other processes.
Syntax
synonym EXCLUSIVE
Usage
You can lock a table if you own the table or have the Select privilege on the
table or on a column in the table, either from a direct grant or from a grant to
PUBLIC. The LOCK TABLE statement fails if the table is already locked in
exclusive mode by another process, or if an exclusive lock is attempted while
another user has locked the table in share mode.
The SHARE keyword locks a table in shared mode. Shared mode allows other
processes read access to the table but denies write access. Other processes
cannot update or delete data if a table is locked in shared mode.
The following guidelines apply to the use of the LOCK TABLE statement
within transactions:
The following example shows how to change the locking mode of a table in
a database that was created with transaction logging:
BEGIN WORK
LOCK TABLE orders IN EXCLUSIVE MODE
...
COMMIT WORK
BEGIN WORK
LOCK TABLE orders IN SHARE MODE
...
COMMIT WORK
To change the lock mode on a table, release the lock with the UNLOCK TABLE
statement and then issue a new LOCK TABLE statement.
The following example shows how to change the lock mode of a table in a
database that was created without transactions:
LOCK TABLE orders IN EXCLUSIVE MODE
.
.
.
UNLOCK TABLE orders
.
.
.
LOCK TABLE orders IN SHARE MODE
Related Information
Related statements: BEGIN WORK, COMMIT WORK, ROLLBACK WORK, SET
ISOLATION, SET LOCK MODE, and UNLOCK TABLE
For a discussion of concurrency and locks, see the Informix Guide to SQL:
Tutorial.
E/C
OPEN
Use the OPEN statement to activate a cursor.
Syntax
OPEN cursor_id
+
cursor_id_var
WITH REOPTIMIZATION
USING parameter_var
DESCRIPTOR sqlda_pointer
Usage
The OPEN statement activates the following types of cursors:
The specific actions that the database server takes differ, depending on the
statement with which the cursor is associated.
When you associate one of the previous statements with a cursor directly
(that is, you do not prepare the statement and associate the statement
identifier with the cursor) the OPEN statement implicitly prepares the
statement.
ANSI In an ANSI-compliant database, you receive an error code if you try to open
a cursor that is already open. ♦
XPS In Extended Parallel Server, to recreate this example use the CREATE
PROCEDURE statement instead of the CREATE FUNCTION statement. ♦
ANSI In an ANSI-compliant database, you receive an error code if you try to open
a cursor that is already open. ♦
Even if the values of the variables are unchanged, the values in the active set
can be different, in the following situations:
The database server can process most queries dynamically. For these queries,
the database server does not pre-fetch all rows when it opens the select or
function cursor. Therefore, if other users are modifying the table at the same
time that the cursor is being processed, the active set might reflect the results
of these actions.
However, for some queries, the database server evaluates the entire active set
when it opens the cursor. These queries include those with the following
features:
■ Queries that require sorting: those with an ORDER BY clause or with
the DISTINCT or UNIQUE keyword
■ Queries that require hashing: those with a join or with the GROUP BY
clause
For these queries, any changes that other users make to the table while the
cursor is being processed are not reflected in the active set.
ANSI In an ANSI-compliant database, you receive an error code if you try to open
a cursor that is already open. ♦
Use the name of a collection variable in the USING clause of the OPEN
statement. For more information on the use of OPEN...USING with a collection
variable, see “Fetching From a Collection Cursor” on page 2-466 and
“Inserting into a Collection Cursor” on page 2-599.
USING Clause
The USING clause of the OPEN statement is required when the cursor is
associated with a prepared statement that includes question-mark (?) place-
holders, as follows:
You can supply values for these parameters in one of the following ways:
You cannot include indicator variables in the list of variable names. To use an
indicator variable, you must include the SELECT or EXECUTE FUNCTION (or
EXECUTE PROCEDURE) statement as part of the DECLARE statement.
You must supply one host variable name for each placeholder. The data type
of each variable must be compatible with the corresponding type that the
prepared statement requires.
The following example illustrates the USING clause of the OPEN statement
with an EXECUTE FUNCTION statement in an ESQL/C code fragment:
stcopy ("EXECUTE FUNCTION one_func(?, ?)", exfunc_stmt);
EXEC SQL prepare exfunc_id from :exfunc_stmt;
EXEC SQL declare func_curs cursor for exfunc_id;
EXEC SQL open func_curs using :arg1, :arg2;
XPS In Extended Parallel Server, to recreate this example use the CREATE
PROCEDURE statement instead of the CREATE FUNCTION statement. ♦
As the example indicates, the system descriptor area must be allocated before
you reference it in the OPEN statement.
The sqlda value specifies the number of input values that are described in
occurrences of sqlvar. This number must correspond to the number of
dynamic parameters in the prepared statement.
■ Rebuilds only the query-design plan rather than the entire statement
■ Uses fewer resources
■ Reduces overhead
■ Requires less time
Similarly, if you use the SET AUTOFREE statement for one or more cursors,
when the program closes the specific cursor, the database server automati-
cally frees the cursor-related resources. In this case, you cannot use the cursor
unless you declare the cursor again.
Related Information
Related statements: ALLOCATE DESCRIPTOR, DEALLOCATE DESCRIPTOR,
DESCRIBE, CLOSE, DECLARE, EXECUTE, FETCH, FLUSH, FREE, GET
DESCRIPTOR, PREPARE, PUT, SET AUTOFREE, SET DEFERRED_PREPARE, and
SET DESCRIPTOR
For a task-oriented discussion of the OPEN statement, see the Informix Guide
to SQL: Tutorial.
+ OUTPUT
DB
Use the OUTPUT statement to send query results directly to an operating-
system file or to pipe query results to another program.
Syntax
SELECT
OUTPUT TO filename Statement
p. 2-634
UNIX WITHOUT HEADINGS
PIPE program
Usage
You can use the OUTPUT statement to direct the results of a query to an
operating-system file or to a program. You can also specify whether column
headings should be omitted from the query output.
Related Information
Related statements: SELECT and UNLOAD
+ PREPARE
E/C
Use the PREPARE statement to parse, validate, and generate an execution
plan for SQL statements at runtime.
Syntax
Quoted
PREPARE statement_id FROM String
p. 4-260
statement_id_var
statement_var
Usage
The PREPARE statement permits your program to assemble the text of an SQL
statement at runtime and make it executable. This dynamic form of SQL is
accomplished in three steps:
Restrictions
For information on statements that you cannot use in a prepared statement,
see “Restricted Statements in Single-Statement Prepares” on page 2-584 and
“Restricted Statements in Multi-Statement Prepares” on page 2-591.
A subsequent FREE statement releases the resources that were allocated to the
statement. After you release the database-server resources, you cannot use
the statement identifier with a DECLARE cursor or with the EXECUTE
statement until you prepare the statement again.
The first example shows a statement identifier that was prepared as a host
variable. The second example shows a statement identifier that was prepared
as a character-string constant:
stcopy ("query2", stmtid);
EXEC SQL prepare :stmtid from
'select * from customer';
Statement Text
The PREPARE statement can take statement text either as a quoted string or as
text that is stored in a program variable. The following restrictions apply to
the statement text:
IDS If the prepared statement contains the Collection Derived Table segment on
an ESQL/C collection variable, some additional limitations exist on how you
can assemble the text for the PREPARE statement. For information about
dynamic SQL, see the Informix ESQL/C Programmer’s Manual. ♦
IDS You can prepare any single SQL statement except the following statements.
ALLOCATE COLLECTION FLUSH
ALLOCATE DESCRIPTOR FREE
ALLOCATE ROW GET DESCRIPTOR
CLOSE GET DIAGNOSTICS
CONNECT INFO
CREATE FUNCTION FROM LOAD
CREATE PROCEDURE FROM OPEN
CREATE ROUTINE FROM OUTPUT
DEALLOCATE COLLECTION PREPARE
DEALLOCATE DESCRIPTOR PUT
DEALLOCATE ROW SET AUTOFREE
DECLARE SET CONNECTION
DESCRIBE SET DEFERRED_PREPARE
DISCONNECT SET DESCRIPTOR
EXECUTE UNLOAD
EXECUTE IMMEDIATE WHENEVER
FETCH
XPS You can prepare any single SQL statement except the following statements
ALLOCATE DESCRIPTOR GET DESCRIPTOR
CLOSE GET DIAGNOSTICS
CONNECT INFO
CREATE PROCEDURE FROM LOAD
DEALLOCATE DESCRIPTOR OPEN
DECLARE OUTPUT
DESCRIBE PREPARE
DISCONNECT PUT
EXECUTE SET CONNECTION
EXECUTE IMMEDIATE SET DEFERRED_PREPARE
FETCH SET DESCRIPTOR
FLUSH UNLOAD
FREE WHENEVER
You can prepare a SELECT statement. If the SELECT statement includes the
INTO TEMP clause, you can execute the prepared statement with an EXECUTE
statement. If it does not include the INTO TEMP clause, the statement returns
rows of data. Use DECLARE, OPEN, and FETCH cursor statements to retrieve
the rows.
A prepared SELECT statement can include a FOR UPDATE clause. This clause
is used with the DECLARE statement to create an update cursor. The
following example shows a SELECT statement with a FOR UPDATE clause in
ESQL/C:
The PREPARE statements in the following ESQL/C examples show some uses
of question-mark (?) placeholders:
EXEC SQL prepare s3 from
'select * from customer where state matches ?';
You can use a placeholder to defer evaluation of a value until runtime only
for an expression. You cannot use a question-mark (?) placeholder to
represent an SQL identifier except as noted in “Preparing Statements with
SQL Identifiers” on page 2-587.
The USING clause is available in both OPEN (for statements that are
associated with a cursor) and EXECUTE (all other prepared statements)
statements.
However, in a few special cases, you can use the question-mark (?) place-
holder for an SQL identifier. These cases are as follows:
■ You can use the question-mark (?) placeholder for the database name
in the DATABASE statement.
■ You can use the question-mark (?) placeholder for the dbspace name
in the IN dbspace clause of the CREATE DATABASE statement.
■ You can use the question-mark (?) placeholder for the cursor name in
statements that use cursor names.
The following ESQL/C example prompts the user for the name of a table and
uses that name in a SELECT statement. Because the table name is unknown
until runtime, the number and data types of the table columns are also
unknown. Therefore, the program cannot allocate host variables to receive
data from each row in advance. Instead, this program fragment describes the
statement into an sqlda descriptor and fetches each row with the descriptor.
The fetch puts each row into memory locations that the program provides
dynamically.
If a program retrieves all the rows in the active set, the FETCH statement
would be placed in a loop that fetched each row. If the FETCH statement
retrieves more than one data value (column), another loop exists after the
FETCH, which performs some action on each data value.
#include <stdio.h>
EXEC SQL include sqlda;
EXEC SQL include sqltypes;
char *malloc( );
main()
{
struct sqlda *demodesc;
char tablename[19];
int i;
EXEC SQL BEGIN DECLARE SECTION;
char demoselect[200];
EXEC SQL END DECLARE SECTION;
}
}
for( ; ; )
{
printf( "\n" );
EXEC SQL fetch d_curs using descriptor demodesc;
if ( sqlca.sqlcode != 0 )
break;
for ( i = 0; i < demodesc->sqld; i++ )
{
switch (demodesc->sqlvar[i].sqltype)
{
case CCHARTYPE:
printf( "%s: \"%s\n", demodesc->sqlvar[i].sqlname,
demodesc->sqlvar[i].sqldata );
break;
case CINTTYPE:
printf( "%s: %d\n", demodesc->sqlvar[i].sqlname,
*((int *) demodesc->sqlvar[i].sqldata) );
break;
}
}
}
EXEC SQL close d_curs;
EXEC SQL free d_curs;
prsqlda(sp)
struct sqlvar_struct *sp;
{
printf ("type = %d\n", sp->sqltype);
printf ("len = %d\n", sp->sqllen);
printf ("data = %lx\n", sp->sqldata);
printf ("ind = %lx\n", sp->sqlind);
printf ("name = %s\n", sp->sqlname);
}
■ UPDATE…WHERE…
■ SELECT INTO TEMP…WHERE…
■ INSERT INTO…WHERE…
■ DELETE FROM…WHERE…
In the following example, four SQL statements are prepared into a single
ESQL/C string that is called query. Individual statements are delimited with
semicolons. A single PREPARE statement can prepare the four statements for
execution, and a single EXECUTE statement can execute the statements that
are associated with the qid statement identifier.
In the preceding code fragment, the semicolons (;) are required as SQL
statement-terminator symbols between each SQL statement in the text that
query holds.
■ Statements that can cause the current database to close during the
execution of the multistatement sequence
■ Statements that include references to TEXT or BYTE host variables
main()
{
sprintf(disc_up, "%s %s",
"update customer ",
"set discount = 0.1 where customer_num = ?");
EXEC SQL prepare up1 from :disc_up;
while (1)
{
printf("Enter customer number (or 0 to quit): ");
scanf("%d", cust_num);
if (cust_num == 0)
break;
EXEC SQL execute up1 using :cust_num;
}
}
Related Information
Related statements: CLOSE, DECLARE, DESCRIBE, EXECUTE, FREE, OPEN, SET
AUTOFREE, and SET DEFERRED_PREPARE
For information about basic concepts relating to the PREPARE statement, see
the Informix Guide to SQL: Tutorial.
+ PUT
E/C
Use the PUT statement to store a row in an insert buffer for later insertion into
the database.
Syntax
PUT cursor_id
cursor_id_var ,
FROM output_var
: :indicator_var
$ indicator_var
INDICATOR indicator_var
DESCRIPTOR sqlda_pointer
Usage
Each PUT statement stores a row in an insert buffer that was created when the
cursor was opened. If the buffer has no room for the new row when the
statement executes, the buffered rows are written to the database in a block
and the buffer is emptied. As a result, some PUT statement executions cause
rows to be written to the database, and some do not.
You can use the FLUSH statement to write buffered rows to the database
without adding a new row. The CLOSE statement writes any remaining rows
before it closes an insert cursor.
If the current database uses explicit transactions, you must execute a PUT
statement within a transaction.
X/O The PUT statement is not an X/Open SQL statement. Therefore, you get a
warning message if you compile a PUT statement in X/Open mode. ♦
When all the inserted values are constants, the PUT statement has a special
effect. Instead of creating a row and putting it in the buffer, the PUT statement
merely increments a counter. When you use a FLUSH or CLOSE statement to
empty the buffer, one row and a repetition count are sent to the database
server, which inserts that number of rows.
If you are creating an insert cursor (using DECLARE with INSERT), you must
use only program variables in the VALUES clause. Variable names are not
recognized in the context of a prepared statement; you associate a prepared
statement with a cursor through its statement identifier.
The following ESQL/C example illustrates the use of an insert cursor. The
code includes the following statements:
int keep_going = 1;
EXEC SQL BEGIN DECLARE SECTION
struct cust_row { /* fields of a row of customer table */ } cust_rec;
EXEC SQL END DECLARE SECTION
main()
{
EXEC SQL connect to 'stores_demo';
EXEC SQL prepare ins_comp from
'insert into customer (customer_num, company) values (0, ?)';
EXEC SQL declare ins_curs cursor for ins_comp;
EXEC SQL open ins_curs;
while (1)
{
printf("\nEnter a customer: ");
gets(u_company);
EXEC SQL put ins_curs from :u_company;
printf("Enter another customer (y/n) ? ");
Each time the PUT statement executes, the values that the descriptor structure
describes are used to replace question-mark (?) placeholders in the INSERT
statement. This process is similar to using a FROM clause with a list of
variables, except that your program has full control over the memory
location of the data values.
The following ESQL/C example shows how to associate values from an sqlda
structure:
EXEC SQL put selcurs using descriptor pointer2;
To put elements, one at a time, into the insert cursor, use the PUT statement
and the FROM clause. The PUT statement identifies the collection cursor that
is associated with the collection variable. The FROM clause identifies the
element value to be inserted into the cursor. The data type of any host
variable in the FROM clause must match the element type of the collection.
Important: The collection variable stores the elements of the collection. However, it
has no intrinsic connection with a database column. Once the collection variable
contains the correct elements, you must then save the variable into the actual
collection column with the INSERT or UPDATE statement.
Suppose you have a table called children with the following structure:
CREATE TABLE children
(
age SMALLINT,
name VARCHAR(30),
fav_colors SET(VARCHAR(20)),
)
The following ESQL/C code fragment shows how to use an insert cursor to
put elements into a collection variable called child_colors:
EXEC SQL BEGIN DECLARE SECTION;
client collection child_colors;
char *favorites[]
(
"blue",
"purple",
"green",
"white",
"gold",
0
);
int a = 0;
char child_name[21];
EXEC SQL END DECLARE SECTION;
■ The buffer is too full to hold the new row at the start of a PUT
statement.
■ A FLUSH statement executes.
■ A CLOSE statement closes the cursor.
■ An OPEN statement executes, naming the cursor.
When the OPEN statement is applied to an open cursor, it closes the
cursor before reopening it; this implied CLOSE statement flushes the
buffer.
■ A COMMIT WORK statement executes.
■ The buffer contains BYTE or TEXT data (flushed after a single PUT
statement).
If the program terminates without closing an insert cursor, the buffer remains
unflushed. Rows that were inserted into the buffer since the last flush are lost.
Do not rely on the end of the program to close the cursor and flush the buffer.
Error Checking
The sqlca structure contains information on the success of each PUT
statement as well as information that lets you count the rows that were
inserted. The result of each PUT statement is contained in the following fields
of the sqlca: sqlca.sqlcode, SQLCODE and sqlca.sqlerrd[2].
Data buffering with an insert cursor means that errors are not discovered
until the buffer is flushed. For example, an input value that is incompatible
with the data type of the column for which it is intended is discovered only
when the buffer is flushed. When an error is discovered, rows in the buffer
that are located after the error are not inserted; they are lost from memory.
At any time, (total - pending) represents the number of rows that were
actually inserted. If all commands are successful, pending contains zero after
the cursor is closed. If an error occurs during a PUT, FLUSH, or CLOSE
statement, the value that remains in pending is the number of uninserted
(discarded) rows.
Related Information
Related statements: ALLOCATE DESCRIPTOR, CLOSE, DEALLOCATE
DESCRIPTOR, FLUSH, DECLARE, GET DESCRIPTOR, OPEN, PREPARE, and SET
DESCRIPTOR
For a task-oriented discussion of the PUT statement, see the Informix Guide to
SQL: Tutorial.
For further information about error checking, the system-descriptor area, and
the sqlda structure, see the Informix ESQL/C Programmer’s Manual.
+
RENAME COLUMN
Use the RENAME COLUMN statement to change the name of a column.
Syntax
Usage
You can rename a column of a table if any of the following conditions are true:
■ You own the table.
■ You have the DBA privilege on the database.
■ You have the Alter privilege on the table.
XPS You cannot rename the columns of a fragmented table if the table is
fragmented by range. For more information on tables fragmented by range,
see “RANGE Method Clause” on page 2-265. ♦
If you rename a column that appears in a check constraint, the text of the
check constraint in the syschecks system catalog table is updated to reflect
the new column name.
When the trigger executes, if the database server encounters a column name
that no longer exists in the table, it returns an error.
Related Information
Related statements: ALTER TABLE, CREATE TABLE, and RENAME TABLE
+
RENAME DATABASE
Use the RENAME DATABASE statement to change the name of a database.
Syntax
Usage
You can rename a database if either of the following statements is true:
You can only rename local databases. You can rename a local database from
inside an SPL routine.
Related Information
Related statement: CREATE DATABASE
+
RENAME TABLE
Use the RENAME TABLE statement to change the name of a table.
Syntax
Usage
You can rename a table if any of the following statements are true:
You cannot change the table owner by renaming the table. You can use the
owner. convention in the old name of the table, but an error occurs during
compilation if you try to use the owner. convention in the new name of the
table.
XPS If you are using Extended Parallel Server, you cannot rename a table that
contains a dependent GK index. ♦
ANSI In an ANSI-compliant database, you must use the owner. convention in the old
name of the table if you are referring to a table that you do not own. ♦
You cannot use the RENAME TABLE statement to move a table from the
current database to another database or to move a table from another
database to the current database. The table that you want to rename must
reside in the current database. The renamed table that results from the
statement remains in the current database.
■ The database server replaces the name of the table in the trigger
definition.
■ The table name is not replaced where it appears inside any triggered
actions.
■ The database server returns an error if the new table name is the
same as a correlation name in the REFERENCING clause of the trigger
definition.
The following example uses the RENAME TABLE statement as the last step:
CREATE TABLE new_table
(
item_num SMALLINT,
order_num INTEGER,
quantity SMALLINT,
stock_num SMALLINT,
manu_code CHAR(3),
total_price MONEY(8)
);
INSERT INTO new_table
SELECT item_num, order_num, quantity, stock_num,
manu_code, total_price
FROM items;
DROP TABLE items;
RENAME TABLE new_table TO items;
Related Information
Related statements: ALTER TABLE, CREATE TABLE, DROP TABLE, and
RENAME COLUMN.
+ REVOKE
Use the REVOKE statement to cancel any of the following items for specific
users or for a role:
■ Privileges on a database
■ Privileges on a table, synonym, or view
■ Privileges on a user-defined data type or user-defined routine (UDR)
■ A role name
Syntax
Role Name
Routine-Level p. 2-624
Privileges
p. 2-620
Language-Level
IDS Privileges
p. 2-622
Role
IDS Name
p. 2-624
Usage
You can revoke privileges if:
■ you granted them and did not name another user as grantor.
■ the GRANT statement named you as grantor.
■ you own an object on which PUBLIC has privileges by default.
■ you have database-level DBA privileges.
You cannot revoke privileges from yourself. You cannot revoke privileges
you granted if you named another user as grantor, nor can you revoke the
status as grantor from the other user.
Database-Level Privileges
CONNECT
RESOURCE
DBA
Similarly, if you revoke the Connect privilege from a user with the Resource
privilege, the statement has no effect. If you revoke the Resource privilege
from a user, the user retains the Connect privilege on the database.
The following table lists the appropriate keyword for each database-level
privilege.
Privilege Purpose
CONNECT Lets you query and modify data. You can modify the database
schema if you own the database object that you want to modify.
Any user with the Connect privilege can perform the following
functions:
■ Connect to the database with the CONNECT statement or
another connection statement
■ Execute SELECT, INSERT, UPDATE, and DELETE statements,
provided that the user has the necessary table-level privileges
■ Create views, provided that the user has the Select privilege on
the underlying tables
■ Create synonyms
■ Create temporary tables, and create indexes on the temporary
tables
■ Alter or drop a table or an index, provided that the user owns the
table or index (or has the Alter, Index, or References privilege on
the table)
■ Grant privileges on a table, provided that the user owns the table
(or was given privileges on the table with the WITH GRANT
OPTION keyword)
RESOURCE Lets you extend the structure of the database. In addition to the
capabilities of the Connect privilege, the holder of the Resource
privilege can perform the following functions:
■ Create new tables
■ Create new indexes
■ Create new UDRs
■ Create new data types
(1 of 2)
Privilege Purpose
DBA Has all the capabilities of the Resource privilege and can perform
the following functions in addition to t:
■ Grant any database-level privilege, including the DBA privilege,
to another user
■ Grant any table-level privilege to another user
■ Grant any table-level privilege to a role
■ Grant a role to a user or to another role
■ Restrict the Execute privilege to DBAs when registering a UDR
■ Execute the SET SESSION AUTHORIZATION statement
■ Use the NEXT SIZE keywords to alter extent sizes in the system
catalog tables
■ Drop any database object, regardless of who owns it
■ Create tables, views, and indexes as well as specify another user
as owner of the database objects
■ Execute the DROP DATABASE statement
■ Insert, delete, or update rows of any system catalog table except
systables
(2 of 2)
Warning: Although the user informix and DBAs can modify most system catalog
tables (only the user informix can modify systables), Informix strongly recom-
mends that you do not update, delete, or insert any rows in these tables. Modifying
the system catalog tables can destroy the integrity of the database. Informix does
support use of the ALTER TABLE statement to modify the size of the next extent of
system catalog tables.
Table-Level Privileges
ALL ON table
PRIVILEGES view
, synonym
INSERT
DELETE
SELECT
UPDATE
INDEX
ALTER
REFERENCES
IDS
UNDER
In one REVOKE statement, you can list one or more of the following keywords
to specify the privileges you want to revoke from the same users.
Privilege Purpose
ALTER Lets you add or delete columns, modify column data types, add
or delete constraints, change the locking mode of a table from
PAGE to ROW, or add or drop a corresponding row type name for
your table.
This privilege also lets you set the database object mode of unique
indexes and constraints to the enabled, disabled, or filtering
mode. In addition, this privilege lets you set the database object
mode of non-unique indexes and triggers to the enabled or
disabled modes.
If a user receives the same privilege from two different grantors and one
grantor revokes the privilege, the grantee still has the privilege until the
second grantor also revokes the privilege. For example, if both you and a DBA
grant the Update privilege on your table to ted, both you and the DBA must
revoke the Update privilege to prevent ted from updating your table.
The REVOKE statement results in ISAM error message 111, No record found,
because the system catalog tables (syscolauth or systabauth) contain no
table-level privilege entry for a user named ted. The REVOKE does not
prevent ted from having all the table-level privileges given to PUBLIC on the
customer table.
To restrict table-level privileges, first revoke the privileges with the PUBLIC
keyword, then re-grant them to the appropriate users. The following
example revokes the Index and Alter privileges from all users for the
customer table and grants these privileges specifically to user mary:
REVOKE INDEX, ALTER ON customer FROM PUBLIC
GRANT INDEX, ALTER ON customer TO mary
In the following example, mary first receives the ability to reference four
columns in customer, then the table owner restricts references to two
columns:
GRANT REFERENCES (fname, lname, company, city) ON
customer TO mary
REVOKE REFERENCES ON customer FROM mary
GRANT REFERENCES (company, city)
ON customer TO mary
The following example shows how to restrict Select privileges for PUBLIC to
certain columns:
REVOKE SELECT ON customer FROM PUBLIC
GRANT SELECT (fname, lname, company, city)
ON customer TO PUBLIC
For example, assume that the user hal has the Select and Insert privileges on
the customer table. User jocelyn wants to revoke all seven table-level privi-
leges from user hal. So user jocelyn issues the following REVOKE statement:
REVOKE ALL ON customer FROM hal
Usage Privilege
Any user can reference a built-in data type in an SQL statement, but not a
distinct data type based on a built-in data type. The creator of a user-defined
data type or a DBA must explicitly grant the Usage privilege on that new
type, including a distinct data type based on a built-in data type.
REVOKE with the USAGE ON TYPE keywords removes the Usage privilege
that you granted earlier to another user or role.
Under Privilege
You own a named-row type that you create. If you want other users to be able
to create subtypes under this named-row type, you must grant these users
the Under privilege on your named-row type. If you later want to remove the
ability of these users to create subtypes under the named-row type, you must
revoke the Under privilege from these users. A REVOKE statement with the
UNDER ON TYPE keywords removes the Under privilege that you granted
earlier to these users.
For example, suppose that you have created a row type named rtype1:
CREATE ROW TYPE rtype1
(cola INT, colb INT)
If you want another user named kathy to be able to create a subtype under
this named-row type, you must grant the Under privilege on this named-row
type to user kathy:
GRANT UNDER on rtype1 to kathy
Now user kathy can create another row type under the rtype1 row type even
though kathy is not the owner of the rtype1 row type:
CREATE ROW TYPE rtype2
(colc INT, cold INT)
UNDER rtype1
If you later want to remove the ability of user kathy to create subtypes under
the rtype1 row type, enter the following statement:
REVOKE UNDER on rtype1 FROM kathy
Routine-Level Privileges
If you revoke the EXECUTE privilege on a user-defined routine (UDR) from a
user, that user can no longer execute that UDR in any way. For information on
the ways a user can execute a UDR, see “Routine-Level Privileges” on
page 2-513.
EXECUTE ON SPL_routine
IDS
PROCEDURE routine ( )
FUNCTION
Routine Parameter List
ROUTINE p. 4-286
Specific Name
SPECIFIC PROCEDURE p. 4-296
FUNCTION
ROUTINE
When you create a UDR under any of the following circumstances, you must
explicitly grant the Execute privilege before you can revoke it:
IDS Any negator function for which you grant the Execute privilege requires a
separate, explicit REVOKE statement. ♦
When you create a UDR without any of the preceding conditions in effect,
PUBLIC can execute your UDR without a GRANT statement. To limit who
executes your UDR, revoke the privilege using the keywords FROM PUBLIC
and then grant it to a user list (see “User List” on page 2-623) or role (see
“Role Name” on page 2-624).
IDS If two or more UDRs have the same name, use the appropriate keyword from
the following list to specify which of those UDRs a user can no longer execute.
PRIVILEGE Purpose
USAGE ON LANGUAGE C
JAVA
SPL
If you want to revoke the Usage privilege on a language from a user or role,
issue a REVOKE USAGE ON LANGUAGE statement.
The effect of issuing this statement is that the user or role can no longer
register UDRs that are written in the specified language. For example, if you
revoke the default Usage privilege on the SPL language from PUBLIC, the
ability to create SPL routines is taken away from all users:
REVOKE USAGE ON LANGUAGE SPL FROM PUBLIC
User List
In the user list, you identify who loses the privileges you are revoking. The
user list can consist of the logins for a single user or multiple users, separated
by commas. If you use the PUBLIC keyword as the user list, the REVOKE
statement revokes privileges from all users.
PUBLIC
,
user
When the user list contains specific logins, you can combine the REVOKE
statement with the GRANT statement to selectively secure tables, columns,
UDRs, types, and so forth. For examples, see “When to Use REVOKE Before
GRANT” on page 2-616.
Spell the user names in the list exactly as they were spelled in the GRANT
statement. In a database that is not ANSI compliant, you can optionally use
quotes around each user in the list.
ANSI In an ANSI-compliant database, if you do not use quotes around user, the
name of the user is stored in uppercase letters. ♦
When you revoke a role that was granted with the WITH GRANT OPTION,
both the role and grant option are revoked. “Revoking Privileges Granted
WITH GRANT OPTION” on page 2-625 explains revoking such a role.
role_name
The following examples show the effects of REVOKE with role name:
■ Remove users or another role name from inclusion in the role
REVOKE accounting FROM mary
REVOKE payroll FROM accounting
■ Remove one or more privileges from a role
REVOKE UPDATE ON employee FROM accounting
When you revoke table-level privileges from a role, you cannot use the
RESTRICT or CASCADE clauses.
Thus, when you revoke privileges from users or a role, you also revoke the
same privilege resulting from GRANT statements:
The following examples illustrate this situation. You, as the owner of the table
items, issue the following statements to grant access to the user mary:
REVOKE ALL ON items FROM PUBLIC
GRANT SELECT, UPDATE ON items TO mary WITH GRANT OPTION
The user mary uses her new privilege to grant users cathy and paul access to
the table.
GRANT SELECT, UPDATE ON items TO cathy
GRANT SELECT ON items TO paul
This single statement effectively revokes all privileges on the items table
from the users mary, cathy, and paul.
The CASCADE keyword has the same effect as this default condition.
However, if you revoke the Under privilege on a named-row type with the
CASCADE option, and the row type is in use, the REVOKE statement fails. This
exception to the normal behavior of the CASCADE option results from the fact
that the database server supports the DROP ROW TYPE statement with the
RESTRICT keyword only.
For example, assume that user jeff creates a row type named rtype1 and
grants the Under privilege on that row type to user mary. User mary now
creates a row type named rtype2 under row type rtype1 and grants the
Under privilege on row type rtype2 to user andy. Then user andy creates a
row type named rtype3 under row type rtype2. Now user jeff tries to revoke
the Under privilege on row type rtype1 from user mary with the CASCADE
option. The REVOKE statement fails because row type rtype2 is still in use by
row type rtype3.
A REVOKE statement does not fail if it pertains to a user who has the right to
grant the privilege to any other user but does not exercise that right, as the
following example shows:
Assume that the user clara uses the WITH GRANT OPTION clause to grant the
Select privilege on the customer table to the user ted.
Assume that user ted, in turn, grants the Select privilege on the customer
table to user tania. The following REVOKE statement issued by clara fails
because ted used his authority to grant the Select privilege:
REVOKE SELECT ON customer FROM ted RESTRICT
By contrast, if user ted does not grant the Select privilege to tania or any other
user, the same REVOKE statement succeeds.
Even if ted does grant the Select privilege to another user, either of the
following statements succeeds:
REVOKE SELECT ON customer FROM ted CASCADE
REVOKE SELECT ON customer FROM ted
Related Information
Related Statements: GRANT, GRANT FRAGMENT, and REVOKE FRAGMENT
For information about roles, see the following statements: CREATE ROLE,
DROP ROLE, and SET ROLE.
In the Informix Guide to Database Design and Implementation, see the discussion
of privileges.
+ REVOKE FRAGMENT
IDS
Use the REVOKE FRAGMENT statement to revoke privileges that were
granted on individual fragments of a fragmented table. You can use this
statement to revoke the Insert, Update, and Delete fragment-level privileges
from users.
Syntax
Fragment-Level
REVOKE FRAGMENT Privileges ON table
p. 2-629
FROM user
,
' user '
( dbspace )
Usage
Use the REVOKE FRAGMENT statement to revoke the Insert, Update, or
Delete privilege on one or more fragments of a fragmented table from one or
more users.
The REVOKE FRAGMENT statement is only valid for tables that are
fragmented according to an expression-based distribution scheme. For an
explanation of an expression-based distribution scheme, see “Syntax” on
page 2-12.
Fragment-Level Privileges
ALL
,
INSERT
DELETE
UPDATE
Privilege Purpose
UPDATE Lets you update rows in the fragment and to name any column of
the table in an UPDATE statement
For example, assume that a user currently has the Update privilege on one
fragment of a table. If you use the ALL keyword to revoke all current privi-
leges on this fragment from this user, the user loses the Update privilege that
he or she had on this fragment.
Related Information
Related statements: GRANT FRAGMENT and REVOKE
ROLLBACK WORK
Use the ROLLBACK WORK statement to cancel a transaction deliberately and
undo any changes that occurred since the beginning of the transaction. The
ROLLBACK WORK statement restores the database to the state that it was in
before the transaction began.
Syntax
ROLLBACK
WORK
Usage
The ROLLBACK WORK statement is valid only in databases with transactions.
The ROLLBACK WORK statement releases all row and table locks that the
cancelled transaction holds. If you issue a ROLLBACK WORK statement when
no transaction is pending, an error occurs.
E/C In ESQL/C, the ROLLBACK WORK statement closes all open cursors except
those that are declared with hold. Hold cursors remain open after a trans-
action is committed or rolled back.
If you use the ROLLBACK WORK statement within an SPL routine that a
WHENEVER statement calls, specify WHENEVER SQLERROR CONTINUE and
WHENEVER SQLWARNING CONTINUE before the ROLLBACK WORK
statement. This step prevents the program from looping if the ROLLBACK
WORK statement encounters an error or a warning. ♦
WORK Keyword
The WORK keyword is optional in a ROLLBACK WORK statement. The
following two statements are equivalent:
ROLLBACK;
ROLLBACK WORK;
Related Information
Related statements: BEGIN WORK and COMMIT WORK
For a discussion of transactions and ROLLBACK WORK, see the Informix Guide
to SQL: Tutorial.
SELECT
Use the SELECT statement to query a database or the contents of an SPL or
ESQL/C collection variable.
Syntax
UNION
UNION ALL
Select
SELECT Clause
p. 2-636
+ Optimizer E/C INTO
Directives Clause
IDS p. 4-244 SPL p. 2-645
FROM
Clause
p. 2-649
WHERE GROUP BY HAVING
Clause Clause Clause
p. 2-658 p. 2-668 p. 2-671
+ +
ORDER BY INTO Table
Clause FOR READ ONLY Clauses
p. 2-673 p. 2-682
FOR UPDATE
,
OF column
Usage
You can query the tables in the current database, a database that is not
current, or a database that is on a different database server from your current
database.
The SELECT statement includes many basic clauses. Each clause is described
in the following list.
Clause Purpose
FOR READ ONLY Specifies that the values returned by the SELECT
statement cannot be updated after a fetch
INTO EXTERNAL Loads an external table with the results of the query
SELECT Clause
The SELECT clause contains the list of database objects or expressions to be
selected, as shown in the following diagram
,
Select
List
FIRST num ALL
XPS DISTINCT
MIDDLE +
UNIQUE
Select
List
Expression
p. 4-73
display_label
AS
*
table.
view.
synonym.
alias.
XPS
external.
( subquery )
IDS
Collection Subquery
p. 4-24
In the SELECT clause, specify exactly what data is being selected as well as
whether you want to omit duplicate values.
When you use this option with an ORDER BY clause, you can retrieve the first
number of rows according to the order criteria. For example, the following
query finds the ten highest-paid employees.
SELECT FIRST 10 name, salary
FROM emp
ORDER BY salary DESC
XPS If you are using Extended Parallel Server, you can also use the FIRST option
to select the first rows that result from a union query. In the following
example, the FIRST option is applied to the result of the UNION expression.
SELECT FIRST 10 a, b FROM tab1 UNION SELECT a, b FROM tab2
The syntax and restrictions for this option are the same as those for the FIRST
option. For more information see “Using the FIRST Option” on page 2-638.
Allowing Duplicates
You can apply the ALL, UNIQUE, or DISTINCT keywords to indicate whether
duplicate values are returned, if any exist. If you do not specify any
keywords, all the rows are returned by default.
Keyword Purpose
For example, the following query lists the stock_num and manu_code of all
items that have been ordered, excluding duplicate items:
SELECT DISTINCT stock_num, manu_code FROM items
You can use the DISTINCT or UNIQUE keywords once in each level of a query
or subquery. For example, the following query uses DISTINCT in both the
query and the subquery:
SELECT DISTINCT stock_num, manu_code FROM items
WHERE order_num = (SELECT DISTINCT order_num FROM orders
WHERE customer_num = 120)
You cannot use variable names (for example, a host variable in an ESQL/C
application) in the select list by themselves. You can include a variable name
in the select list, however, if an arithmetic or concatenation operator connects
it to a constant.
Selecting Columns
Column expressions are the most commonly used expressions in a SELECT
statement. For a complete description of the syntax and use of column
expressions, see “Column Expressions” on page 4-91.
Selecting Constants
If you include a constant expression in the select list, the same value is
returned for each row that the query returns. For a complete description of
the syntax and use of constant expressions, see “Constant Expressions” on
page 4-108.
The following example calls the get_orders user-defined function for each
customer_num and displays the output of the function under the n_orders
label:
SELECT customer_num, lname,
get_orders(customer_num) n_orders
FROM customer
SPL If a called SPL routine contains certain SQL statements, the database server
returns an error. For information on which SQL statements cannot be used in
an SPL routine that is called within a data manipulation statement, see
“Restrictions on an SPL Routine Called in a Data Manipulation Statement”
on page 4-302. ♦
You can also enter an asterisk in place of a field name to signify that all fields
of the row-type column are to be selected. For example, if the my_tab table
has a row-type column named rowcol that contains four fields, the following
SELECT statement retrieves all four fields of the rowcol column:
You can also retrieve all fields from a row-type column by specifying the
column name without any dot notation. The following SELECT statement has
the same effect as the preceding SELECT statement:
SELECT rowcol FROM my_tab
You can use dot notation not only with row-type columns but with expres-
sions that evaluate to row-type values. For more information on the use of
dot notation with row-type columns and expressions, see “Column Expres-
sions” on page 4-91 in the Expression segment.
DB In DB-Access, a display label appears as the heading for that column in the
output of the SELECT statement. ♦
E/C In ESQL/C, the value of display_label is stored in the sqlname field of the sqlda
structure. For more information on the sqlda structure, see the Informix
ESQL/C Programmer’s Manual. ♦
For a list of SQL reserved words, see Appendix A, “Reserved Words for
Dynamic Server.”
If you are using the SELECT statement in creating a view, do not use display
labels. Specify the desired label names in the CREATE VIEW column list
instead.
INTO Clause
Use the INTO clause in an SPL routine or an ESQL/C program to specify the
program variables or host variables to receive the data that the SELECT
statement retrieves. The following diagram shows the syntax of the INTO
clause.
INTO output_var
E/C
: indicator_var
+
$ indicator_var
INDICATOR indicator_var
data_structure
You must specify an INTO clause with SELECT to name the variables that
receive the values that the query returns. If the query returns more than one
value, the values are returned into the list of variables in the order in which
you specify them.
If the SELECT statement stands alone (that is, it is not part of a DECLARE
statement and does not use the INTO clause), it must be a singleton SELECT
statement. A singleton SELECT statement returns only one row.
SPL In an SPL routine, if a SELECT returns more than one row, you must use the
FOREACH statement to access the rows individually. The INTO clause of the
SELECT statement holds the fetched values. For more information, see
“FOREACH” on page 3-30. ♦
The following ESQL/C code examples show different ways you can use the
INTO clause. As both examples show, first you must use the DECLARE
statement to declare a cursor.
i = 5
j = 2
EXEC SQL declare c cursor for
select order_num, po_num into :a[i], :a[j] from orders
where order_num =1005 and po_num =2865
You can also use program variables in the FETCH statement to specify an
element of a program array in the INTO clause. With the FETCH statement, the
program variables are evaluated at each fetch rather than when you declare
the cursor.
Error Checking
If the data type of the receiving variable does not match that of the selected
item, the data type of the selected item is converted, if possible. If the
conversion is impossible, an error occurs, and a negative value is returned in
the status variable, sqlca.sqlcode, SQLCODE. In this case, the value in the
program variable is unpredictable.
FROM Clause
The FROM clause lists the table or tables from which you are selecting the
data. The following diagrams show the syntax of the FROM clause.
FROM table
XPS external
IDS
ONLY (table)
(synonym)
+
IDS Collection Derived Table
E/C p. 4-9
SPL
table
XPS
XPS view alias
num SAMPLES OF
LOCAL +
synonym
XPS AS
+ external
OUTER table
view alias
synonym AS
IDS
ONLY (table )
(synonym)
OUTER ( table )
view alias , Additional
Tables
synonym AS
IDS
ONLY (table )
(synonym )
Use the keyword OUTER to form outer joins. Outer joins preserve rows that
otherwise would be discarded by simple joins. If you have a complex outer
join, that is, the query has more than one outer join, you must embed the
additional outer join or joins in parentheses as the syntax diagram shows. For
more information on outer joins, see the Informix Guide to SQL: Tutorial.
When one of the tables to be joined is a collection, the FROM clause cannot
have a join. This restriction applies when you use a collection variable to hold
your collection derived table. For more information, see “Collection Derived
Table” on page 4-9.
You can supply an alias for a table name or view name in the FROM clause. If
you do so, you must use the alias to refer to the table or view in other clauses
of the SELECT statement. Aliases are especially useful with a self-join. For
more information about self-joins, see “WHERE Clause” on page 2-658.
The following example shows typical uses of the FROM clause. The first
query selects all the columns and rows from the customer table. The second
query uses a join between the customer and orders table to select all the
customers who have placed orders.
SELECT * FROM customer
The following example is the same as the second query in the preceding
example, except that it establishes aliases for the tables in the FROM clause
and uses them in the WHERE clause:
SELECT fname, lname, order_num
FROM customer c, orders o
WHERE c.customer_num = o.customer_num
The following example uses the OUTER keyword to create an outer join and
produce a list of all customers and their orders, regardless of whether they
have placed orders:
SELECT c.customer_num, lname, order_num
FROM customer c, OUTER orders o
WHERE c.customer_num = o.customer_num
If you do not assign an alias name to a collection derived table, the database
server assigns an implementation-dependent name to it.
You qualify the name of a table with the LOCAL keyword to indicate that you
want to retrieve rows from fragments only on the local coserver. The LOCAL
keyword has no effect on data that is retrieved from nonfragmented tables.
When a query involves a join, you must plan carefully if you want to extract
data that the client can aggregate. The simplest way to ensure that a join will
retrieve data suitable for aggregation is to limit the number of LOCAL tables
to one. The client can then aggregate data with respect to that table.
The following example shows a query that returns data suitable for aggre-
gation by the client:
SELECT x.col1, y.col2
FROM LOCAL tab1 x, tab2 y{can be aggregated by client}
INTO TEMP t1
WHERE x.col1 = y.col1;{tab1 is local}
The following example shows data that the client cannot aggregate:
SELECT x.col1, y.col2
FROM LOCAL tab1 x, LOCAL tab2 y{cannot be aggregated by
client}
INTO SCRATCH s4
WHERE x.col1 = y.col1;{tab1 and tab2 are local}
The client must submit exactly the same query to each coserver to retrieve
data that can be aggregated.
You can use a sampled query to gather quickly an approximate profile of data
within a large table. If you use a sufficiently large sample size, you can
examine trends in the data by sampling the data instead of scanning all the
data. In such cases, sampled queries can provide better performance than
scanning the data.
A sampled query has at least one sampled table. You do not need to sample
all tables in a sampled query. You can specify the SAMPLES OF option for
some tables in the FROM clause but not specify it for other tables.
For example, you might want to generate a list of how many of each part is
sold from the parts_sold table, which is known to contain approximately
100,000,000 rows. The following query provides a sampling ratio of one
percent and returns an approximate result:
SELECT part_number, COUNT(*) * 100 AS how_many
FROM 1000000 SAMPLES OF parts_sold
GROUP BY part_number;
The Collection Derived Table segment identifies the collection variable from
which to select the elements. For more information, see “Collection Derived
Table” on page 4-9.
■ You can select the contents (if any) of a collection column into a
collection variable.
You can assign the data type of the column to the collection variable
if the collection is of type COLLECTION (that is, an untyped collection
variable).
■ You can select the contents from a collection variable to determine
the data that you might want to update.
■ You can select the contents from a collection variable INTO another
variable in order to update certain collection elements.
The INTO clause identifies the variable for the element value that is
selected from the collection variable. The type of the host variable in
the INTO clause must be compatible with the element type of the
collection.
E/C ■ You can use a collection cursor to select one or more elements from
an ESQL/C collection variable. For more information, including
restrictions on the SELECT statement that you use, see “Associating
a Cursor With a Collection Variable” on page 2-367 in the DECLARE
statement. ♦
SPL ■ You can use a collection cursor to select one or more elements from
an SPL collection variable. For more information, including restric-
tions on the SELECT statement that you use, see “Using a
SELECT...INTO Statement” on page 3-33 of the FOREACH
statement. ♦
For more information, see the Collection Derived Table segment and the
INSERT, UPDATE, or DELETE statements.
The SELECT statement and the Collection Derived Table segment allow you
to select a particular field or group of fields in the row variable. The INTO
clause identifies the variable that holds the field value selected from the row
variable. The data type of the host variable in the INTO clause must be
compatible with the field type.
For example, the following code fragment puts the value of the width field
into the rect_width host variable:
EXEC SQL BEGIN DECLARE SECTION;
row (x int, y int, length float, width float) myrect;
double rect_width;
EXEC SQL END DECLARE SECTION;
...
EXEC SQL select rect into :myrect from rectangles
where area = 200;
EXEC SQL select width into :rect_width from table(:myrect);
You can modify the row variable with the Collection Derived Table segment
of the UPDATE statements. (The INSERT and DELETE statements do not
support a row variable in the Collection Derived Table segment.) The row
variable stores the fields of the row. However, it has no intrinsic connection
with a database column. Once the row variable contains the correct field
values, you must then save the variable into the row column with one of the
following SQL statements:
■ To update the row column in the table with the row variable, use an
UPDATE statement on a table or view name and specify the row
variable in the SET clause.
For more information, see “Updating Row-Type Columns” on
page 2-826.
■ To insert a row in a column, use the INSERT statement on a table or
view name and specify the row variable in the VALUES clause.
For more information, see “Inserting Values into Row-Type
Columns” on page 2-546.
For more information on how to use SPL row variables, see the Informix
Guide to SQL: Tutorial. For more information on how to use ESQL/C row
variables, see the discussion of complex data types in the Informix ESQL/C
Programmer’s Manual.
WHERE Clause
Use the WHERE clause to specify search criteria and join conditions on the
data that you are selecting.
AND
OR
WHERE Condition
p. 4-27
Join
p. 2-665
Function Expression
p. 4-121
( subquery )
IDS
( Collection Subquery )
p. 4-24
■ Relational-operator condition
■ BETWEEN
■ IN
■ IS NULL
■ LIKE or MATCHES
You also can use a SELECT statement within the WHERE clause; this is called
a subquery. The following list contains the kinds of subquery WHERE clauses:
■ IN
■ EXISTS
■ ALL, ANY, SOME
Examples of each type of condition are shown in the following sections. For
more information about each kind of condition, see “Condition” on page 27.
You cannot use an aggregate function in the WHERE clause unless it is part of
a subquery or if the aggregate is on a correlated column originating from a
parent query and the WHERE clause is within a subquery that is within a
HAVING clause.
Relational-Operator Condition
For a complete description of the relational-operator condition, see
“Relational-Operator Condition” on page 4-32.
BETWEEN Condition
For a complete description of the BETWEEN condition, see “BETWEEN
Condition” on page 4-33.
The BETWEEN condition is satisfied when the value to the left of the
BETWEEN keyword lies in the inclusive range of the two values on the right
of the BETWEEN keyword. The first two queries in the following example use
literal values after the BETWEEN keyword. The third query uses the built-in
CURRENT function and a literal interval. It looks for dates between the
current day and seven days earlier.
SELECT stock_num, manu_code FROM stock
WHERE unit_price BETWEEN 125.00 AND 200.00
IN Condition
For a complete description of the IN condition, see “IN Subquery” on
page 4-41.
The IN condition is satisfied when the expression to the left of the IN keyword
is included in the list of values to the right of the keyword. The following
examples show the IN condition:
SELECT lname, fname, company
FROM customer
WHERE state IN ('CA','WA', 'NJ')
IS NULL Condition
For a complete description of the IS NULL condition, see “IS NULL
Condition” on page 4-36.
The IS NULL condition is satisfied if the column contains a null value. If you
use the NOT option, the condition is satisfied when the column contains a
value that is not null. The following example selects the order numbers and
customer numbers for which the order has not been paid:
SELECT order_num, customer_num FROM orders
WHERE paid_date IS NULL
The LIKE or MATCHES condition is satisfied when either of the following tests
is true:
The following SELECT statement returns all rows in the customer table in
which the lname column begins with the literal string 'Baxter'. Because
the string is a literal string, the condition is case sensitive.
SELECT * FROM customer WHERE lname LIKE 'Baxter%'
The following SELECT statement returns all rows in the customer table in
which the value of the lname column matches the value of the fname
column:
SELECT * FROM customer WHERE lname LIKE fname
The following examples use the LIKE condition with a wildcard. The first
SELECT statement finds all stock items that are some kind of ball. The second
SELECT statement finds all company names that contain a percent sign (%).
The backslash (\) is used as the standard escape character for the wildcard
percent sign (%). The third SELECT statement uses the ESCAPE option with
the LIKE condition to retrieve rows from the customer table in which the
company column includes a percent sign (%). The z is used as an escape
character for the wildcard percent sign (%).
SELECT stock_num, manu_code FROM stock
WHERE description LIKE '%ball'
IN Subquery
For a complete description of the IN subquery, see “IN Condition” on
page 4-34.
With the IN subquery, more than one row can be returned, but only one
column can be returned. The following example shows the use of an IN
subquery in a SELECT statement:
SELECT DISTINCT customer_num FROM orders
WHERE order_num NOT IN
(SELECT order_num FROM items
WHERE stock_num = 1)
EXISTS Subquery
For a complete description of the EXISTS subquery, see “EXISTS Subquery”
on page 4-42.
The preceding example would work equally well if you use a SELECT * in the
subquery in place of the column names because you are testing for the
existence of a row or rows.
In the following example, the SELECT statements return the order number of
all orders that contain an item whose total price is greater than the total price
of every item in order number 1023. The first SELECT statement uses the ALL
subquery, and the second SELECT statement produces the same result by
using the MAX aggregate function.
SELECT DISTINCT order_num FROM items
WHERE total_price > ALL (SELECT total_price FROM items
WHERE order_num = 1023)
The following SELECT statements return the order number of all orders that
contain an item whose total price is greater than the total price of at least one
of the items in order number 1023. The first SELECT statement uses the ANY
keyword, and the second SELECT statement uses the MIN aggregate function.
SELECT DISTINCT order_num FROM items
WHERE total_price > ANY (SELECT total_price FROM items
WHERE order_num = 1023)
You can omit the keywords ANY, ALL, or SOME in a subquery if you know
that the subquery returns exactly one value. If you omit ANY, ALL, or SOME,
and the subquery returns more than one value, you receive an error. The
subquery in the following example returns only one row because it uses an
aggregate function:
SELECT order_num FROM items
WHERE stock_num = 9 AND quantity =
(SELECT MAX(quantity) FROM items WHERE stock_num = 9)
Relational Operator
column p. 4-265 column
table. table.
view. view.
synonym. synonym.
alias. alias.
XPS XPS
external. external.
Two-Table Joins
The following example shows a two-table join:
SELECT order_num, lname, fname
FROM customer, orders
WHERE customer.customer_num = orders.customer_num
Tip: You do not have to specify the column where the two tables are joined in the
SELECT list.
Multiple-Table Joins
A multiple-table join is a join of more than two tables. Its structure is similar
to the structure of a two-table join, except that you have a join condition for
more than one pair of tables in the WHERE clause. When columns from
different tables have the same name, you must distinguish them by
preceding the name with its associated table or table alias, as in table.column.
For the full syntax of a table name, see “Database Object Name” on page 4-50.
The following multiple-table join yields the company name of the customer
who ordered an item as well as the stock number and manufacturer code of
the item:
SELECT DISTINCT company, stock_num, manu_code
FROM customer c, orders o, items i
WHERE c.customer_num = o.customer_num
AND o.order_num = i.order_num
Self-Joins
You can join a table to itself. To do so, you must list the table name twice in
the FROM clause and assign it two different table aliases. Use the aliases to
refer to each of the two tables in the WHERE clause.
The following example is a self-join on the stock table. It finds pairs of stock
items whose unit prices differ by a factor greater than 2.5. The letters x and y
are each aliases for the stock table.
SELECT x.stock_num, x.manu_code, y.stock_num, y.manu_code
FROM stock x, stock y
WHERE x.unit_price > 2.5 * y.unit_price
XPS If you are using Extended Parallel Server, you cannot use a self-join with an
external table. ♦
Outer Joins
The following outer join lists the company name of the customer and all
associated order numbers, if the customer has placed an order. If not, the
company name is still listed, and a null value is returned for the order
number.
SELECT company, order_num
FROM customer c, OUTER orders o
WHERE c.customer_num = o.customer_num
XPS If you are using Extended Parallel Server, you cannot use an external table as
the outer table in an outer join. ♦
For more information about outer joins, see the Informix Guide to SQL:
Tutorial.
GROUP BY Clause
Use the GROUP BY clause to produce a single row of results for each group.
A group is a set of rows that have the same values for each column listed.
GROUP BY column
table.
view.
synonym.
alias.
XPS
external.
+ select_number
If you are selecting a BYTE or TEXT column, you cannot use the GROUP BY
clause. In addition, you cannot use ROWID in a GROUP BY clause.
IDS If your select list includes a column with a user-defined data type, the type
must either use the built-in bit-hashing function or have its own user-defined
hash function. Otherwise, you cannot use a GROUP BY clause. ♦
If a column stands alone in a column expression in the select list, you must
use it in the GROUP BY clause. If a column is combined with another column
by an arithmetic operator, you can choose to group by the individual
columns or by the combined expression using a specific number.
HAVING Clause
Use the HAVING clause to apply one or more qualifying conditions to groups.
HAVING Condition
p. 4-27
You can use the HAVING clause to place conditions on the GROUP BY column
values as well as on calculated values. The following example returns the
customer_num, call_dtime (in full year-to-fraction format), and cust_code,
and groups them by call_code for all calls that have been received from
customers with customer_num less than 120:
SELECT customer_num, EXTEND (call_dtime), call_code
FROM cust_calls
GROUP BY call_code, 2, 1
HAVING customer_num < 120
ORDER BY Clause
Use THE ORDER BY clause to sort query results by the values that are
contained in one or more columns.
ORDER BY column
+
table. ASC
[first, last]
view. DESC
synonym.
alias.
XPS
external.
select_number
display_label
+
ROWID
IDS
(1 of 3)
(2 of 3)
The following query explicitly selects the order date and shipping date from
the orders table and then rearranges the query by the order date. By default,
the query results are listed in ascending order.
SELECT order_date, ship_date FROM orders
ORDER BY order_date
The following example shows a SELECT statement that queries the customer
table and specifies a column substring in the ORDER BY column. The column
substring instructs the database server to sort the query results by the portion
of the lname column contained in the sixth through ninth positions of the
column:
SELECT * from customer
ORDER BY lname[6,9]
Assume that the value of lname in one row of the customer table is
Greenburg. Because of the column substring in the ORDER BY clause, the
database server determines the sort position of this row by using the value
burg, not the value Greenburg.
You can specify column substrings only for columns that have a character
data type. If you specify a column substring in the ORDER BY clause, the
column must have one of the following data types: BYTE, CHAR, NCHAR,
NVARCHAR, TEXT, or VARCHAR.
GLS For information on the GLS aspects of using column substrings in the ORDER
BY clause, see the Informix Guide to GLS Functionality. ♦
Nested Ordering
If you list more than one column in the ORDER BY clause, your query is
ordered by a nested sort. The first level of sort is based on the first column;
the second column determines the second level of sort. The following
example of a nested sort selects all the rows in the cust_calls table and orders
them by call_code and by call_dtime within call_code:
SELECT * FROM cust_calls
ORDER BY call_code, call_dtime
Select numbers are required in the ORDER BY clause when SELECT statements
are joined by the UNION or UNION ALL keywords or compatible columns in
the same position have different names.
If you want to specify the rowid column in the ORDER BY clause, enter the
keyword ROWID in lowercase or uppercase letters.
You cannot specify the rowid column in the ORDER BY clause if the table from
which you are selecting is a fragmented table that does not have a rowid
column.
You cannot specify the rowid column in the ORDER BY clause unless you
have included the rowid column in the select list of the SELECT clause.
For further information on how to use the rowid column in column expres-
sions, see “Expression” on page 4-73.
The FOR UPDATE keyword notifies the database server that updating is
possible, causing it to use more-stringent locking than it would with a select
cursor. You cannot modify data through a cursor without this clause. You can
specify particular columns that can be updated.
After you declare a cursor for a SELECT... FOR UPDATE statement, you can
update or delete the currently selected row using an UPDATE OR DELETE
statement with the WHERE CURRENT OF clause. The words CURRENT OF
refer to the row that was most recently fetched; they replace the usual test
expressions in the WHERE clause.
To update rows with a particular value, your program might contain state-
ments such as the sequence of statements shown in the following example:
EXEC SQL BEGIN DECLARE SECTION;
char fname[ 16];
char lname[ 16];
EXEC SQL END DECLARE SECTION;
.
.
.
for (;;)
{
EXEC SQL fetch xc into $fname, $lname;
if (strncmp(SQLSTATE, '00', 2) != 0) break;
printf("%d %s %s\n",cnum, fname, lname );
if (cnum == 999)--update rows with 999 customer_num
EXEC SQL update customer set fname = 'rosey' where current of xc;
}
ANSI If you have used the High-Performance Loader (HPL) in express mode to
load data into the tables of an ANSI-compliant database, and you have not yet
performed a level-0 backup of this data, the database is in read-only mode.
When the database is in read-only mode, the database server rejects any
attempts by a select cursor to access the data unless the SELECT or the
DECLARE includes a FOR READ ONLY clause. This restriction remains in effect
until the user has performed a level-0 backup of the data.
The solution is to include the FOR READ ONLY clause in your select cursors.
The read-only cursor that this clause specifies is compatible with the read-
only mode of the database. For example, the following SELECT FOR READ
ONLY statement against the customer_ansi table succeeds:
DB DB-Access executes all SELECT statements with select cursors. Therefore, you
must include the FOR READ ONLY clause in all SELECT statements that access
data in a read-only ANSI-mode database. The FOR READ ONLY clause causes
DB-Access to declare the cursor for the SELECT statement as a read-only
cursor. ♦
For more information on level-0 backups, see your Backup and Restore Guide.
For more information on select cursors, read-only cursors, and update
cursors, see “DECLARE” on page 2-349.
IDS For more information on the express mode of the HPL, see the Guide to the
High-Performance Loader. ♦
WITH NO LOG
XPS
SCRATCH table
DATAFILES
EXTERNAL table USING ( Clause )
p. 2-137
Table Table
Options , , Options
p. 2-686 p. 2-686
Naming Columns
The column names of the temporary, scratch, or external table are those that
are named in the SELECT clause. You must supply a display label for all
expressions other than simple column expressions. The display label for a
column or expression becomes the column name in the temporary, scratch or
external table. If you do not provide a display label for a column expression,
the table uses the column name from the select list.
The following INTO TEMP example creates the pushdate table with two
columns, customer_num and slowdate:
SELECT customer_num, call_dtime + 5 UNITS DAY slowdate
FROM cust_calls INTO TEMP pushdate
If you use the same query results more than once, using a temporary table
saves time. In addition, using an INTO TEMP clause often gives you clearer
and more understandable SELECT statements. However, the data in the
temporary table is static; data is not updated as changes are made to the
tables used to build the temporary table.
A logged, temporary table exists until one of the following situations occurs:
IDS If your database does not have logging, the table behaves in the same way as
a table that uses the WITH NO LOG option. ♦
The behavior of a temporary table that you create with the WITH NO LOG
option is the same as that of a scratch table.
Because scratch tables do not disappear when the database is closed, you can
use a scratch table to transfer data from one database to another while the
application remains connected.
A scratch table is identical to a temporary table that is created with the WITH
NO LOG option.
For more information about scratch tables, see “CREATE Temporary TABLE”
on page 2-286.
When you use the INTO EXTERNAL clause to unload data, you create a
default external table description. This clause is especially useful for
unloading Informix-internal data files because you can use the external table
description when you subsequently reload the files.
To obtain the same effect for text tables, issue a CREATE EXTERNAL...SAMEAS
statement. Then issue an INSERT INTO...SELECT statement.
Table Options
The following table describes the keywords that apply to unloading data. If
you want to specify additional table options in the external-table description
for the purpose of reloading the table later, see “Table Options” on
page 2-139. In the SELECT...INTO EXTERNAL statement, you can specify all
table options that are discussed in the CREATE EXTERNAL TABLE statement
except the fixed-format option.
You can use the INTO EXTERNAL clause when the format type of the created
data file is either DELIMITED text or text in Informix internal data format. You
cannot use it for a fixed-format unload.
Keyword Purpose
UNION Operator
Place the UNION operator between two SELECT statements to combine the
queries into a single query. You can string several SELECT statements
together using the UNION operator. Corresponding items do not need to
have the same name.
E/C ■ In ESQL/C, you cannot use an INTO clause in a query unless you are
sure that the compound query returns exactly one row, and you are
not using a cursor. In this case, the INTO clause must be in the first
SELECT statement. ♦
■ The number of items in the SELECT clause of each query must be the
same, and the corresponding items in each SELECT clause must have
compatible data types.
■ The columns in the SELECT clause of each query cannot be BYTE or
TEXT columns. This restriction does not apply to UNION ALL
operations.
■ If you use an ORDER BY clause, it must follow the last SELECT clause,
and you must refer to the item ordered by integer, not by identifier.
Ordering takes place after the set operation is complete.
IDS ■ You cannot use a UNION operator inside a subquery. ♦
To put the results of a UNION operator into a temporary table, use an INTO
TEMP clause in the final SELECT statement.
UNION ALL
If you want to remove duplicates, use the UNION operator without the
keyword ALL in the query. In the preceding example, if the combination
101 B were returned in both SELECT statements, a UNION operator would
cause the combination to be listed once. (If you want to remove duplicates
within each SELECT statement, use the DISTINCT keyword in the SELECT
clause, as described in “SELECT Clause” on page 2-636.)
Related Information
For task-oriented discussions of the SELECT statement, see the Informix Guide
to SQL: Tutorial.
For a discussion of the GLS aspects of the SELECT statement, see the Informix
Guide to GLS Functionality.
For information on how to access row and collections with ESQL/C host
variables, see the discussion of complex data types in the Informix ESQL/C
Programmer’s Manual.
+ SET AUTOFREE
IDS
Use the SET AUTOFREE statement to specify that the database server will free
E/C the memory allocated for a cursor automatically, as soon as the cursor is
closed.
Syntax
SET AUTOFREE
Usage
When the Autofree feature is enabled for a cursor, you do not need to
explicitly use a FREE statement to free the cursor memory in the database
server once the cursor is closed.
You can specify the ENABLED or DISABLED options for the SET AUTOFREE
statement. If you do not specify either option, the default is ENABLED. The
following example shows how to enable the Autofree feature for all subse-
quent cursors in the program by default:
EXEC SQL set autofree;
Restrictions
The SET AUTOFREE statement that enables the Autofree feature must appear
before the OPEN statement that opens a cursor. If a cursor is already open, the
SET AUTOFREE statement does not affect its behavior.
After a cursor is autofree enabled, you cannot open the cursor a second time.
The following example shows how to enable the Autofree feature for all
subsequent cursors:
EXEC SQL set autofree enabled;
This option allows you to override a global setting for all cursors. For
example, if you issue a SET AUTOFREE ENABLED statement for all cursors in
a program, you can issue a subsequent SET AUTOFREE DISABLED FOR
statement for a particular cursor.
In the following example, the first statement enables the Autofree feature for
all cursors, while the second statement disables the Autofree feature for the
cursor named x1:
EXEC SQL set autofree enabled;
EXEC SQL set autofree disabled for x1;
The term associated statement has a special meaning in the context of the
Autofree feature. A cursor is associated with a prepared statement if it is the
first cursor that you declare with the prepared statement, or if it is the first
cursor that you declare with the statement after the statement is detached.
The term detached statement has a special meaning in the context of the
Autofree feature. A prepared statement is detached if you do not declare a
cursor with the statement, or if the cursor with which the statement is
associated was freed.
If the Autofree feature is enabled for a cursor that has an associated prepared
statement, the database server frees memory allocated to the prepared
statement as well as the memory allocated for the cursor. Suppose that you
enable the Autofree feature for the following cursor:
/*Cursor associated with a prepared statement */
EXEC SQL prepare sel_stmt 'select * from customer';
EXEC SQL declare sel_curs2 cursor for sel_stmt;
Related Information
Related statements: CLOSE, DECLARE, FETCH, FREE, OPEN, and PREPARE
For more information on the Autofree feature, see the Informix ESQL/C
Programmer’s Manual.
E/C
SET CONNECTION
Use the SET CONNECTION statement to reestablish a connection between an
application and a database environment and make the connection current.
You can also use the SET CONNECTION statement with the DORMANT option
to put the current connection in a dormant state.
Syntax
Database
+ Environment
p. 2-108
DEFAULT
+ CURRENT DORMANT
Usage
You can use the SET CONNECTION statement to change the state of a
connection in the following ways:
You cannot use the SET CONNECTION statement in the statement text of a
prepared statement.
DEFAULT Option
Use the DEFAULT option to identify the default connection for a SET
CONNECTION statement. The default connection is one of the following
connections:
You can use SET CONNECTION without a DORMANT option to reestablish the
default connection or with the DORMANT option to make the default
connection dormant. For more information, see “DEFAULT Option” on
page 2-105 and “The Implicit Connection with DATABASE Statements” on
page 2-106.
CURRENT Keyword
Use the CURRENT keyword with the DORMANT option of the SET
CONNECTION statement as a shorthand form of identifying the current
connection. The CURRENT keyword replaces the current connection name. If
the current connection is con1, the following two statements are equivalent:
SET CONNECTION 'con1' DORMANT;
Related Information
Related statements: CONNECT, DISCONNECT, and DATABASE
Syntax
Table-Mode
SET Format
p. 2-701
List-Mode
Format
p. 2-702
Usage
When you change the mode of constraints, indexes, or triggers, the change is
persistent. The setting remains in effect until you change the mode of the
database object again.
The sysobjstate system catalog table lists all of the database objects in the
database and the current mode of each database object. For information on
the sysobjstate system catalog table, see the Informix Guide to SQL: Reference.
Table-Mode Format
Use the table-mode format to change the mode of all database objects of a
given type that have been defined on a particular table.
,
Modes for
CONSTRAINTS FOR table Constraints and
Unique Indexes
INDEXES p. 2-703
For example, to disable all constraints that are defined on the cust_subset
table, enter the following statement:
SET CONSTRAINTS FOR cust_subset DISABLED
When you use the table-mode format, you can change the modes of more
than one database object type with a single SET Database Object Mode
statement. For example, to enable all constraints, indexes, and triggers that
are defined on the cust_subset table, enter the following statement:
SET CONSTRAINTS, INDEXES, TRIGGERS FOR cust_subset
ENABLED
List-Mode Format
Use the list-mode format to change the mode for a particular constraint,
index, or trigger.
,
Modes for
CONSTRAINTS constraint Constraints and
Unique Indexes
p. 2-703
,
Modes for
INDEXES index Constraints and
Unique Indexes
p. 2-703
For example, to change the mode of the unique index unq_ssn on the
cust_subset table to filtering, enter the following statement:
SET INDEXES unq_ssn FILTERING
You can also use the list-mode format to change the mode for a list of
constraints, indexes, or triggers that are defined on the same table. Assume
that four triggers are defined on the cust_subset table: insert_trig,
update_trig, delete_trig, and execute_trig. Also assume that all four triggers
are enabled. To disable all triggers except execute_trig, enter the following
statement:
SET TRIGGERS insert_trig, update_trig, delete_trig DISABLED
DISABLED
ENABLED
FILTERING
WITHOUT ERROR
WITH ERROR
If you do not specify the mode for a constraint in a CREATE TABLE, ALTER
TABLE, or SET Database Object Mode statement, the constraint is enabled by
default.
If you do not specify the mode for an index in the CREATE INDEX or SET
Database Object Mode statement, the index is enabled by default.
Enabled Mode
Constraints, indexes, and triggers are enabled by default. The CREATE TABLE,
ALTER TABLE, CREATE INDEX, and CREATE TRIGGER statements create
database objects in the enabled mode unless you specify another mode in the
statement.
Disabled Mode
When a database object is disabled, the database server does not take it into
consideration during the execution of an INSERT, DELETE, OR UPDATE
statement. A disabled constraint is not enforced, a disabled index is not
updated, and a disabled trigger is not executed when the trigger event takes
place. When you disable constraints and unique indexes, any data manipu-
lation statement that violates the restriction of the constraint or unique index
succeeds, (that is the target row is changed) and the database server does not
return an error message.
You can use the disabled mode to add a new constraint or new unique index
to an existing table, even if some rows in the table do not satisfy the new
integrity specification. For information on adding a new constraint, see
“Adding a Constraint When Existing Rows Violate the Constraint”in the
ALTER TABLE statement. For information on adding a new unique index, see
“Adding a Unique Index When Duplicate Values Exist in the Column” in the
CREATE INDEX statement.
Filtering Mode
When a constraint or unique index is in filtering mode, the INSERT, DELETE,
OR UPDATE statement succeeds, but the database server enforces the
constraint or the unique-index requirement by writing any failed rows to the
violations table associated with the target table. Diagnostic information
about the constraint violation or unique-index violation is written to the
diagnostics table associated with the target table.
In all of these cases, the database server sends diagnostic information about
each constraint violation or unique-index violation to the diagnostics table
associated with the target table.
For detailed information on the structure of the records that the database
server writes to the violations and diagnostics tables, see “Structure of the
Violations Table” on page 2-785 and “Structure of the Diagnostics Table” on
page 2-793.
DISABLED
ENABLED
If you do not specify the mode for a trigger in the CREATE TRIGGER or SET
Database Object Mode statement, the trigger is enabled by default.
If you do not specify the mode for an index in the CREATE INDEX or SET
Database Object Mode statement, the index is enabled by default.
Related Information
Related statements: ALTER TABLE, CREATE TABLE, CREATE INDEX, CREATE
TRIGGER, START VIOLATIONS TABLE and STOP VIOLATIONS TABLE
For a discussion of object modes and violation detection and examples that
show how database object modes work when users execute data manipu-
lation statements on target tables or add new constraints and indexes to
target tables, see the Informix Guide to SQL: Tutorial.
For information on the system catalog tables associated with the SET
Database Object Mode statement, see the sysobjstate and sysviolations
tables in the Informix Guide to SQL: Reference.
+
SET DATASKIP
Use the SET DATASKIP statement to instruct the database server to skip a
dbspace that is unavailable during the course of processing a transaction.
Syntax
SET DATASKIP ON
,
dbspace
OFF
DEFAULT
Usage
The SET DATASKIP statement allows you to control whether the database
server skips a dbspace that is unavailable (for example, due to a media
E/C failure) in the course of processing a transaction.
IDS This statement applies only to tables that are fragmented across dbspaces. It
does not apply to blobspaces or sbspaces. ♦
When you SET DATASKIP ON without specifying a dbspace, you are telling
the database server to skip any dbspaces in the fragmentation list that are
unavailable. You can use the onstat -d or -D utility to determine if a dbspace
is down.
When you SET DATASKIP ON dbspace, you are telling the database server to
skip the specified dbspace if it is unavailable.
Use the SET DATASKIP OFF statement to turn off the dataskip feature.
When the setting is DEFAULT, the database server uses the setting for the
dataskip feature from the ONCONFIG file. The setting of the dataskip feature
can be changed at runtime.
The database server cannot skip a dbspace under certain conditions. The
following list outlines those conditions:
■ Indexing
When you perform updates that affect the index, such as when you
insert or delete records, or when you update an indexed field, the
index must be available.
When you try to create an index, the dbspace you want to use must
be available.
■ Serial keys
The first fragment is used to store the current serial-key value inter-
nally. This is not visible to you except when the first fragment
becomes unavailable and a new serial key value is required, which
happens during insert statements.
Related Information
For additional information about the dataskip feature, see your
Administrator’s Guide.
+
SET DEBUG FILE TO
Use the SET DEBUG FILE TO statement to name the file that is to hold the run-
time trace output of an SPL routine.
Syntax
expression
Usage
This statement indicates that the output of the TRACE statement in the SPL
routine goes to the file that filename indicates. Each time the TRACE statement
is executed, the trace data is added to this output file.
If you specify an existing file, the current contents of the file are purged when
you issue the SET DEBUG TO FILE statement. The first execution of a TRACE
command sends trace output to the beginning of the file.
However, if you include the WITH APPEND option, the current contents of the
file are preserved when you issue the SET DEBUG TO FILE statement. The first
execution of a TRACE command adds trace output to the end of the file.
If you specify a new file in the SET DEBUG TO FILE statement, it makes no
difference whether you include the WITH APPEND option. The first execution
of a TRACE command sends trace output to the beginning of the new file
whether you include or omit the WITH APPEND option.
Related Information
Related statement: TRACE
For a task-oriented discussion of SPL routines, see the Informix Guide to SQL:
Tutorial.
+ SET DEFERRED_PREPARE
IDS
Use the SET DEFERRED_PREPARE statement to defer sending a PREPARE
E/C statement to the database server until the OPEN or EXECUTE statement is
sent.
Syntax
SET DEFERRED_PREPARE
ENABLED
DISABLED
Usage
The SET DEFERRED_PREPARE statement causes the application program to
delay sending the PREPARE statement to the database server until the OPEN
or EXECUTE statement is executed. In effect, the PREPARE statement is
bundled with the other statement so that one round trip of messages instead
of two is sent between the client and the server.
ENABLED Option
Use the ENABLED option to enable the Deferred-Prepare feature within the
application. The following example shows how to use the ENABLED option:
EXEC SQL set deferred_prepare enabled;
DISABLED Option
Use the DISABLED option to disable the Deferred-Prepare feature within the
application. The following example shows how to use the DISABLED option:
EXEC SQL set deferred_prepare disabled;
When you disable the Deferred-Prepare feature, the application sends each
PREPARE statement to the database server when the PREPARE statement is
executed.
a = 2;
EXEC SQL EXECUTE ins_stmt using :a;
if (SQLCODE)
printf("EXECUTE : SQLCODE is %d\n", SQLCODE);
Related Information
Related statements: DECLARE, DESCRIBE, EXECUTE, OPEN, and PREPARE
+ SET DESCRIPTOR
E/C
Use the SET DESCRIPTOR statement to assign values to a system-descriptor
area.
Syntax
descriptor_var total_items_var
,
Usage
The SET DESCRIPTOR statement can be used after you have described SELECT,
EXECUTE FUNCTION (OR EXECUTE PROCEDURE), and INSERT statements
with the DESCRIBE...USING SQL DESCRIPTOR statement. The SET
DESCRIPTOR statement can assign values to a system-descriptor area in the
following instances:
If you allocate a system-descriptor area with more items than you are using,
you need to set the COUNT field to the number of items that you are actually
using. The following example shows the sequence of statements in ESQL/C
that can be used in a program:
EXEC SQL BEGIN DECLARE SECTION;
int count;
EXEC SQL END DECLARE SECTION;
count = 2;
EXEC SQL set descriptor 'desc_100' count = :count;
Item Descriptor
Use the Item Descriptor portion of the SET DESCRIPTOR statement to set
value for a particular field in a system-descriptor area.
TYPE = literal_int
LENGTH literal_int_var
PRECISION
SCALE
NULLABLE
INDICATOR
ITYPE
ILENGTH
Literal Number
DATA = p. 4-237
IDATA Literal DATETIME
p. 4-231
Literal INTERVAL
p. 4-234
NAME
IDS Quoted String
p. 4-260
EXTYPENAME
EXTYPEOWNERNAME input_var
EXTYPEID = literal_int
EXTYPELENGTH literal_int_var
EXTYPEOWNERLENGTH
SOURCEID
SOURCETYPE
IDS The following table includes additional integer constants that represent data
types available with Dynamic Server.
These TYPE constants are the same values that appear in the coltype column
in the syscolumns system catalog table.
For code that is easier to maintain, use the predefined constants for these SQL
data types instead of their actual integer values. These constants are defined
in the sqltypes.h header file. However, you cannot use the actual constant
name in the SET DESCRIPTOR statement. Instead, assign the constant to an
integer host variable and specify the host variable in the SET DESCRIPTOR
statement file.
The following example shows how you can set the TYPE field in ESQL/C:
main()
{
EXEC SQL BEGIN DECLARE SECTION;
int itemno, type;
EXEC SQL END DECLARE SECTION;
...
EXEC SQL allocate descriptor 'desc1' with max 5;
...
type = SQLINT; itemno = 3;
EXEC SQL set descriptor 'desc1' value :itemno type = :type;
}
This information is identical for ITYPE. Use ITYPE when you create a
dynamic program that does not comply with the X/Open standard.
For code that is easier to maintain, use the predefined constants for these
X/Open SQL data types instead of their actual integer value. These constants
are defined in the sqlxtype.h header file.
If you set DATA to a host variable of DATETIME or INTERVAL, you do not need
to set LENGTH explicitly to the encoded qualifier integer.
When any value other than DATA is set, the value of DATA is undefined. You
cannot set the DATA or IDATA field for an item without setting TYPE for that
item. If you set the TYPE field for an item to a character type, you must also
set the LENGTH field. If you do not set the LENGTH field for a character item,
you receive an error.
This information is identical for ILENGTH. Use ILENGTH when you create a
dynamic program that does not comply with the X/Open standard.
If you set the INDICATOR field to 0 to indicate that the data is not null, you
must set the DATA field.
■ The EXTYPEID field stores the extended identifier for the opaque
type.
This integer value must correspond to a value in the extended_id
column of the sysxtdtypes system catalog table.
■ The EXTYPENAME field stores the name of the opaque type.
This character value must correspond to a value in the name column
of the row with the matching extended_id value in the sysxtdtypes
system catalog table.
For more information on the sysxtdtypes system catalog table, see the
Informix Guide to SQL: Reference.
■ The SOURCEID field stores the extended identifier for the source
data type.
Set this field if the source type of the distinct type is an opaque data
type. This integer value must correspond to a value in the source
column for the row of the sysxtdtypes system catalog table whose
extended_id value matches that of the distinct type you are setting.
■ The SOURCETYPE field stores the data-type constant for the source
data type.
This value is the data-type constant for the built-in data type that is
the source type for the distinct type. The codes for the SOURCETYPE
field are the same as those for the TYPE field (page 2-724). This
integer value must correspond to the value in the type column for
the row of the sysxtdtypes system catalog table whose extended_id
value matches that of the distinct type you are setting.
For more information on the sysxtdtypes system catalog table, see the
Informix Guide to SQL: Reference.
Related Information
Related statements: ALLOCATE DESCRIPTOR, DEALLOCATE DESCRIPTOR,
DECLARE, DESCRIBE, EXECUTE, FETCH, GET DESCRIPTOR, OPEN, PREPARE,
and PUT
SET EXPLAIN
Use the SET EXPLAIN statement to display the query plan the optimizer
chooses, an estimate of the number of rows returned, and a relative cost of the
query.
Syntax
SET EXPLAIN ON
OFF
XPS
expr
Usage
The SET EXPLAIN statement provides various measurements of the work
involved in performing a query.
Option Purpose
The filename may be any valid combination of optional path and filename. If
no path component is specified, the file is placed in your current directory.
The permissions for the file are owned by the current user.
If you specify an existing file, the current contents of the file are purged when
you issue the SET EXPLAIN FILE TO statement. The first execution of a FILE TO
command sends output to the beginning of the file.
However, if you include the WITH APPEND option, the current contents of the
file are preserved when you issue the SET EXPLAIN FILE TO statement. The
execution of a WITH APPEND command appends output to the end of the file.
If you specify a new file in the SET EXPLAIN FILE TO statement, it makes no
difference whether you include the WITH APPEND option. The first execution
of the command sends output to the beginning of the new file.
If the output file does not exist when you issue the SET EXPLAIN ON
statement, the database server creates the output file. If the output file
already exists when you issue the SET EXPLAIN ON statement, subsequent
output is appended to the file.
If the client application and the database server are on the same computer, the
sqexplain.out file is stored in your current directory. If you are using a
version 5.x or earlier client application and the sqexplain.out file does not
appear in the current directory, check your home directory for the file.When
the current database is on another computer, the sqexplain.out file is stored
in your home directory on the remote host. ♦
WIN NT On Windows NT, when you issue a SET EXPLAIN ON statement, the plan that
the optimizer chooses for each subsequent query is written to the file
%INFORMIXDIR%\sqexpln\username.out where username is the user
login. ♦
The following table contains terms that can appear in the output file and their
significance.
Term Significance
Query Displays the executed query. Indicates whether SET OPTIMIZATION was set to
high.
If you SET OPTIMIZATION to LOW, the output of SET EXPLAIN displays the
following uppercase string as the first line:
QUERY:{LOW}
If you SET OPTIMIZATION to HIGH, the output of SET EXPLAIN displays the
following uppercase string as the first line:
QUERY:
Directives followed Lists the directives set for the executed query.
If the syntax for a directive is incorrect, the query is processed without the
directive. In that case, the output will show DIRECTIVES NOT FOLLOWED in
addition to DIRECTIVES FOLLOWED.
For more information on the directives specified after this term, see the
“Optimizer Directives” on page 4-244 or “SET OPTIMIZATION” on page 2-747.
Numbered List The order in which tables are accessed, followed by the access method used (index
path or sequential scan).
When a query involves table inheritance, all of the tables are listed under the
supertable in the order they were accessed.
(1 of 2)
Term Significance
Index Keys The columns used as filters or indexes; the column name used for the index path
or filter is indicated.
The notation (Key Only) indicates that all of the desired columns are part of the
index key, so a key-only read of the index could be substituted for a read of the
actual table.
The Lower Index Filter shows the key value where the index read begins. If the filter
condition contains more than one value, an Upper Index Filter would be shown for
the key value where the index read stops.
Join Method When the query involves a join between two tables, the join method the optimizer
used (Nested Loop or Dymanic Hash) is shown at the bottom of the output for that
query.
When the query involves a dynamic join of two tables, if the output contains the
words Build Outer, the hash table is built on the first table listed (called the build
table).
If the words Build Outer do not appear, the hash table is built on the second table
listed.
(2 of 2)
Related Information
Related statements: SET OPTIMIZATION and UPDATE STATISTICS
For discussions of SET EXPLAIN and of analyzing the output of the optimizer,
see your Performance Guide.
+
SET ISOLATION
Use the SET ISOLATION statement to define the degree of concurrency among
processes that attempt to access the same rows simultaneously.
Syntax
CURSOR STABILITY
REPEATABLE READ
Usage
The database isolation level affects read concurrency when rows are retrieved
from the database. The database server uses shared locks to support different
levels of isolation among processes attempting to access data.
The update or delete process always acquires an exclusive lock on the row
that is being modified. The level of isolation does not interfere with rows that
you are updating or deleting. If another process attempts to update or delete
rows that you are reading with an isolation level of Repeatable Read, that
process is denied access to those rows.
E/C In ESQL/C, cursors that are currently open when you execute the SET
ISOLATION statement might or might not use the new isolation level when
rows are later retrieved. The isolation level in effect could be any level that
was set from the time the cursor was opened until the time the application
actually fetches a row. The database server might have read rows into
internal buffers and internal temporary tables using the isolation level that
was in effect at that time. To ensure consistency and reproducible results,
close open cursors before you execute the SET ISOLATION statement. ♦
This isolation level is most appropriate for static tables that are used for
queries, that is, tables where data is not being modified, since it provides no
isolation. With Dirty Read, the program might return a phantom row, which
is an uncommitted row that was inserted or modified within a transaction
that has subsequently rolled back. No other isolation level allows access to a
phantom row.
If you set the isolation level to Cursor Stability, but you are not using a trans-
action, the Cursor Stability isolation level acts like the Committed Read
isolation level.
Repeatable Read isolation places the largest number of locks and holds them
the longest. Therefore, it is the level that reduces concurrency the most.
Committed Read Default level of isolation in a database with logging that is not
ANSI compliant
The default level remains in effect until you issue a SET ISOLATION statement.
After a SET ISOLATION statement executes, the new isolation level remains in
effect until one of the following events occurs:
In a database with the isolation level set to Dirty Read, Committed Read, or
Cursor Stability, the database server places an update lock on a fetched row
of a SELECT... FOR UPDATE statement. When you turn on the RETAIN UPDATE
LOCKS option, the database server retains the update lock until the end of the
transaction rather than release it at the next subsequent FETCH or when the
cursor is closed. This option prevents other users from placing an exclusive
lock on the updated row before the current user reaches the end of the
transaction.
You can use this option to achieve the same locking effects but avoid the
overhead of dummy updates or the repeatable read isolation level.
You can turn this option on or off at any time during the current session.
You can turn the option off by resetting the isolation level without using the
RETAIN UPDATE LOCKS keywords.
Switching off the feature does not directly release any update lock. When you
turn this option off, the database server reverts to normal behavior for the
three isolation levels. That is, a FETCH statement releases the update lock
placed on a row by the immediately preceding FETCH statement, and a
closed cursor releases the update lock on the current row.
Update locks placed by earlier FETCH statements are not released unless
multiple update cursors are present within the same transaction. In this case,
a subsequent FETCH could also release older update locks of other cursors.
You can issue a SET ISOLATION statement from a client computer only after a
database is opened.
The data obtained during retrieval of a BYTE or TEXT column can vary,
depending on the database isolation level. Under Dirty Read or Committed
Read levels of isolation, a process is permitted to read a BYTE or TEXT column
that is either deleted (if the delete is not yet committed) or in the process of
being deleted. Under these isolation levels, an application can read a deleted
data when certain conditions exist. For information about these conditions,
see the Administrator’s Guide.
DB When you use DB-Access, as you use higher levels of isolation, lock conflicts
occur more frequently. For example, if you use Cursor Stability, more lock
conflicts occur than if you use Committed Read. ♦
E/C In ESQL/C, if you use a scroll cursor in a transaction, you can force consis-
tency between your temporary table and the database table either by setting
the isolation level to Repeatable Read or by locking the entire table during the
transaction.
If you use a scroll cursor with hold in a transaction, you cannot force consis-
tency between your temporary table and the database table. A table-level
lock or locks that are set by Repeatable Read are released when the
transaction is completed, but the scroll cursor with hold remains open
beyond the end of the transaction. You can modify released rows as soon as
the transaction ends, but the retrieved data in the temporary table might be
inconsistent with the actual data. ♦
Related Information
Related statements: CREATE DATABASE, SET LOCK MODE, and SET
TRANSACTION
For a discussion of setting the isolation level, see the Informix Guide to SQL:
Tutorial.
+
SET LOCK MODE
Use the SET LOCK MODE statement to define how the database server
handles a process that tries to access a locked row or table.
Syntax
seconds
NOT WAIT
Usage
You can direct the response of the database server in the following ways
when a process tries to access a locked row or table.
NOT WAIT Database server ends the operation immediately and returns
an error code. This condition is the default.
WAIT Database server suspends the process until the lock releases.
WAIT seconds Database server suspends the process until the lock releases or
until the end of a waiting period, which is specified in
seconds. If the lock remains after the waiting period, the
database server ends the operation and returns an error code.
In the following example, the user specifies that the process should be
suspended until the lock is released:
SET LOCK MODE TO WAIT
In the following example, the user specifies that if the process requests a
locked row the operation should end immediately and an error code should
be returned:
SET LOCK MODE TO NOT WAIT
In the following example, the user places an upper limit of 17 seconds on the
length of any wait:
SET LOCK MODE TO WAIT 17
WAIT Clause
The WAIT clause causes the database server to suspend the process until the
lock is released or until a specified number of seconds have passed without
the lock being released.
The database server protects against the possibility of a deadlock when you
request the WAIT option. Before the database server suspends a process, it
checks whether suspending the process could create a deadlock. If the
database server discovers that a deadlock could occur, it ends the operation
(overruling your instruction to wait) and returns an error code. In the case of
either a suspected or actual deadlock, the database server returns an error.
Cautiously use the unlimited waiting period that was created when you
specify the WAIT option without seconds. If you do not specify an upper limit,
and the process that placed the lock somehow fails to release it, suspended
processes could wait indefinitely. Because a true deadlock situation does not
exist, the database server does not take corrective action.
Related Information
Related statements: LOCK TABLE, SET ISOLATION, SET TRANSACTION and
UNLOCK TABLE
For a discussion on how to set the lock mode, see the Informix Guide to SQL:
Tutorial.
+
SET LOG
Use the SET LOG statement to change your database logging mode from
buffered transaction logging to unbuffered transaction logging or vice versa.
Syntax
SET LOG
BUFFERED
Usage
You activate transaction logging when you create a database or add logging
to an existing database. These transaction logs can be buffered or unbuffered.
The SET LOG statement in the following example changes the transaction
logging mode to buffered logging:
SET BUFFERED LOG
The SET LOG statement in the following example changes the transaction
logging mode to unbuffered logging:
SET LOG
The SET LOG statement redefines the mode for the current session only. The
default mode, which the database administrator sets with the ondblog utility,
remains unchanged.
The buffering option does not affect retrievals from external tables. For
distributed queries, a database with logging can retrieve only from databases
with logging, but it makes no difference whether the databases use buffered
or unbuffered logging.
Related Information
Related statement: CREATE DATABASE
+
SET OPTIMIZATION
Use the SET OPTIMIZATION statement to specify the time the optimizer
spends to determine the query plan or to specify the optimization goals of the
query.
Syntax
LOW
IDS
FIRST_ROWS
ALL_ROWS
Usage
You can execute a SET OPTIMIZATION statement at any time. The
optimization level carries across databases on the current database server.
When you issue a SET OPTIMIZATION statement, the option that you specify
is persistent. That is, the new optimization level remains in effect until you
issue another SET OPTIMIZATION statement or until the program ends.
The default database-server optimization level for the time the optimizer
spends determining the query plan is HIGH.
IDS The default database-server optimization level for the optimization goal of
the query is ALL_ROWS.
Although you can set only one option at a time, you can issue two SET
OPTIMIZATION statements: one that specifies the time the optimizer spends
to determine the query plan and one that specifies the optimization goal of
the query. ♦
■ HIGH
This option directs the optimizer to use a sophisticated, cost-based
algorithm that examines all reasonable query-plan choices and
selects the best overall alternative.
For large joins, this algorithm can incur more overhead than you
desire. In extreme cases, you can run out of memory.
■ LOW
This option directs the optimizer to use a less sophisticated, but
faster, optimization algorithm. This algorithm eliminates unlikely
join strategies during the early stages of optimization and reduces
the time and resources spent during optimization.
When you specify a low level of optimization, the database server
might not select the optimal strategy because the strategy was elimi-
nated from consideration during the early stages of the algorithm.
■ FIRST_ROWS
This option directs the optimizer to choose the query plan that
returns the first result record as soon as possible.
■ ALL_ROWS
This option directs the optimizer to choose the query plan which
returns all the records as quickly as possible.
You can also specify the optimization goal of a specific query with the optimi-
zation-goal directive. For more information on how to use a directive to
specify the optimization goal of a query, see “Optimizer Directives” on
page 4-244.
Examples
The following example shows optimization across a network. The central
database (on the midstate database server) is to have LOW optimization; the
western database (on the rockies database server) is to have HIGH
optimization.
CONNECT TO 'central@midstate';
SET OPTIMIZATION LOW;
SELECT * FROM customer;
CLOSE DATABASE;
CONNECT TO 'western@rockies';
SET OPTIMIZATION HIGH;
SELECT * FROM customer;
CLOSE DATABASE;
CONNECT TO 'wyoming@rockies';
SELECT * FROM customer;
IDS The following example directs the optimizer to use the most time to
determine a query plan and to then return the first rows of the result as soon
as possible.
SET OPTIMIZATION LOW;
SET OPTIMIZATION FIRST_ROWS;
SELECT lname, fname, bonus
FROM sales_emp, sales
WHERE sales.empid = sales_emp.empid AND bonus > 5,000
ORDER BY bonus DESC
Related Information
Related statements: SET EXPLAIN and UPDATE STATISTICS
IDS For information on other methods by which you can alter the query plan of
the optimizer, see “Optimizer Directives” on page 4-244. ♦
+
SET PDQPRIORITY
The SET PDQPRIORITY statement allows an application to set the query
priority level dynamically within an application.
Syntax
LOW
IDS OFF
HIGH
resources
Usage
The priority set with the SET PDQPRIORITY statement overrides the
environment variable PDQPRIORITY. However, no matter what priority
value you set with the SET PDQPRIORITY statement, the ONCONFIG configu-
ration parameter MAX_PDQPRIORITY determines the actual priority value
that the database server uses for your queries.
For example, assume that the DBA sets the MAX_PDQPRIORITY parameter to
50. Then a user enters the following SET PDQPRIORITY statement to set the
query priority level to 80 percent of resources:
SET PDQPRIORITY 80
When it processes the query, the database server uses the value of the
MAX_PDQPRIORITY parameter to factor the query priority level set by the
user. The database server silently processes the query with a priority level of
40. This priority level represents 50 percent of the 80 percent of resources that
the user specifies.
IDS Set PDQ priority to a value that is less than the quotient of 100 divided by the
maximum number of prepared statements. For example, if two prepared
statements are active, you should set PDQ priority to less than 50. ♦
XPS In Extended Parallel Server, set PDQ priority to a value greater than 0 when
you need more memory for database operations such as sorts, groups, and
index builds. For guidelines on which values to use, see your Performance
Guide. ♦
Keyword Purpose
Resources include the amount of memory and the number of processors. The
higher the number you specify in this parameter, the more resources the
database server uses. Although the use of more resources by a database
server usually indicates better performance for a given query, using too many
resources can cause contention among the resources and remove resources
from other queries, which results in degraded performance.
With the resources option, the following values are numeric equivalents of the
keywords that indicate query priority level.
-1 DEFAULT
IDS The following statements are equivalent. The first statement uses the
keyword LOW to establish a low query-priority level. The second statement
uses a value of 1 in the resources parameter to establish a low query-priority
level.
SET PDQPRIORITY LOW;
SET PDQPRIORITY 1;
Related Information
For information about configuration parameters and about the Resource
Grant Manager, see your Administrator’s Guide and your Performance Guide.
Syntax
WITH APPEND
Usage
The WITH APPEND option allows you to append new log information to the
existing log file.
Each time a session closes, the log file for that session also closes. If you issue
more than one SET PLOAD FILE statement within a session, each new
statement closes a previously opened log file and opens a new log file.
If you invoke a SET PLOAD FILE statement with a simple filename on a local
database, the output file is located in your current directory. If your current
database is on a remote database server, then the output file is located in your
home directory on the remote database server, on the coserver where the
initial connection was made. If you provide a full pathname for the file, it is
placed in the directory and file specified on the remote server.
Related Information
Related Statements: CREATE EXTERNAL TABLE
+
SET Residency
Use the SET Residency statement to specify that one or more fragments of a
table or index be resident in shared memory as long as possible.
Syntax
Usage
The SET Residency statement allows you to specify the tables, indexes, and
data fragments that you want to remain in the buffer as long as possible.
When a free buffer is requested, pages that are declared MEMORY_RESIDENT
are considered last for page replacement.
The default resident state for database objects is nonresident. The resident
state is persistent for the time the database server is up. That is, each time the
database server is started you must specify the database objects that you
want to remain in shared memory.
■ You use the SET Residency statement to set the database object to
NON_RESIDENT.
■ The database object is dropped.
■ The database server is taken off-line.
You must be user informix to set or change the residency status of a database
object.
Examples
The following example shows how to set the residency status of an entire
table.
SET TABLE tab1 MEMORY_RESIDENT
For fragmented tables or indexes, you can specify residency for individual
fragments as the following example shows.
SET INDEX index1 (dbspace1, dbspace2) MEMORY_RESIDENT;
SET TABLE tab1 (dbspace1) NON_RESIDENT
This example specifies that the tab1 fragment in dbspace1 is not to remain in
shared memory while the index1 fragments in dbspace1 and dbspace2 are to
remain in shared memory as long as possible.
Related Information
Related statements: SYNTAX
For information on how to monitor the residency status of tables, indexes and
fragments, refer to your Administrator’s Guide.
+ SET ROLE
IDS
Use the SET ROLE statement to enable the privileges of a role.
Syntax
NONE
Usage
Any user who is granted a role can enable the role using the SET ROLE
statement. You can only enable one role at a time. If you execute the SET ROLE
statement after a role is already set, the new role replaces the old role.
All users are, by default, assigned the role NULL or NONE (NULL and NONE
are synonymous). The roles NULL and NONE have no privileges. When you
set the role to NULL or NONE, you disable the current role.
When you set a role, you gain the privileges of the role, in addition to the
privileges of PUBLIC and your own privileges. If a role is granted to another
role, you gain the privileges of both roles, in addition to those of PUBLIC and
your own privileges. After a SET ROLE statement executes successfully, the
role remains effective until the current database is closed or the user executes
another SET ROLE statement. Additionally, the user, not the role, retains
ownership of all the database objects, such as tables, that were created during
a session.
The scope of a role is within the current database only. You cannot use the
privileges you acquire from a role to access data in another database. For
example, if you have privileges from a role in the database named acctg, and
you execute a distributed query over the databases named acctg and
inventory, your query cannot access the data in the inventory database
unless your were granted privileges in the inventory database.
Your cannot execute the SET ROLE statement while in a transaction. If the SET
ROLE statement is executed while a transaction is active, an error occurs.
If the SET ROLE statement is executed as a part of a trigger or SPL routine, and
the owner of the trigger or SPL routine was granted the role with the WITH
GRANT OPTION, the role is enabled even if you are not granted the role.
The following example sets a role and then relinquishes the role after it
performs a SELECT operation:
EXEC SQL set role engineer;
EXEC SQL select fname, lname, project
into :efname, :elname, :eproject
from projects
where project_num > 100 and lname = 'Larkin';
printf ("%s is working on %s\n", efname, eproject);
EXEC SQL set role null;
Related Information
Related statements: CREATE ROLE, DROP ROLE, GRANT, and REVOKE
For a discussion of how to use roles, see the Informix Guide to SQL: Tutorial.
Syntax
Usage
The highest priority level is 100. That is, a query at level 100 is more
important than a query at level 1. In general, the Resource Grant Manager
(RGM) processes a query with a higher scheduling level before a query with
a lower scheduling level. The exact behavior of the RGM is influenced by the
setting of the DS_ADM_POLICY configuration parameter.
Related Information
Related statement: SET PDQPRIORITY
For information about the Resource Grant Manager, see your Administrator’s
Guide.
Syntax
Usage
The SET SESSION AUTHORIZATION statement allows a user with the DBA
privilege to bypass the privileges that protect database objects. You can use
this statement to gain access to a table and adopt the identity of a table owner
to grant access privileges. You must obtain the DBA privilege before you start
a session in which you use this statement. Otherwise, this statement returns
an error.
When you use this statement, the user name to which the authorization is set
must have the Connect privilege on the current database. Additionally, the
DBA cannot set the authorization to PUBLIC or to any defined role in the
current database.
Setting a session to another user causes a change in a user name in the current
active database server. In other words, these users are, as far as this database
server process is concerned, completely dispossessed of any privileges that
they might have while accessing the database server through some adminis-
trative utility. Additionally, the new session user is not able to initiate an
administrative operation (execute a utility, for example) by virtue of the
acquired identity.
Related Information
Related statements: CONNECT, DATABASE, GRANT, and SET ROLE
Syntax
OFF
Usage
You can use the SET STATEMENT CACHE statement to turn caching in the SQL
statement cache ON or OFF for the current session. The SQL statement cache
is a mechanism that stores identical statements that are repeatedly executed
in a buffer.
When the SQL statement cache is enabled, each statement that you execute
passes through the SQL statement cache to determine if a matching cache
entry is present. If so, the database server uses the cached entry to execute the
statement.
If the statement does not have a matching entry, the database server tests to
see if it qualifies for entry into the cache. For information on the conditions a
statement must meet to enter into the cache, see “Statement Qualification” on
page 766.
■ Case
■ Comments
■ Query text strings
■ White space
■ Optimization settings
❑ SET OPTIMIZATION statement options
❑ Optimizer directives
❑ Settings of the OPTCOMPIND environment variable or the
OPTCOMPIND ONCONFIG configuration parameter
Host variable names, however, are insignificant. For example, the following
select statements are considered identical:
SELECT * FROM tab1 WHERE x = :x AND y = :y;
In the previous example, although the host names are different, the state-
ments qualify because the case, query text strings, and white space match.
For example, if you have little cache cohesion, that is, when relatively few
matches but many new entries into the cache exist, the cache management
overhead is high. In this case, turn the SQL statement cache off.
In addition, if you know that you are executing many statements that do not
qualify for the SQL statement cache, you might want to disable it and avoid
the overhead of testing to see if each statement qualifies for entry into the
cache.
Statement Qualification
A statement that can be cached in the SQL statement cache (and consequently,
one that can match a statement that already appears in the SQL statement
cache), must meet the following conditions:
Related Information
For information on optimization settings, see “SET OPTIMIZATION” on
page 2-747 and “Optimizer Directives” on page 4-244.
For more information about the STMT_CACHE onconfig parameter and the
onmode utility, see your Administrator’s Reference.
+
SET TRANSACTION
Use the SET TRANSACTION statement to define isolation levels and to define
the access mode of a transaction (read-only or read-write).
Syntax
,
READ ONLY
REPEATABLE READ
SERIALIZABLE
READ UNCOMMITTED
Usage
You can use SET TRANSACTION only in databases with logging.
You can issue a SET TRANSACTION statement from a client computer only
after a database is opened.
The update or delete process always acquires an exclusive lock on the row
that is being modified. The level of isolation does not interfere with rows that
you are updating or deleting; however, the access mode does affect whether
you can update or delete rows. If another process attempts to update or
delete rows that you are reading with an isolation level of Serializable or
(ANSI) Repeatable Read, that process will be denied access to those rows.
SET ISOLATION
EXEC SQL BEGIN WORK;
EXEC SQL SET ISOLATION TO DIRTY READ;
EXEC SQL SELECT ... ;
EXEC SQL SET ISOLATION TO REPEATABLE READ;
EXEC SQL INSERT ... ;
EXEC SQL COMMIT WORK;
-- Executes without error
SET TRANSACTION
EXEC SQL BEGIN WORK;
EXEC SQL SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
EXEC SQL SELECT ... ;
EXEC SQL SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
-- Produces error 876: Cannot issue SET TRANSACTION
-- in an active transaction.
This isolation level is most appropriate for static tables that are used for
queries, that is, tables where data is not being modified, since it provides no
isolation. With Read Uncommitted, the program might return a phantom
row, which is an uncommitted row that was inserted or modified within a
transaction that has subsequently rolled back. No other isolation level allows
access to a phantom row.
Serializable isolation places the largest number of locks and holds them the
longest. Therefore, it is the level that reduces concurrency the most.
The default isolation level remains in effect until you issue a SET
TRANSACTION statement within a transaction. After a COMMIT WORK
statement completes the transaction or a ROLLBACK WORK statement cancels
the transaction, the isolation level is reset to the default.
Access Modes
Informix database servers support access modes. Access modes affect read
and write concurrency for rows within transactions. Use access modes to
control data modification.
You can specify that a transaction is read-only or read-write through the SET
TRANSACTION statement. By default, transactions are read-write. When you
specify that a transaction is read-only, certain limitations apply. Read-only
transactions cannot perform the following actions:
■ Insert, delete, or update table rows
■ Create, alter, or drop any database object such as schemas, tables,
temporary tables, indexes, or SPL routines
■ Grant or revoke privileges
■ Update statistics
■ Rename columns or tables
You can execute SPL routines in a read-only transaction as long as the SPL
routine does not try to perform any restricted statement.
The data that is obtained during retrieval of BYTE or TEXT data can vary,
depending on the database isolation levels. Under Read Uncommitted or
Read Committed isolation levels, a process is permitted to read a BYTE or
TEXT column that is either deleted (if the delete is not yet committed) or in
the process of being deleted. Under these isolation levels, an application can
read a deleted BYTE or TEXT column when certain conditions exist. For
information about these conditions, see the Administrator’s Guide.
E/C In ESQL/C, if you use a scroll cursor in a transaction, you can force consis-
tency between your temporary table and the database table either by setting
the isolation level to Serializable or by locking the entire table during the
transaction.
If you use a scroll cursor with hold in a transaction, you cannot force
consistency between your temporary table and the database table. A table-
level lock or locks set by Serializable are released when the transaction is
completed, but the scroll cursor with hold remains open beyond the end of
the transaction. You can modify released rows as soon as the transaction
ends, so the retrieved data in the temporary table might be inconsistent with
the actual data. ♦
Related Information
Related statements: CREATE DATABASE, SET ISOLATION, and SET LOCK
MODE
For a discussion of isolation levels and concurrency issues, see the Informix
Guide to SQL: Tutorial.
IDS To change the mode of constraints to on, off, or filtering, see “SET Database
Object Mode” on page 2-700. ♦
Syntax
,
ALL DEFERRED
Usage
When you set the transaction mode of a constraint, the effect of the SET Trans-
action Mode statement is limited to the transaction in which it is executed.
The setting that the SET Transaction Mode statement produces is effective
only during the transaction.
You use the IMMEDIATE keyword to set the transaction mode of constraints
to statement-level checking. You use the DEFERRED keyword to set the trans-
action mode to transaction-level checking.
You can set the transaction mode of constraints only in a database with
logging.
Statement-Level Checking
When you set the transaction mode to immediate, statement-level checking
is turned on, and all specified constraints are checked at the end of each
INSERT, UPDATE, or DELETE statement. If a constraint violation occurs, the
statement is not executed. Immediate is the default transaction mode of
constraints.
Transaction-Level Checking
When you set the transaction mode of constraints to deferred, statement-
level checking is turned off, and all specified constraints are not checked until
the transaction is committed. If a constraint violation occurs while the
transaction is being committed, the transaction is rolled back.
Tip: If you defer checking a primary-key constraint, checking the not-null constraint
for that column or set of columns is also deferred.
The following example specifies that a list of constraints is not checked until
the transaction is complete:
BEGIN WORK
SET CONSTRAINTS update_const, insert_const DEFERRED
.
.
.
COMMIT WORK
Related Information
Related Statements: ALTER TABLE and CREATE TABLE
+
START VIOLATIONS TABLE
Use the START VIOLATIONS TABLE statement to create a violations table and
a diagnostics table for a specified target table. The database server associates
the violations and diagnostics tables with the target table by recording the
relationship among the three tables in the sysviolations system catalog table.
XPS In Extended Parallel Server, the START VIOLATIONS TABLE statement creates
a violations table but not a diagnostics table. ♦
Syntax
Usage
The START VIOLATIONS TABLE statement creates the special violations table
that holds rows that fail to satisfy constraints and unique indexes during
insert, update, and delete operations on target tables. This statement also
creates the special diagnostics table that contains information about the
integrity violations caused by each row in the violations table.
XPS In Extended Parallel Server, the START VIOLATIONS TABLE statement creates
a violations table but not a diagnostics table. ♦
Similarly, if you use the SET Database Object Mode statement to set a disabled
constraint or disabled unique index to the enabled or filtering database object
mode, but you do not use the START VIOLATIONS TABLE statement to start
the violations and diagnostics tables for the table on which the database
objects are defined, any existing rows in the table that do not satisfy the
constraint or unique-index requirement are not filtered out to a violations
table. If, in these cases, you want the ability to identify existing rows that do
not satisfy the constraint or unique-index requirement, you must issue the
START VIOLATIONS TABLE statement to start the violations and diagnostics
tables before you issue the SET Database Object Mode statement to set the
database objects to the enabled or filtering database object mode.
XPS In Extended Parallel Server, the SET Database Object Mode statement is not
supported, and the concept of database object modes does not exist. Instead,
once you use the START VIOLATIONS TABLE statement to create a violations
table and associate it with a target table, the existence of this violations table
causes all violations of constraints and unique-index requirements by insert,
delete, and update operations to be recorded in the violations table.
In other words, once you issue a START VIOLATIONS TABLE statement, all
constraints and unique indexes in a database on Extended Parallel Server
behave like filtering-mode constraints and filtering-mode unique indexes in
a database on Dynamic Server. For an explanation of the behavior of filtering-
mode constraints and filtering-mode unique indexes, see “Filtering Mode”
on page 2-705. ♦
However, the result is that all three transactions do not receive error
messages about constraint and unique-index violations even though transac-
tions B and C do not expect this behavior. For example, if transaction B issues
an INSERT or UPDATE statement that violates a check constraint on table tab1,
the database server does not issue a constraint violation error to transaction
B. Instead, the database server filters the bad row to the violations table
without notifying transaction B that a data-integrity violation occurred.
IDS You can prevent this situation from arising in Dynamic Server by specifying
the WITH ERRORS option when you set database objects to the FILTERING
mode in a SET Database Object Mode, CREATE TABLE, ALTER TABLE, or
CREATE INDEX statement. When multiple transactions operate on a table and
the WITH ERRORS option is in effect, any transaction that violates a constraint
or unique-index requirement on a target table receives a data-integrity error
message. ♦
USING Clause
IDS You can use the USING clause to assign explicit names to the violations and
diagnostics tables.
If you omit the USING clause, the database server assigns names to the viola-
tions and diagnostics tables. The system-assigned name of the violations
table consists of the name of the target table followed by the string vio. The
system-assigned name of the diagnostics table consists of the name of the
target table followed by the string dia.
If you omit the USING clause, the maximum length of the target table is 124
characters.♦
XPS You can use the USING clause to assign an explicit name to the violations
table.
If you omit the USING clause, the database server assigns a name to the viola-
tions table. The system-assigned name of the violations table consists of the
name of the target table followed by the string vio.
If you omit the USING clause, the maximum length of the target table is 14
characters. ♦
If you do not include the MAX ROWS clause in the START VIOLATIONS TABLE
statement, no upper limit exists on the number of rows that can be inserted
into the diagnostics table when a single statement is executed on the target
table.
Same columns as the These columns of the Table definition of the target table is reproduced
target table, in the same violations table match the in the violations table so that rows that violate
order that they appear in data type of the constraints or unique-index requirements during
the target table corresponding columns insert, update, and delete operations can be
in the target table, except filtered to the violations table.
that SERIAL columns in Users can examine these bad rows in the
the target table are violations table, analyze the related rows that
converted to INTEGER contain diagnostics information in the diagnostics
data types in the table, and take corrective actions.
violations table.
I = Insert
D = Delete
informix_recowner CHAR(8) Identifies the user who issued the statement that
created this bad row.
Each row of the violations table has at least one corresponding row in the
diagnostics table. The row in the violations table contains a copy of the row
in the target table for which a data-integrity violation was detected. The row
in the diagnostics table contains information about the nature of the data-
integrity violation caused by the bad row in the violations table. The row in
the violations table has a unique serial identifier in the informix_tupleid
column. The row in the diagnostics table has the same serial identifier in its
informix_tupleid column.
A given row in the violations table can have more than one corresponding
row in the diagnostics table. The multiple rows in the diagnostics table all
have the same serial identifier in their informix_tupleid column so that they
are all linked to the same row in the violations table. Multiple rows can exist
in the diagnostics table for the same row in the violations table because a bad
row in the violations table can cause more than one data-integrity violation.
For example, a bad row can violate a unique-index requirement for one
column, a not-null constraint for another column, and a check constraint for
yet another column. In this case, the diagnostics table contains three rows for
the single bad row in the violations table. Each of these diagnostic rows
identifies a different data-integrity violation that the nonconforming row in
the violations table caused.
The following table explains the circumstances under which the database
server grants each privilege on the violations table. The first column lists each
privilege. The second column explains the conditions under which the
database server grants that privilege to a user.
Insert User has the Insert privilege on the violations table if the user has any
of the following privileges on the target table: the Insert privilege, the
Delete privilege, or the Update privilege on any column.
Delete User has the Delete privilege on the violations table if the user has any
of the following privileges on the target table: the Insert privilege, the
Delete privilege, or the Update privilege on any column.
User has the Select privilege on any other column of the violations
table if the user has the Select privilege on the same column in the
target table.
User has the Update privilege on any other column of the violations
table if the user has the Update privilege on the same column in the
target table.
(1 of 2)
Index User has the Index privilege on the violations table if the user has the
Index privilege on the target table.
Alter Alter privilege is not granted on the violations table. (Users cannot
alter violations tables.)
The following rules apply to ownership of the violations table and privileges
on the violations table:
■ When the violations table is created, the owner of the target table
becomes the owner of the violations table.
■ The owner of the violations table automatically receives all table-
level privileges on the violations table, including the Alter and
References privileges. However, the database server prevents the
owner of the violations table from altering the violations table or
adding a referential constraint to the violations table.
■ You can use the GRANT and REVOKE statements to modify the initial
set of privileges on the violations table.
■ When you issue an INSERT, DELETE, or UPDATE statement on a target
table that has a filtering-mode unique index or constraint defined on
it, you must have the Insert privilege on the violations and
diagnostics tables.
If you do not have the Insert privilege on the violations and
diagnostics tables, the database server executes the INSERT, DELETE,
or UPDATE statement on the target table provided that you have the
necessary privileges on the target table. The database server does not
return an error concerning the lack of insert permission on the viola-
tions and diagnostics tables unless an integrity violation is detected
during the execution of the INSERT, DELETE, or UPDATE statement.
For example, assume that you have a table named cust_subset that holds
customer data. This table consists of the following columns: ssn (customer
social security number), fname (customer first name), lname (customer last
name), and city (city in which the customer lives).
■ User barbara has the Insert and Index privileges on the table. She
also has the Select privilege on the ssn and lname columns.
■ User carrie has the Update privilege on the city column. She also has
the Select privilege on the ssn column.
■ User danny has the Alter privilege on the table.
The database server grants the following set of initial privileges on the
cust_subset_viols violations table:
■ User alvin is the owner of the violations table, so he has all table-
level privileges on the table.
■ User barbara has the Insert, Delete, and Index privileges on the
violations table.
User barbara has the Select privilege on the following columns of the
violations table: the ssn column, the lname column, the
informix_tupleid column, the informix_optype column, and the
informix_recowner column.
■ User carrie has the Insert and Delete privileges on the violations
table.
User carrie has the Update privilege on the following columns of the
violations table: the city column, the informix_tupleid column, the
informix_optype column, and the informix_recowner column.
However, user carrie cannot update the informix_tupleid column
because this column is a SERIAL column.
User carrie has the Select privilege on the following columns of the
violations table: the ssn column, the informix_tupleid column, the
informix_optype column, and the informix_recowner column.
■ User danny has no privileges on the violations table.
■ Every pair of update rows in the violations table has the same value
in the informix_tupleid column to indicate that both rows refer to
the same row in the target table.
■ If the target table has columns named informix_tupleid,
informix_optype, or informix_recowner, the database server
attempts to generate alternative names for these columns in the
violations table by appending a digit to the end of the column name
(for example, informix_tupleid1). If this attempt fails, the database
server returns an error, and the violations table is not started for the
target table.
■ When a table functions as a violations table, it cannot have triggers
or constraints defined on it.
■ When a table functions as a violations table, users can create indexes
on the table, even though the existence of an index affects perfor-
mance. Unique indexes on the violations table cannot be set to the
filtering database object mode.
■ If a target table has a violations and diagnostics table associated with
it, dropping the target table in cascade mode (the default mode)
causes the violations and diagnostics tables to be dropped also. If the
target table is dropped in the restricted mode, the existence of the
violations and diagnostics tables causes the DROP TABLE statement
to fail.
■ Once a violations table is started for a target table, you cannot use the
ALTER TABLE statement to add, modify, or drop columns in the target
table, violations table, or diagnostics table. Before you can alter any
of these tables, you must issue a STOP VIOLATIONS TABLE statement
for the target table.
■ The database server does not clear out the contents of the violations
table before or after it uses the violations table during an Insert,
Update, Delete, or SET Database Object Mode operation.
Because your START VIOLATIONS statement does not include a USING clause,
the violations table is named customer_vio by default. The customer_vio
table includes the following columns:
customer_num
fname
lname
company
address1
address2
city
state
zipcode
phone
informix_tupleid
informix_optype
informix_recowner
The customer_vio table has the same table definition as the customer table
except that the customer_vio table has three additional columns that contain
information about the operation that caused the bad row.
C = Constraint violation
I = Unique-index violation
(1 of 2)
The following table explains the circumstances under which the database
server grants each privilege on the diagnostics table. The first column lists
each privilege. The second column explains the conditions under which the
database server grants that privilege to a user.
Insert User has the Insert privilege on the diagnostics table if the user has any
of the following privileges on the target table: the Insert privilege, the
Delete privilege, or the Update privilege on any column
Delete User has the Delete privilege on the diagnostics table if the user has
any of the following privileges on the target table: the Insert privilege,
the Delete privilege, or the Update privilege on any column
Select User has the Select privilege on the diagnostics table if the user has the
Select privilege on any column in the target table
Update User has the Update privilege on the diagnostics table if the user has
the Update privilege on any column in the target table
(1 of 2)
Index User has the Index privilege on the diagnostics table if the user has the
Index privilege on the target table
■ When the diagnostics table is created, the owner of the target table
becomes the owner of the diagnostics table.
■ The owner of the diagnostics table automatically receives all table-
level privileges on the diagnostics table, including the Alter and
References privileges. However, the database server prevents the
owner of the diagnostics table from altering the diagnostics table or
adding a referential constraint to the diagnostics table.
■ You can use the GRANT and REVOKE statements to modify the initial
set of privileges on the diagnostics table.
■ When you issue an INSERT, DELETE, or UPDATE statement on a target
table that has a filtering-mode unique index or constraint defined on
it, you must have the Insert privilege on the violations and
diagnostics tables.
If you do not have the Insert privilege on the violations and
diagnostics tables, the database server executes the INSERT, DELETE,
or UPDATE statement on the target table provided that you have the
necessary privileges on the target table. The database server does not
return an error concerning the lack of insert permission on the viola-
tions and diagnostics tables unless an integrity violation is detected
during the execution of the INSERT, DELETE, or UPDATE statement.
For example, assume that you have a table called cust_subset that holds
customer data. This table consists of the following columns: ssn (social
security number), fname (first name), lname (last name), and city (city in
which the customer lives).
The database server grants the following set of initial privileges on the
cust_subset_diags diagnostics table:
■ User alvin is the owner of the diagnostics table, so he has all table-
level privileges on the table.
■ User barbara has the Insert, Delete, Select, and Index privileges on
the diagnostics table.
■ User carrie has the Insert, Delete, Select, and Update privileges on
the diagnostics table.
■ User danny has no privileges on the diagnostics table.
The following issues concern the structure and use of the diagnostics table:
■ The MAX ROWS clause of the START VIOLATIONS TABLE statement
sets a limit on the number of rows that can be inserted into the
diagnostics table when you execute a single statement, such as an
INSERT or SET Database Object Mode statement, on the target table.
■ The MAX ROWS clause limits the number of rows only for operations
in which the table functions as a diagnostics table.
Because your START VIOLATIONS TABLE statement does not include a USING
clause, the diagnostics table is named stock_dia by default. The stock_dia
table includes the following columns:
informix_tupleid
objtype
objowner
objname
Related Information
Related statements: SET DATABASE OBJECT MODE and STOP VIOLATIONS
TABLE
For a discussion of object modes and violation detection, see the Informix
Guide to SQL: Tutorial.
+
STOP VIOLATIONS TABLE
Use the STOP VIOLATIONS TABLE statement to drop the association between
a target table and the special violations and diagnostics tables.
XPS In Extended Parallel Server, the diagnostics table does not exist. The STOP
VIOLATIONS TABLE statement drops the association between the target table
and the violations table. ♦
Syntax
Usage
The STOP VIOLATIONS TABLE statement drops the association between the
target table and the violations and diagnostics tables. After you issue this
statement, the former violations and diagnostics tables continue to exist, but
they no longer function as violations and diagnostics tables for the target
table. They now have the status of regular database tables instead of viola-
tions and diagnostics tables for the target table. You must issue the DROP
TABLE statement to drop these two tables explicitly.
Related Information
Related statements: SET DATABASE OBJECT MODE and START VIOLATIONS
TABLE
For a discussion of database object modes and violation detection, see the
Informix Guide to SQL: Tutorial.
+ TRUNCATE
XPS
Use the TRUNCATE statement to quickly remove all rows from a table and
also remove all corresponding index data.
Syntax
TRUNCATE table
ONLY TABLE
Usage
You must be the owner of the table or have the DBA privilege to use this
statement.
The TRUNCATE statement does not automatically reset the serial value of a
column. To reset the serial value of a column, you must do so explicitly, either
before or after you run the TRUNCATE statement.
Restrictions
The statement will not succeed if any of the following conditions exist:
■ One or more cursors are open on the table
■ Referential constraints exist on the table and any of the referencing
tables has at least one row
■ A shared or exclusive lock on the table already exists
Example
The following statement deletes all rows and related index data from the cust
table:
TRUNCATE TABLE cust
Because the TRUNCATE statement does not alter the schema, the database
server does not automatically update statistics. After you use this statement,
you might want to issue an UPDATE STATISTICS statement.
If the table was fragmented, after the statement executes, each fragment has
a space allocated for it that is the same size as that of the first extent size. The
fragment size of any indexes also correspond to the size of the first extents.
Using this statement can be faster than removing all rows from a table with
the DELETE statement because it does not activate any DELETE triggers. In
addition, when you use this statement, the database server creates a log entry
for the entire TRUNCATE statement rather than for each deleted row.
You might also use this statement instead of dropping a table and then recre-
ating it. When you drop and recreate a table, you have to regrant privileges
on the table. In addition, you must recreate any indexes, constraints, and
triggers defined on the table. The TRUNCATE statement leaves these database
objects and privileges intact.
Related Information
Related Statements: DELETE, DROP TABLE
+ UNLOAD
DB
Use the UNLOAD statement to write the rows retrieved in a SELECT statement
SQLE to an operating-system file.
Syntax
SELECT
UNLOAD TO ' filename ' Statement
p. 2-634
DELIMITER ' delimiter '
Usage
To use the UNLOAD statement, you must have the Select privilege on all
columns selected in the SELECT statement. For information on database-level
and table-level privileges, see “GRANT” on page 2-500.
The SELECT statement can consist of a literal SELECT statement or the name
of a character variable that contains a SELECT statement. (See “SELECT” on
page 2-634.)
UNLOAD TO File
The UNLOAD TO file contains the selected rows retrieved from the table. You
can use the UNLOAD TO file as the LOAD FROM file in a LOAD statement.
The following table shows types of data and their output format in the
UNLOAD TO file (when the locale is the default locale, U.S. English).
simple large objects TEXT and BYTE columns are unloaded directly into the
(TEXT, BYTE) UNLOAD TO file. For more information, see “Unloading
Simple Large Objects” on page 2-809.
smart large objects CLOB and BLOB columns are unloaded into a separate
(CLOB, BLOB) operating-system file on the client computer. The field for
the CLOB or BLOB column in the UNLOAD TO file
contains the name of this separate file. For more infor-
mation, see “Unloading Smart Large Objects” on
page 2-809.
user-defined data The associated opaque type must have an export support
formats (opaque function defined if special processing is required to copy
types) the data in the internal format of the opaque type to the
format in the UNLOAD TO file. An export binary support
function might also be required if the data is in binary
format. The data in the UNLOAD TO file would corre-
spond to the format that the export or exportbinary
support function returns.
(3 of 3)
For more information on DB environment variables, refer to the Informix
Guide to SQL: Reference. For more information on GL environment variables,
refer to the Informix Guide to GLS Functionality.
GLS If you are using a nondefault locale, the formats of DATE, DATETIME, MONEY,
and numeric column values in the UNLOAD TO file are determined by the
formats that the locale supports for these data types. For more information,
see the Informix Guide to GLS Functionality. ♦
The following statement unloads rows from the customer table where the
value of customer_num is greater than or equal to 138, and puts them in a
filenamed cust_file:
UNLOAD TO 'cust_file' DELIMITER '!'
SELECT * FROM customer WHERE customer_num> = 138
If you are unloading files that contain simple-large-object data types, do not
use the following characters as delimiters in the UNLOAD TO file: 0 to 9, a to
f, A to F, newline character, or backslash.
GLS For TEXT columns, the database server handles any required code-set conver-
sions for the data. For more information, see the Informix Guide to GLS
Functionality. ♦
If you are unloading files that contain simple-large-object data types, objects
smaller than 10 kilobytes are stored temporarily in memory. You can adjust
the 10-kilobyte setting to a larger setting with the DBBLOBBUF environment
variable. Simple large objects that are larger than the default or the setting of
the DBBLOBBUF environment variable are stored in a temporary file. For
additional information about the DBBLOBBUF environment variable, see the
Informix Guide to SQL: Reference.
In the preceding formats, the pound (#) symbols represent the digits of the
unique hexadecimal smart-large-object identifier. The database server uses
the hexadecimal ID for the first smart large object in the file. The maximum
number of digits for a smart-large-object identifier is 17. However, most
smart large objects would have an identifier with significantly fewer digits.
When the database server unloads the first smart large object, it creates the
appropriate BLOB or CLOB client file with the hexadecimal identifier of the
smart large object. It appends any additional BLOB or CLOB values to the
appropriate file until the file size reaches a limit of 2 gigabytes. If additional
smart-large-object values are present, the database server creates another
BLOB or CLOB client file whose filename contains the hexadecimal identifier
of the next smart large object to unload.
Each BLOB or CLOB value is appended to the appropriate file. The database
server might create several files if the values are extremely large or there are
many values.
In this format, start_off is the starting offset (in hexadecimal) of the smart-
large-object value within the client file, length is the length (in hexadecimal)
of the BLOB or CLOB value, and client_path is the pathname for the client file.
No spaces can appear between these values.
For example, if a CLOB value is 512 bytes long and is at offset 256 in the
/usr/apps/clob9ce7.318 file, the CLOB value appears as follows in the
UNLOAD TO file:
|100,200,/usr/apps/clob9ce7.318|
If a BLOB or CLOB column value occupies an entire client file, the CLOB or
BLOB column value appears as follows in the UNLOAD TO file:
client_path
GLS For CLOB columns, the database server handles any required code-set
conversions for the data. For more information, see the Informix Guide to GLS
Functionality. ♦
DELIMITER Clause
Use the DELIMITER clause to identify the delimiter that separates the data
contained in each column in a row in the output file. If you omit this clause,
DB-Access checks the DBDELIMITER environment variable. If DBDELIMITER
has not been set, the default delimiter is the pipe (|).
You can specify the TAB (CTRL-I) or <blank> (ASCII 32) as the delimiter symbol.
You cannot use the following as the delimiter symbol:
■ Backslash (\)
■ Newline character (CTRL-J)
■ Hexadecimal numbers (0 to 9, a to f, A to F)
Related Information
Related statements: LOAD and SELECT
For a discussion of the GLS aspects of the UNLOAD statement, see the Informix
Guide to GLS Functionality.
+
UNLOCK TABLE
Use the UNLOCK TABLE statement in a database without transactions to
unlock a table that you previously locked with the LOCK TABLE statement.
The UNLOCK TABLE statement fails in a database that uses transactions.
Syntax
synonym
Usage
You can lock a table if you own the table or if you have the Select privilege on
the table, either from a direct grant to yourself or from a grant to public. You
can only unlock a table that you locked. You cannot unlock a table that
another process locked. Only one lock can apply to a table at a time.
The table name either is the name of the table you are unlocking or a
synonym for the table. Do not specify a view or a synonym of a view.
To change the lock mode of a table in a database without transactions, use the
UNLOCK TABLE statement to unlock the table, then issue a new LOCK TABLE
statement. The following example shows how to change the lock mode of a
table in a database that was created without transactions:
LOCK TABLE items IN EXCLUSIVE MODE
.
.
.
UNLOCK TABLE items
.
.
.
LOCK TABLE items IN SHARE MODE
ANSI If you are using an ANSI-compliant database, do not issue an UNLOCK TABLE
statement. The UNLOCK TABLE statement fails if it is issued within a trans-
action, and a transaction is always in effect in an ANSI-compliant database. ♦
Related Information
Related statements: BEGIN WORK, COMMIT WORK, LOCK TABLE, and
ROLLBACK WORK
For a discussion of concurrency and locks, see the Informix Guide to SQL:
Tutorial.
UPDATE
Use the UPDATE statement to change the values in one or more columns of
one or more rows in a table or view.
IDS With Dynamic Server, you can also use this statement to change the values in
one or more elements in an ESQL/C collection variable. ♦
Syntax
SET Clause
UPDATE table p. 2-819
view WHERE Condition
XPS
p. 4-27
synonym
+
Subset of
+ IDS E/C FROM Clause
IDS p. 2-829
ONLY ( table ) SPL
Optimizer
( synonym )
Directives WHERE CURRENT OF cursor_id
p. 4-244
+
Collection Derived Table SET Clause
IDS p. 4-9 p. 2-819
E/C
SPL
WHERE CURRENT OF cursor_id
(2 of 2)
Usage
Use the UPDATE statement to update any of the following types of objects:
To update data in a table, you must either own the table or have the Update
privilege for the table (see “GRANT” on page 2-500). To update data in a
view, you must have the Update privilege, and the view must meet the
requirements that are explained in “Updating Rows Through a View” on
page 2-817.
If you omit the WHERE clause, all rows of the target table are updated.
If you are using effective checking, and the checking mode is set to
IMMEDIATE, all specified constraints are checked at the end of each UPDATE
statement. If the checking mode is set to DEFERRED, all specified constraints
are not checked until the transaction is committed.
DB If you omit the WHERE clause and are in interactive mode, DB-Access does
not run the UPDATE statement until you confirm that you want to change all
rows. However, if the statement is in a command file, and you are running
from the command line, the statement executes immediately. ♦
Warning: If you use the UPDATE statement on a supertable without the ONLY
keyword and without a WHERE clause, all rows of the supertable and its subtables
are updated.
You cannot use the ONLY keyword if you plan to use the WHERE CURRENT
OF clause to update the current row of the active set of a cursor.
In addition, if a view is built on a table that has a derived value for a column,
that column is not updatable through the view. However, other columns in
the view can be updated.
In an updatable view, you can update the values in the underlying table by
inserting values into the view.
You can use data-integrity constraints to prevent users from updating values
in the underlying table when the update values do not fit the SELECT
statement that defined the view. For more information, see “WITH CHECK
OPTION Keywords” on page 2-338.
Because duplicate rows can occur in a view even though the underlying table
has unique rows, be careful when you update a table through a view. For
example, if a view is defined on the items table and contains only the
order_num and total_price columns, and if two items from the same order
have the same total price, the view contains duplicate rows. In this case, if
you update one of the two duplicate total price values, you have no way to
know which item price is updated.
Important: If you are using a view with a check option, you cannot update rows to
a remote table.
You can create temporary tables with the WITH NO LOG option. These tables
are never logged and are not recoverable.
XPS In Extended Parallel Server, tables that you create with the RAW table type
are never logged. Thus, RAW tables are not recoverable, even if the database
uses logging. For information about RAW tables, refer to the Informix Guide to
SQL: Reference. ♦
If you are within an explicit transaction, and the update fails, the database
server automatically undoes the effects of the update. ♦
Locking Considerations
When a row is selected with the intent to update, the update process acquires
an update lock. Update locks permit other processes to read, or share, a row
that is about to be updated but do not let those processes update or delete it.
Just before the update occurs, the update process promotes the shared lock to
an exclusive lock. An exclusive lock prevents other processes from reading or
modifying the contents of the row until the lock is released.
An update process can acquire an update lock on a row or a page that has a
shared lock from another process, but you cannot promote the update lock
from shared to exclusive (and the update cannot occur) until the other
process releases its lock.
If the number of rows affected by a single update is very large, you can
exceed the limits placed on the maximum number of simultaneous locks. If
this occurs, you can reduce the number of transactions per UPDATE
statement, or you can lock the page or the entire table before you execute the
statement.
SET Clause
Use the SET clause to identify the columns to update and assign values to
each column. The clause supports the following formats:
■ A single-column format, which pairs a single column to a single
expression
■ A multiple-column format, which lists multiple columns and sets
them equal to corresponding expressions
Single-Column Format
SET p. 2-820
Multiple-Column Format
p.2-823
Single-Column Format
Use the single-column format of the SET clause to pair a single column to a
single expression.
column = expression
( singleton select )
NULL
IDS
collection_var
The following examples illustrate the single-column format of the SET clause.
UPDATE customer
SET address1 = '1111 Alder Court',
city = 'Palo Alto',
zipcode = '94301'
WHERE customer_num = 103;
UPDATE stock
SET unit_price = unit_price * 1.07;
IDS If you are updating a supertable in a table hierarchy, the SET clause cannot
include a subquery that references a subtable.
Multiple-Column Format
Use the multiple-column format of the SET clause to list multiple columns
and set them equal to corresponding expressions.
, ,
( column ) = ( expression )
*
( singleton select )
NULL
XPS
SPL function ( )
,
Argument
p. 4-6
The multiple-column format of the SET clause offers the following options for
listing a series of columns you intend to update:
You must list each expression explicitly, placing commas between expres-
sions and enclosing the set of expressions in parentheses. The number of
columns in the column list must be equal to the number of expressions in the
expression list, unless the expression list includes an SQL subquery.
The following examples show the multiple-column format of the SET clause:
UPDATE customer
SET (fname, lname) = ('John', 'Doe')
WHERE customer_num = 101
UPDATE manufact
SET * = ('HNT', 'Hunter')
WHERE manu_code = 'ANZ'
UPDATE table1
SET (col1, col2, col3) =
((SELECT MIN (ship_charge),
MAX (ship_charge) FROM orders),
'07/01/1997')
WHERE col4 = 1001
IDS If you are updating the supertable in a table hierarchy, the SET clause cannot
include a subquery that references one of its subtables.
In the following example, the SPL function p2() updates the i2 and c2
columns of the t2 table.
CREATE PROCEDURE p2()
RETURNING int, char(20);
RETURN 3, ‘three’;
END PROCEDURE;
In Extended Parallel Server, you create an SPL function with the CREATE
PROCEDURE statement. The CREATE FUNCTION statement is not available.
To update an unnamed row type, specify the ROW constructor before the
parenthesized list of field values. The following statement updates the name
column (an unnamed row type) of the empinfo table:
UPDATE empinfo
SET name = ROW('John','Williams')
WHERE emp_id =455
To update a named row type, specify the ROW constructor before the paren-
thesized list of field values and use the cast operator (::) to cast the row value
as a named row type. The following statement updates the address column
(a named row type) of the empinfo table:
UPDATE empinfo
SET address = ROW('103 Baker St','Tracy','CA')::address_t
WHERE emp_id = 3568
For more information on the syntax for ROW constructors, see “Constructor
Expressions” on page 4-116. See also “Literal Row” on page 4-239.
E/C The row-column SET clause can only support literal values for fields. To use
a variable to specify a field value, you must select the row into a row variable,
use host variables for the individual field values, then update the row
column with the row variable. For more information, see “Updating a Row
Variable” on page 2-832. ♦
E/C You can use ESQL/C host variables to insert non-literal values as:
When you use a row variable in the SET clause, the row variable must contain
values for each field value. For information on how to insert values into a row
variable, see “Updating a Row Variable” on page 2-832. ♦
To update only some of the fields in a row, you can perform one of the
following operations:
■ Specify the field names with field projection for all fields whose
values remain unchanged.
For example, the following UPDATE statement changes only the
street and city fields of the address column of the empinfo table:
UPDATE empinfo
SET address = ROW('23 Elm St', 'Sacramento',
address.state)
WHERE emp_id = 433
The address.state field remains unchanged.
E/C ■ Select the row into a row variable and update the desired fields.
For more information, see “Updating a Row Variable” on
page 2-832. ♦
E/C You can also use a collection variable to update values in a collection column.
With a collection variable you can insert one or more individual elements in
SPL a collection. For more information, see “Collection Derived Table” on
page 4-9. ♦
Example
For example, suppose you define the tab1 table as follows:
CREATE TABLE tab1
(
int1 INTEGER,
list1 LIST(ROW(a INTEGER, b CHAR(5)) NOT NULL),
dec1 DECIMAL(5,2)
)
The collection column, list1, in this example has three elements. Each element
is an unnamed row type with an INTEGER field and a CHAR(5) field. The first
element is composed of two literal values, an integer (2) and a quoted string
('zyxwv'). The second and third elements also use a quoted string to indicate
the value for the second field. However, they each designate the value for the
first field with an expression rather than a literal value.
As indicated in the diagram for “UPDATE” on page 2-815, you can use only
a subset of the FROM clause. You cannot use the LOCAL keyword or the
SAMPLES OF segment of the FROM clause with the UPDATE statement.
The following example shows how you can use a FROM clause to introduce
tables to be joined in the WHERE clause.
UPDATE tab1
SET tab1.a = tab2.a
FROM tab1, tab2, tab3
WHERE tab1.b = tab2.b AND tab2.c =tab3.c
For a complete description of the FROM Clause, see the “FROM Clause” on
page 650.
WHERE Clause
The WHERE clause lets you limit the rows that you want to update. If you
omit the WHERE clause, every row in the table is updated.
The database server also sets SQLSTATE and SQLCODE to these values if the
UPDATE... WHERE... is a part of a multistatement prepare and the database
server returns no rows. ♦
The UPDATE statement does not advance the cursor to the next row, so the
current row position remains unchanged.
IDS You cannot use this clause if you are selecting from only one table in a table
hierarchy. That is, you cannot use this option if you use the ONLY keyword. ♦
E/C To use the CURRENT OF keywords, you must have previously used the
DECLARE statement to define the cursor with the FOR UPDATE option.
If the DECLARE statement that created the cursor specified one or more
columns in the FOR UPDATE clause, you are restricted to updating only those
columns in a subsequent UPDATE...WHERE CURRENT OF statement. The
advantage to specifying columns in the FOR UPDATE clause of a DECLARE
statement is speed. The database server can usually perform updates more
quickly if columns are specified in the DECLARE statement. ♦
SPL Before you can use the CURRENT OF keywords, you must declare a cursor
with the FOREACH statement. ♦
Tip: You can use an update cursor to perform updates that are not possible with the
UPDATE statement.
The following ESQL/C example illustrates the CURRENT OF form of the
WHERE clause. In this example, updates are performed on a range of
customers who receive 10-percent discounts (assume that a new column,
discount, is added to the customer table). The UPDATE statement is prepared
outside the WHILE loop to ensure that parsing is done only once.
char answer [1] = 'y';
EXEC SQL BEGIN DECLARE SECTION;
char fname[32],lname[32];
int low,high;
EXEC SQL END DECLARE SECTION;
main()
{
EXEC SQL connect to 'stores_demo';
EXEC SQL prepare sel_stmt from
'select fname, lname from customer \
where cust_num between ? and ? for update';
EXEC SQL declare x cursor for sel_stmt;
printf("\nEnter lower limit customer number: ");
scanf("%d", &low);
printf("\nEnter upper limit customer number: ");
scanf("%d", &high);
EXEC SQL open x using :low, :high;
EXEC SQL prepare u from
'update customer set discount = 0.1 \
where current of x';
while (1)
{
EXEC SQL fetch x into :fname, :lname;
if ( SQLCODE == SQLNOTFOUND)
break;
}
printf("\nUpdate %.10s %.10s (y/n)?", fname, lname);
if (answer = getch() == 'y')
EXEC SQL execute u;
EXEC SQL close x;
}
The UPDATE statement and the Collection Derived Table segment allow you
to update a particular field or group of fields in the row variable. You specify
the new field values in the SET clause. For example, the following UPDATE
changes the x and y fields in the myrect ESQL/C row variable:
EXEC SQL BEGIN DECLARE SECTION;
row (x int, y int, length float, width float) myrect;
EXEC SQL END DECLARE SECTION;
.
.
.
EXEC SQL select into :myrect from rectangles
where area = 64;
EXEC SQL update table(:myrect)
set x=3, y=4;
Suppose that after the SELECT statement, the myrect2 variable has the values
x=0, y=0, length=8, and width=8. After the UPDATE statement, the myrect2
variable has field values of x=3, y=4, length=8, and width=8.
You cannot use a row variable in the Collection Derived Table segment of an
INSERT statement. However, you can use the UPDATE statement and the
Collection Derived Table segment to insert new field values into a row host
variable, as long as you specify a value for every field in the row. For
example, the following code fragment inserts new field values into the
myrect row variable and then inserts this row variable into the database:
EXEC SQL update table(:myrect)
set x=3, y=4, length=12, width=6;
EXEC SQL insert into rectangles
values (72, :myrect);
If the row variable is an untyped variable, you must use a SELECT statement
before the UPDATE so that ESQL/C can determine the data types of the fields.
An UPDATE of a field or fields in a row variable cannot include a WHERE
clause.
The row variable stores the fields of the row. However, it has no intrinsic
connection with a database column. Once the row variable contains the
correct field values, you must then save the variable into the row column
with one of the following SQL statements:
■ To update the row column in the table with contents of the row
variable, use an UPDATE statement on a table or view name and
specify the row variable in the SET clause.
For more information, see “Updating Row-Type Columns” on
page 2-826.
■ To insert a row in a column, use the INSERT statement on a table or
view name and specify the row variable in the VALUES clause.
For more information, see “Inserting Values into Row-Type
Columns” on page 2-546.
For more information on how to use SPL row variables, see the Informix Guide
to SQL: Tutorial. For more information on how to use ESQL/C row variables,
see the discussion of complex data types in the Informix ESQL/C Programmer’s
Manual. ♦
Related Information
Related statements: DECLARE, INSERT, OPEN, SELECT, and FOREACH
For a discussion of the GLS aspects of the UPDATE statement, see the Informix
Guide to GLS Functionality.
For information on how to access row and collections with ESQL/C host
variables, see the discussion of complex data types in the Informix ESQL/C
Programmer’s Manual.
+
UPDATE STATISTICS
Use the UPDATE STATISTICS statement to:
Syntax
Routine Statistics
p. 2-844
Usage
You cannot update the statistics used by the optimizer for a table or UDR that
is external to the current database. That is, you cannot update statistics on
remote database objects.
If you use the FOR TABLE clause without a specific table name to build distri-
butions on all of the tables in the database, distributions will also be built on
all of the temporary tables in your session.
XPS In Extended Parallel Server, the UPDATE STATISTICS statement does not
update, maintain, or collect statistics on indexes. The statement does not
update the syscolumns and sysindexes tables. Any information about
indexes, the syscolumns, and the sysindexes tables in the following pages
does not apply to Extended Parallel Server. ♦
For example, assume your database has the typed table hierarchy that
appears in Figure 2-2, which shows a supertable named employee that has a
subtable named sales_rep. The sales_rep table, in turn, has a subtable named
us_sales_rep.
Figure 2-2
Table Hierarchy
employee
sales_rep
us_sales_rep
In contrast, the following example generates statistical data for each column
in table sales_rep but does not act on tables employee or us_sales_rep:
UPDATE STATISTICS FOR TABLE ONLY sales_rep
If pages are found with the delete flag marked as 1, the corresponding keys
are removed from the B-tree cleaner list.
If you do not specify a mode, the database server uses low by default.
IDS In Dynamic Server, the LOW mode option updates index and column
statistics for specified columns also. The database server generates and
updates this statistical data in the syscolumns, and sysindexes tables.
When you use the low mode, the database server generates the least amount
of information about the column. If you want the UPDATE STATISTICS
statement to do minimal work, specify a column that is not part of an index.
Because the low mode does not update data in the sysdistrib system catalog
table, all distributions associated with the customer table remain intact, even
those that already exist on the customer_num column. ♦
When you specify the DROP DISTRIBUTIONS option, the database server
removes the distribution data that exists for the column or columns you
specify. If you do not specify any columns, the database server removes all
the distribution data for that table.
You must have the DBA privilege or be the owner of the table to use this
option.
As the example shows, you drop the distribution data at the same time you
update the statistical data that the LOW mode option generates.
If you use the MEDIUM mode option, the database server scans tables at least
once and takes longer to execute on a given table than the LOW mode option.
You must have the DBA privilege or be the owner of the table to create
medium distributions.
For more on the similarities between the Medium and High Modes, see the
“Resolution Clause” on page 2-842.
You must have the DBA privilege or be the owner of the table to create high
distributions.
If you use the HIGH mode option to update statistics, the database server can
take considerable time to gather the information across the database, partic-
ularly a database with large tables. The HIGH keyword might scan each table
several times (for each column). To minimize processing time, specify a table
name and column names within that table.
For more on the similarities between the Medium and High Modes, see the
“Resolution Clause.”
Resolution Clause
Use the Resolution clause to adjust the size of the distribution bin, designate
whether or not to avoid calculating data on indexes, and with the Medium
mode, to adjust the confidence level.
RESOLUTION Clause
for MEDIUM Mode
RESOLUTION Clause
for HIGH Mode
RESOLUTION Clause
for MEDIUM Mode
RESOLUTION percent
IDS
confidence_level
DISTRIBUTIONS ONLY
RESOLUTION Clause
for HIGH Mode
RESOLUTION percent
IDS
DISTRIBUTIONS ONLY
The optimizer estimates the effect of a WHERE clause by examining, for each
column included in the WHERE clause, the proportionate occurrence of data
values contained in the column.
You cannot create distributions for BYTE or TEXT columns. If you include a
BYTE or TEXT column in an UPDATE STATISTICS statement that specifies
medium or high distributions, no distributions are created for those columns.
Distributions are constructed for other columns in the list, and the statement
does not return an error.
Use this option to avoid the examination of index information that can
consume considerable processing time.
This option does not affect the recalculation of information on tables, such as
the number of pages used, the number of rows, and fragment information.
UPDATE STATISTICS needs this data to construct accurate column distribu-
tions and requires little time and system resources to collect it.
Routine Statistics
Use the Routine Statistics portion of the UPDATE STATISTICS statement to
update the optimized execution plans for SPL routines in the sysprocplan
system catalog table.
FOR PROCEDURE
routine
IDS
PROCEDURE
FUNCTION routine ( )
ROUTINE
Routine Parameter List
p. 4-286
Specific Name
SPECIFIC PROCEDURE p. 4-296
FUNCTION
ROUTINE
The following table explains the keywords that you can use when you update
routine statistics.
KEYWORD Purpose
FUNCTION Reoptimizes the execution plan for any SPL function with the
specified routine name (and parameter types that match
routine parameter list, if supplied).
PROCEDURE Reoptimizes the execution plan for any SPL procedure with
the specified routine name (and parameter types that match
routine parameter list, if supplied).
ROUTINE Reoptimizes the execution plan for SPL functions and SPL
procedures with the specified routine name (and parameter
types that match routine parameter list, if supplied).
The sysprocplan system catalog table stores execution plans for SPL routines.
Two actions update the sysprocplan system catalog table:
If you change a table that an SPL routine references, you can run UPDATE
STATISTICS to reoptimize on demand, rather than waiting until the next time
an SPL routine that uses the table executes.
To drop statistics for a column that holds one of these data types, you must
execute UPDATE STATISTICS in the low mode and use the DROP DISTRIBU-
TIONS option. When you use this option, the database server removes the
row in the sysdistrib system catalog table that corresponds to the tableid and
column. In addition, the database server removes any large objects that
might have been created for storing the statistics information.
Requirements
UPDATE STATISTICS collects statistics for opaque data types only if you have
defined user-defined routines for statcollect(), statprint(), and the selectivity
functions. You must have usage permissions on these routines.
When you use the UPDATE STATISTICS statement to convert the indexes to
use with a newer database server, the indexes are implicitly dropped and re-
created. The only time that an UPDATE STATISTICS statement causes table
indexes to be implicitly dropped and recreated is when you upgrade a
database for use with a newer database server.
Performance
The more specific you make the list of objects that UPDATE STATISTICS
examines, the faster it completes execution. Limiting the number of columns
distributed speeds the update. Similarly, precision affects the speed of the
update. If all other keywords are the same, LOW works fastest, but HIGH
examines the most data.
Related Information
Related statements: SET EXPLAIN and SET OPTIMIZATION
E/C
WHENEVER
Use the WHENEVER statement to trap exceptions that occur during the
execution of SQL statements.
Syntax
Usage
The WHENEVER statement is equivalent to placing an exception-checking
routine after every SQL statement. The following table summarizes the types
of exceptions for which you can check with the WHENEVER statement.
If you do not use the WHENEVER statement in a program, the program does
not automatically abort when an exception occurs. Your program must
explicitly check for exceptions and take whatever corrective action you
desire. If you do not check for exceptions, the program simply continues
running. However, as a result of the errors, the program might not perform
its intended purpose.
After line 8, the preprocessor does not insert code to check for errors after SQL
statements. Therefore, any errors that the INSERT statement (line 10), the
SELECT statement (line 11), and DISCONNECT statement (line 12) generate are
ignored. However, the SELECT statement does not stop program execution if
it does not locate any rows; the WHENEVER statement on line 7 tells the
program to continue if such an exception occurs.
1 main()
2 {
SQLERROR Keyword
If you use the SQLERROR keyword, any SQL statement that encounters an
error is handled as the WHENEVER SQLERROR statement directs. If an error
occurs, the sqlcode variable (sqlca.sqlcode, SQLCODE) is less than zero (0)
and the SQLSTATE variable has a class code with a value greater than 02.
ERROR Keyword
ERROR is a synonym for SQLERROR.
SQLWARNING Keyword
If you use the SQLWARNING keyword, any SQL statement that generates a
warning is handled as the WHENEVER SQLWARNING statement directs. If a
warning occurs, the first field of the warning structure in SQLCA
(sqlca.sqlwarn.sqlwarn0) is set to W, and the SQLSTATE variable has a class
code of 01.
In addition to setting the first field of the warning structure, a warning also
sets an additional field to W. The field that is set indicates the type of warning
that occurred.
In each case, the sqlcode variable is set to 100, and the SQLSTATE variable
has a class code of 02. For the name of the sqlcode variable in each Informix
product, see the table in “SQLERROR Keyword” on page 2-851.
The following statement calls the no_rows() function each time the NOT
FOUND condition exists:
If you do not use any WHENEVER NOT FOUND statements in a program, the
default for WHENEVER NOT FOUND is CONTINUE.
CONTINUE Keyword
Use the CONTINUE keyword to instruct the program to ignore the exception
and to continue execution at the next statement after the SQL statement. The
default action for all exceptions is CONTINUE. You can use this keyword to
turn off a previously specified option.
STOP Keyword
Use the STOP keyword to instruct the program to stop execution when the
specified exception occurs. The following statement halts execution of an
ESQL/C program each time that an SQL statement generates a warning:
GOTO Keywords
Use the GOTO clause to transfer control to the statement that the label
identifies when a particular exception occurs. The GOTO keyword is the
ANSI-compliant syntax of the clause. The GO TO keywords are a non-ANSI
synonym for GOTO.
You must define the labeled statement in each program block that contains
SQL statements. If your program contains more than one user-defined
function, you might need to include the labeled statement and its code in each
function. When the preprocessor reaches the function that does not contain
the labeled statement, it tries to insert the code associated with the labeled
statement. However, if you do not define this labeled statement within the
function, the preprocessor generates an error.
To correct this error, either put a labeled statement with the same label name
in each user-defined function, issue another WHENEVER statement to reset
the error condition, or use the CALL clause to call a separate function.
CALL Clause
Use the CALL clause to transfer program control to the named UDR when a
particular exception occurs. Do not include parentheses after the UDR name.
The following WHENEVER statement causes the program to call the
error_recovery() function if the program detects an error:
EXEC SQL WHENEVER SQLERROR CALL error_recovery;
■ You cannot pass arguments to the named function nor can you return
values from the named function. If the named function needs
external information, use global variables or the GOTO clause of
WHENEVER to transfer control to a label that calls the named
function.
■ You cannot specify the name of an SPL routine in the CALL clause. To
call an SPL routine, use the CALL clause to execute a function that
contains the EXECUTE FUNCTION (or EXECUTE PROCEDURE)
statement.
■ Make sure that all functions that the WHENEVER...CALL statement
affects can find a declaration of the named function.
Related Information
Related Statements: EXECUTE FUNCTION, EXECUTE PROCEDURE and FETCH
For discussions on exception handling and error checking, see the Informix
ESQL/C Programmer’s Manual.
SPL Statements
3
In This Chapter . . . . . . . . . . . . . . . . . . . . 3-3
CALL . . . . . . . . . . . . . . . . . . . . . . 3-4
CASE . . . . . . . . . . . . . . . . . . . . . . 3-7
CONTINUE . . . . . . . . . . . . . . . . . . . . 3-10
DEFINE . . . . . . . . . . . . . . . . . . . . . 3-11
EXIT . . . . . . . . . . . . . . . . . . . . . . 3-24
FOR. . . . . . . . . . . . . . . . . . . . . . . 3-26
FOREACH . . . . . . . . . . . . . . . . . . . . 3-30
IF . . . . . . . . . . . . . . . . . . . . . . . 3-37
LET . . . . . . . . . . . . . . . . . . . . . . . 3-41
ON EXCEPTION . . . . . . . . . . . . . . . . . . 3-45
RAISE EXCEPTION . . . . . . . . . . . . . . . . . 3-50
RETURN . . . . . . . . . . . . . . . . . . . . . 3-52
SYSTEM . . . . . . . . . . . . . . . . . . . . . 3-55
TRACE . . . . . . . . . . . . . . . . . . . . . 3-58
WHILE . . . . . . . . . . . . . . . . . . . . . 3-62
3-2 Informix Guide to SQL: Syntax
In This Chapter
You can use Stored Procedure Language (SPL) statements to write SPL
routines (formerly referred to as stored procedures), and you can store these
routines in the database. SPL routines are effective tools for controlling SQL
activity.
For task-oriented information about using SPL routines, see the Informix
Guide to SQL: Tutorial.
XPS In Extended Parallel Server, to create an SPL function you must use the
CREATE PROCEDURE statement. Extended Parallel Server does not support
the CREATE FUNCTION statement. ♦
IDS
In Dynamic Server, for backward compatibility, you can create an SPL
function with the CREATE PROCEDURE statement. For external functions,
you must use the CREATE FUNCTION statement. Informix recommends that
you use the CREATE FUNCTION statement as you create all new user-defined
functions. ♦
CALL
Use the CALL statement to execute a user-defined routine (UDR) from within
an SPL routine.
Syntax
CALL procedure ( ) ;
,
Argument
p.4-6 ,
routine_var
,
RETURNING data_var
Usage
The CALL statement invokes a UDR. The CALL statement is identical in
behavior to the EXECUTE PROCEDURE and EXECUTE FUNCTION statements,
but you can only use CALL from within an SPL routine. You can use CALL in
an ESQL/C program or with DB-Access, but only if you place the statement
within an SPL routine executed by the program or DB-Access.
Specifying Arguments
If a CALL statement contains more arguments than the called UDR expects,
you receive an error.
If a CALL statement specifies fewer arguments than the called UDR expects,
the arguments are said to be missing. The database server initializes missing
arguments to their corresponding default values. (See “CREATE
PROCEDURE” on page 2-199 and “CREATE FUNCTION” on page 2-146.)
This initialization occurs before the first executable statement in the body of
the UDR.
In each UDR call, you have the option of specifying parameter names for the
arguments you pass to the UDR. Each of the following examples are valid for
a UDR that expects character arguments named t, n, and d, in that order:
CALL add_col (t='customer', n = 'newint', d ='integer');
CALL add_col('customer','newint','integer');
The first routine call (no_args) expects no returned values. The second
routine call is to a function (yes_args), which expects three returned values.
The not_much() procedure declares three integer variables (i, j, and k) to
receive the returned values from yes_args.
XPS
CASE
Use the CASE statement when you need to take one of many branches
depending on the value of an SPL variable or a simple expression. The CASE
statement is a fast alternative to the IF statement.
Syntax
Statement Block
ELSE p. 4-298
Usage
You can use the CASE statement to create a set of conditional branches within
an SPL routine.
Both the WHEN and ELSE clauses are optional, but you must supply one or
the other. If you do not specify either a WHEN clause or an ELSE clause, you
receive a syntax error.
CONTINUE
Use the CONTINUE statement to start the next iteration of the innermost FOR,
WHILE, or FOREACH loop.
Syntax
CONTINUE FOR ;
WHILE
FOREACH
Usage
When you encounter a CONTINUE statement, the SPL routine skips the rest of
the statements in the innermost loop of the indicated type. Execution
continues at the top of the loop with the next iteration. In the following
example, the loopskip function inserts values 3 through 15 into the table
testtable. The function also returns values 3 through 9 and 13 through 15 in
the process. The function does not return the value 11 because it encounters
the CONTINUE FOR statement. The CONTINUE FOR statement causes the
function to skip the RETURN WITH RESUME statement.
CREATE FUNCTION loop_skip()
RETURNING INT;
DEFINE i INT;
.
.
.
FOR i IN (3 TO 15 STEP 2)
INSERT INTO testtable values(i, null, null);
IF i = 11
CONTINUE FOR;
END IF;
RETURN i WITH RESUME;
END FOR;
END FUNCTION;
DEFINE
Use the DEFINE statement to declare variables that an SPL routine uses and to
assign them data types.
Syntax
,
DEFINE GLOBAL SPL_var data_type DEFAULT Default Value ;
p. 3-16
TEXT
,
SPL_var data_type
REFERENCES BYTE
TEXT
synonym
view
PROCEDURE
IDS
BLOB
CLOB
COLLECTION
opaque_type
distinct_type
Usage
The DEFINE statement is not an executable statement. The DEFINE statement
must appear after the routine header and before any other statements.
If you define a local variable (by using DEFINE without the GLOBAL
keyword), the scope of the variable is the statement block in which it is
defined. You can use the variable anywhere within the statement block. You
can also use the same variable name outside the statement block with a
different definition.
If you define a variable with the GLOBAL keyword, the variable is global in
scope and is available outside the statement block and to other SPL routines.
Redeclaration or Redefinition
If you define the same variable twice within the same statement block, you
receive an error. You can redefine a variable within a nested block, in which
case it temporarily hides the outer declaration. The following example
produces an error:
CREATE PROCEDURE example1()
DEFINE n INT; DEFINE j INT;
DEFINE n CHAR (1); -- redefinition produces an error
.
.
.
SPL routines that are running in the current session share global variables.
Because the database server does not save global variables in the database,
the global variables do not remain when the current session closes. The data
types of global variables you use in your SPL routine must match the data
types of variables in the global environment.
Databases do not share global variables. The database server and any appli-
cation development tools do not share global variables.
The first declaration of a global variable establishes the variable in the global
environment; subsequent global declarations simply bind the variable to the
global environment and establish the value of the variable at that point. The
following example shows two SPL procedures, proc1 and proc2; each has
defined the global variable gl_out:
If proc1 is called first, gl_out is set to 13 and then incremented to 14. If proc2
is then called, it sees that the value of gl_out is already defined, so the default
value of 23 is not applied. Then, proc2 assigns the existing value of 14 to tmp.
If proc2 had been called first, gl_out would have been set to 23, and 23 would
have been assigned to tmp. Later calls to proc1 would not apply the default
of 13.
Default Value
Literal Number
p. 4-237
Quoted String
p. 4-260
Literal Interval
p. 4-234
Literal Datetime
p. 4-231
CURRENT
DATETIME
Field Qualifier
p. 4-71
USER
TODAY
NULL
DBSERVERNAME
SITENAME
You can provide a literal value or a null value as the default for a global
variable. You can also use a call to a built-in function to provide the default
value. The following example uses the SITENAME function to provide a
default value. It also defines a global BYTE variable.
CREATE PROCEDURE gl_def()
DEFINE GLOBAL gl_site CHAR(200) DEFAULT SITENAME;
DEFINE GLOBAL gl_byte REFERENCES BYTE DEFAULT NULL;
.
.
.
END PROCEDURE
SITENAME or DBSERVERNAME
If you use the value returned by SITENAME or DBSERVERNAME as the
default, the variable must be defined as a CHAR, VARCHAR, NCHAR, or
NVARCHAR data type.
IDS If you are using Dynamic Server, Informix recommends that the size of the
variable be at least 128 bytes long. You risk getting an error message during
INSERT and ALTER TABLE operations if the length of the variable is too small
to store the default value. ♦
XPS If you are using Extended Parallel Server, Informix recommends that the
length of the variable be at least 18 bytes. You risk getting an error message
during INSERT and ALTER TABLE operations if the length of the variable is too
small to store the default value. ♦
USER
If you use the value returned by USER as the default, the variable must be
defined as a CHAR, VARCHAR, NCHAR, or NVARCHAR data type.
IDS If you are using Dynamic Server, Informix recommends that the length of the
variable be at least 32 bytes. You risk getting an error message during INSERT
and ALTER TABLE operations if the length of the variable is too small to store
the default value. ♦
XPS If you are using Extended Parallel Server, Informix recommends that the
length of the variable be at least 8 bytes. You risk getting an error message
during INSERT and ALTER TABLE operations if the length of the variable is too
small to store the default value. ♦
CURRENT
If you use CURRENT as the default, the variable must be a DATETIME value.
If the YEAR TO FRACTION keyword has qualified your variable, you can use
CURRENT without qualifiers. If your variable uses another set of qualifiers,
you must provide the same qualifiers when you use CURRENT as the default
value. The following example defines a DATETIME variable with qualifiers
and uses CURRENT with matching qualifiers:
DEFINE GLOBAL d_var DATETIME YEAR TO MONTH
DEFAULT CURRENT YEAR TO MONTH;
TODAY
If you use TODAY as the default, the variable must be a DATE value.
A variable defined with the type SET, MULTISET, or LIST is a typed collection
variable. A typed collection variable can hold only a collection of its type.
You must use the NOT NULL keywords when you define the elements of a
typed collection variable, as in the following examples:
DEFINE a SET ( INT NOT NULL );
Note that with variable c, both the INTEGER values in the SET and the SET
values in the LIST are defined as NOT NULL.
You can define collection variables with nested complex types to hold
matching nested complex type data. Any type or depth of nesting is allowed.
You can nest row types within collection types, collection types within row
types, collection types within collection types, row types within collection
and row types, and so on.
In this example, varA is a generic collection variable that changes its data
type to the data type of the currently assigned collection. The first LET
statement makes varA a SET variable. The second LET statement makes varA
a LIST variable.
A generic row variable, defined with the ROW keyword, can hold data from
any row type. A named row variable holds data from the named row type
specified in the variable definition. The following statements show examples
of generic row variables and named row variables:
DEFINE d ROW; -- generic row variable
A named row variable holds named row types of the same type in the
variable definition.
To define a variable that will hold data stored in an unnamed row type, use
the ROW keyword followed by the fields of the row type, as in:
DEFINE area ROW ( x int, y char(10) );
Row variables can have fields, just as row types have fields. To assign a value
to a field of a row variable, use the SQL dot notation variableName.fieldName,
followed by an expression, as in the following example:
CREATE ROW TYPE rectangle_t (start point_t, length real,
width real);
DEFINE r rectangle_t;
-- Define a variable of a named row type
LET r.length = 45.5;
-- Assign a value to a field of the variable
When you assign a value to a row variable, you can use any allowed
expression described in EXPRESSION.
The following example defines a variable of the opaque type point, which
holds the x and y coordinates of a two-dimensional point:
DEFINE b point;
The data types of variables that are defined as database columns are resolved
at run time; therefore, column and table do not need to exist at compile time.
IDS The DEFINE statement does not have a FUNCTION keyword. Use the
PROCEDURE keyword, whether you are calling a user-defined procedure or
a user-defined function. ♦
This definition disables the built-in LENGTH function within the scope of the
statement block. You would use such a definition if you had already created
a user-defined routine with the name length.
If you create an SPL routine with the same name as an aggregate function
(SUM, MAX, MIN, AVG, COUNT) or with the name extend, you must qualify
the routine name with the owner name.
If you pass a variable of BYTE or TEXT data type to an SPL routine, the data is
passed to the database server and stored in the root dbspace or dbspaces that
the DBSPACETEMP environment variable specifies, if it is set. You do not
need to know the location or name of the file that holds the data. BYTE or
TEXT manipulation requires only the name of the BYTE or TEXT variable as it
is defined in the routine.
EXIT
Use the EXIT statement to stop the execution of a FOR, WHILE, or FOREACH
loop.
Syntax
EXIT FOR ;
WHILE
FOREACH
Usage
The EXIT statement causes the innermost loop of the indicated type (FOR,
WHILE, or FOREACH) to terminate. Execution resumes at the first statement
outside the loop.
The following example uses an EXIT FOR statement. In the FOR loop, when j
becomes 6, the IF condition i = 5 in the WHILE loop is true. The FOR loop
stops executing, and the SPL procedure continues at the next statement
outside the FOR loop (in this case, the END PROCEDURE statement). In this
example, the procedure ends when j equals 6.
FOR j = 1 TO 20
IF j > 10 THEN
CONTINUE FOR;
END IF
FOR
Use the FOR statement to initiate a controlled (definite) loop when you want
to guarantee termination of the loop. The FOR statement uses expressions or
range operators to establish a finite number of iterations for a loop.
Syntax
,
Expression Statement
FOR loop_var IN ( Range
) Block END FOR
p. 4-298
, ;
expression
= Expression
Range
Expression
Range
left_expression TO right_expression
STEP increment_expr
Usage
The database server computes all expressions before the FOR statement
executes. If one or more of the expressions are variables, and their values
change during the loop, the change has no effect on the iterations of the loop.
The FOR loop terminates when loop_var is equal to the values of each element
in the expression list or range in succession or when it encounters an EXIT
FOR statement.
If you omit the STEP option, the database server gives increment_expr the
value of -1 if right_expression is less than left_expression, or +1 if
right_expression is more than left_expression. If increment_expr is specified, it
must be negative if right_expression is less than left_expression, or positive if
right expression is more than left_expression. The two statements in the
following example are equivalent. In the first statement, the STEP increment
is explicit. In the second statement, the STEP increment is implicitly 1.
FOR index IN (12 TO 21 STEP 1)
-- statement block
END FOR
FOR index = 12 TO 21
-- statement block
END FOR
The expressions in the IN list do not have to be numeric values, as long as you
do not use range operators in the IN list. The following example uses a
character expression list:
FOR c IN ('hello', (SELECT name FROM t), 'world', v1, v2)
INSERT INTO t VALUES (c);
END FOR
The following FOR statement shows the use of a numeric expression list:
FOR index IN (15,16,17,18,19,20,21)
-- statement block
END FOR
FOREACH
Use a FOREACH loop to select and manipulate more than one row.
Syntax
SELECT...INTO Statement
FOREACH Statement Block END FOREACH
p. 3-33 p. 4-298
WITH HOLD ;
cursor FOR
WITH HOLD
SPL_var
Usage
A FOREACH loop is the procedural equivalent of using a cursor. When a
FOREACH statement executes, the database server takes the following
actions:
An SPL routine that returns more than one row, collection element, or set of
values is called a cursor function. An SPL routine that returns only one row
or value is a noncursor function.
The SELECT statement in the FOREACH statement must include the INTO
clause. It can also include UNION and ORDER BY clauses, but it cannot use the
INTO TEMP clause. For a complete description of SELECT syntax and usage,
see “SELECT” on page 634.
The type and count of each variable in the variable list must match each value
that the SELECT...INTO statement returns.
Restrictions
When you use a collection cursor to fetch individual elements from a
collection variable the FOREACH statement has the following restrictions:
In addition, the SELECT statement that you associate with the collection
cursor has the following restrictions:
Examples
The following excerpt from an SPL routine shows how to fill a collection
variable and then how to use a cursor to access individual elements:
DEFINE a SMALLINT;
DEFINE b SET(SMALLINT NOT NULL);
In this example, the SELECT statement selects one element at a time from the
collection variable b into the element variable a. The select list is an asterisk,
because the collection variable b contains a collection of built-in types. The
variable b is used with the TABLE keyword as a Collection Derived Table. For
more information, see “Collection Derived Table” on page 4-9.
The next example also shows how to fill a collection variable and then how
to use a cursor to access individual elements. This example, however, uses a
list of row type fields in its select list.
.
.
.
DEFINE employees employee_t;
DEFINE n VARCHAR(30);
DEFINE s INTEGER;
XPS In Extended Parallel Server, you must use EXECUTE PROCEDURE. Extended
Parallel Server does not support the EXECUTE FUNCTION statement. ♦
IDS In Dynamic Server, if you use EXECUTE PROCEDURE, the database server
looks first for a user-defined procedure of the name you specify. If it finds the
procedure, the server executes it. If it does not find the procedure, it looks for
a user-defined function of the same name to execute. If the database server
finds neither a function nor a procedure, it issues an error message.
If you use EXECUTE FUNCTION, the database server looks for a user-defined
function of the name you specify. If it does not find a function of that name,
the server issues an error message. ♦
A called SPL function can return zero (0) or more values or rows.
The type and count of each variable in the variable list must match each value
that the function returns.
IF
Use an IF statement to create a branch within an SPL routine.
Syntax
Condition
IF p. 4-27 THEN END IF
;
IF Statement List
p. 3-39 IF Statement List
ELSE p. 3-39
Usage
The condition that the IF clause states is evaluated. If the result is true, the
statements that follow the THEN keyword execute. If the result is false, and
an ELIF clause exists, the statements that follow the ELIF clause execute. If no
ELIF clause exists, or if the condition in the ELIF clause is not true, the state-
ments that follow the ELIF keyword execute.
In the following example, the SPL function uses an IF statement with both an
ELIF clause and an ELSE clause. The IF statement compares two strings and
displays a 1 to indicate that the first string comes before the second string
alphabetically, or a -1 if the first string comes after the second string
alphabetically. If the strings are the same, a zero (0) is returned.
CREATE FUNCTION str_compare (str1 CHAR(20), str2 CHAR(20))
RETURNING INT;
DEFINE result INT;
ELIF Clause
Use the ELIF clause to specify one or more additional conditions to evaluate.
If you specify an ELIF clause, and the IF condition is false, the ELIF condition
is evaluated. If the ELIF condition is true, the statements that follow the ELIF
clause execute.
ELSE Clause
The ELSE clause executes if no true previous condition exists in the IF clause
or any of the ELIF clauses.
Conditions in an IF Statement
Conditions in an IF statement are evaluated in the same way as conditions in
a WHILE statement.
If any expression that the condition contains evaluates to null, the condition
automatically becomes untrue. Consider the following points:
An expression within the condition that has an UNKNOWN value (due to the
use of an uninitialized variable) causes an immediate error. The statement
terminates and raises an exception.
IF Statement List
IF Statement Back to IF
List p. 3-37
Statement
BEGIN Block END
p. 4-298
Subset of
SPL Statements
p. 3-39
Subset of
SQL Statements ;
p. 3-40
The preceding diagram for the “IF Statement List” refers to this section.
You can use a SELECT statement only if you use the INTO TEMP clause to put
the results of the SELECT statement into a temporary table.
The diagram for the “IF Statement List” on page 3-39 refers to this section.
LET
Use the LET statement to assign values to variables or to call a user-defined
function from an SPL routine and assign the return value or values to
variables.
Syntax
,
,
Argument
p. 4-6
Expression
p. 4-73
( SELECT Statement )
p. 3-42
Usage
If you assign a value to a single variable, it is called a simple assignment; if you
assign values to two or more variables, it is called a compound assignment.
You can also assign the value of an expression to a variable. At run time, the
value of the SPL expression is computed first. The resulting value is cast to the
data type of variable, if possible, and the assignment occurs. If conversion is
not possible, an error occurs, and the value of variable name is undefined.
The following example shows several LET statements that assign values to
SPL variables:
LET a = c + d ;
LET a,b = c,d ;
LET expire_dt = end_dt + 7 UNITS DAY;
LET name = 'Brunhilda';
LET sname = DBSERVERNAME;
LET this_day = TODAY;
You cannot use multiple values to operate on other values. For example, the
following statement is illegal:
LET a,b = (c,d) + (10,15); -- ILLEGAL EXPRESSION
The examples in this section use a SELECT statement in a LET statement. You
can use a SELECT statement to assign values to one or more variables on the
left side of the equals (=) operator, as the following example shows:
LET a,b = (SELECT c1,c2 FROM t WHERE id = 1);
LET a,b,c = (SELECT c1,c2 FROM t WHERE id = 1), 15;
You cannot use a SELECT statement to make multiple values operate on other
values. The following example is illegal:
LET a,b = (SELECT c1,c2 FROM t) + (10,15); -- ILLEGAL CODE
If the SELECT statement returns more than one row, you must enclose the
SELECT statement in a FOREACH loop.
An SPL function can return multiple values (that is, values from multiple
columns in the same row) into a list of variable names. In other words, the
function can have multiple values in its RETURN statement and the LET
statement can have multiple variables to receive the returned values.
When you call the function, you must specify all the necessary arguments to
the function unless the arguments of the function have default values. If you
name one of the parameters in the called function, with syntax such as name
= 'smith', you must name all of the parameters.
An SPL function that selects and returns more than one row must be enclosed
in a FOREACH loop.
The following LET statement is not legal, because it tries to add the output of
two functions and then assign the sum to two variables, a and b. You can
easily split this LET statement into two legal LET statements.
LET a, b = func1() + func2(); -- ILLEGAL CODE
In the first statement, the SPL function function1 accepts collection1 (that is,
any collection data type) as an argument and returns its value to the variable
d. In the second statement, the SPL function function2 accepts set1 as an
argument and returns a value to the variable a.
ON EXCEPTION
Use the ON EXCEPTION statement to specify the actions that are taken for a
particular error or a set of errors.
Syntax
Statement
ON EXCEPTION Block END EXCEPTION
p. 4-298
, ;
IN ( error_number ) WITH RESUME
SET SQL_error_var
, ISAM_error_var
, error_data_var
Usage
The ON EXCEPTION statement, together with the RAISE EXCEPTION
statement, provides an error-trapping and error-recovery mechanism for
SPL. The ON EXCEPTION statement defines a list of errors that you want to
trap as the SPL routine executes and specifies the action (within the statement
block) to take when the trap is triggered. If the IN clause is omitted, all errors
are trapped.
You can use more than one ON EXCEPTION statement within a given
statement block.
When an error occurs, the database server searches for the last declaration of
the ON EXCEPTION statement, which traps the particular error code. The ON
EXCEPTION statement can have the error number in the IN clause or have no
IN clause. If the database server finds no pertinent ON EXCEPTION statement,
the error code passes back to the caller (the SPL routine, application, or inter-
active user), and execution aborts.
The following example uses two ON EXCEPTION statements with the same
error number so that error code 691 can be trapped in two levels of nesting:
CREATE PROCEDURE delete_cust (cnum INT)
ON EXCEPTION IN (-691) -- children exist
BEGIN -- Begin-end is necessary so that other DELETEs
-- don't get caught in here.
ON EXCEPTION IN (-691)
DELETE FROM another_child WHERE num = cnum;
DELETE FROM orders WHERE customer_num = cnum;
END EXCEPTION -- for 691
ON EXCEPTION IN (-300)
-- action B
END EXCEPTION
ON EXCEPTION IN (-210, -211, -212)
SET error_num
-- action A
END EXCEPTION
.
.
.
RAISE EXCEPTION
Use the RAISE EXCEPTION statement to simulate the generation of an error.
Syntax
Usage
Use the RAISE EXCEPTION statement to simulate an error or to generate an
error with a custom message. An ON EXCEPTION statement can trap the
generated error.
If you omit the ISAM_error_var parameter, the database server sets the ISAM
error code to zero (0) when the exception is raised. If you want to use the
error_text_var parameter but not specify a value for ISAM_error_var, you can
specify zero (0) as the value of ISAM_error_var.
For example, the following statement raises the error number -208 and
inserts the text a missing file into the variable of the system-generated
error message:
RAISE EXCEPTION -208, 0, 'a missing file';
In the following example, a negative value for alpha raises exception -746
and provides a specific message describing the problem. The code should
contain an ON EXCEPTION statement that traps for an exception of -746.
FOREACH SELECT c1 INTO alpha FROM sometable
IF alpha < 0 THEN
RAISE EXCEPTION -746, 0, ‘a < 0 found’ -- emergency exit
END IF
END FOREACH
When the SPL routine executes and the IF condition is met, the database
server returns the following error:
- 746: a < 0 found.
For more information about the scope and compatibility of exceptions, see
“ON EXCEPTION” on page 3-45.
RETURN
Use the RETURN statement to designate the values that the SPL function
returns to the calling module.
Syntax
RETURN ;
,
Expression
p. 4-73
WITH RESUME
Usage
The RETURN statement returns zero (0) or more values to the calling process.
IDS In Dynamic Server, for backward compatibility, you can use this statement
inside a CREATE PROCEDURE statement to create an SPL function. However,
Informix recommends that you only use this statement inside the CREATE
FUNCTION statement to create new user-defined functions. ♦
All the RETURN statements in the SPL function must be consistent with the
RETURNING clause of the CREATE FUNCTION (or CREATE PROCEDURE)
statement, which defines the function.
The number and data type of values in the RETURN statement, if any, must
match in number and data type the data types that are listed in the
RETURNING clause of the CREATE FUNCTION (or CREATE PROCEDURE)
statement. You can choose to return no values even if you specify one or more
values in the RETURNING clause. If you use a RETURN statement without any
expressions, but the calling UDR or program expects one or more return
values, it is equivalent to returning the expected number of null values to the
calling program.
In the following example, the SPL function includes two acceptable RETURN
statements. A program that calls this function should check if no values are
returned and act accordingly.
CREATE FUNCTION two_returns (stockno INT)
RETURNING CHAR (15);
DEFINE des CHAR(15);
ON EXCEPTION (-272)
-- if user doesn’t have select privs...
RETURN;
-- return no values.
END EXCEPTION;
SELECT DISTINCT descript INTO des FROM stock
WHERE stocknum = stockno;
RETURN des;
END FUNCTION
A RETURN statement without any expressions exits only if the SPL function
is declared not to return values; otherwise it returns nulls.
The following example shows a cursor function that another UDR can call.
After the RETURN I WITH RESUME statement returns each value to the calling
UDR or program, the next line of sequence executes the next time sequence
is called. If backwards equals zero (0), no value is returned to the calling UDR
or program, and execution of sequence stops.
CREATE FUNCTION sequence (limit INT, backwards INT)
RETURNING INT;
DEFINE i INT;
FOR i IN (1 TO limit)
RETURN i WITH RESUME;
END FOR
IF backwards = 0 THEN
RETURN;
END IF
SYSTEM
Use the SYSTEM statement to make an operating-system command run from
within an SPL routine.
Syntax
SYSTEM expression ;
SPL_var
Usage
If the supplied expression is not a character expression, expression is
converted to a character expression before the operating-system command is
made. The complete character expression passes to the operating system and
executes as an operating-system command.
The expressions that follow the SYSTEM statements in this example contain
two variables, %tmp% and %SystemRoot%. Both of these variables are
defined by the Windows NT operating system.
TRACE
Use the TRACE statement to control the generation of debugging output.
Syntax
TRACE ON ;
OFF
PROCEDURE
Expression
p. 4-73
Usage
The TRACE statement generates output that is sent to the file that the SET
DEBUG FILE TO statement specifies.
■ Variables
■ Routine arguments
■ Return values
■ SQL error codes
■ ISAM error codes
If you use the TRACE statement before you specify a DEBUG file to contain the
output, an error is generated.
Any routine that the SPL routine calls inherits the trace state. That is, a called
routine assumes the same trace state (ON, OFF, or PROCEDURE) as the calling
routine. The called routine can set its own trace state, but that state is not
passed back to the calling routine.
A routine that is executed on a remote database server does not inherit the
trace state.
TRACE ON
If you specify the keyword ON, all statements are traced. The values of
variables (in expressions or otherwise) are printed before they are used. To
turn tracing ON implies tracing both routine calls and statements in the body
of the routine.
TRACE OFF
If you specify the keyword OFF, all tracing is turned off.
TRACE PROCEDURE
If you specify the keyword PROCEDURE, only the routine calls and return
values, but not the body of the routine, are traced.
Displaying Expressions
You can use the TRACE statement with a quoted string or an expression to
display values or comments in the output file. If the expression is not a literal
expression, the expression is evaluated before it is written to the output file.
You can use the TRACE statement with an expression even if you used a
TRACE OFF statement earlier in a routine. However, you must first use the
SET DEBUG statement to establish a trace-output file.
-- do something
END;
END PROCEDURE
TRACE PROCEDURE;
LET i = test2();
TRACE ON;
LET i = i + 1;
TRACE OFF;
TRACE 'i+1 = ' || i+1;
TRACE 'Exiting testproc';
END PROCEDURE
WHILE
Use the WHILE statement to establish a loop with variable end conditions.
Syntax
Usage
The condition is evaluated once at the beginning of the loop, and subse-
quently at the beginning of each iteration. The statement block is executed as
long as the condition remains true. The loop terminates when the condition
evaluates to not true.
LET i = 1;
WHILE i < 10
INSERT INTO tab_2 VALUES (i);
LET i = i + 1;
END WHILE;
END PROCEDURE
Segments
4
In This Chapter . . . . . . . . . . . . . . . . . . . . 4-3
Argument . . . . . . . . . . . . . . . . . . . . 4-6
Collection Derived Table . . . . . . . . . . . . . . . 4-9
Condition . . . . . . . . . . . . . . . . . . . . 4-27
Database Name. . . . . . . . . . . . . . . . . . . 4-47
Database Object Name . . . . . . . . . . . . . . . . 4-50
Data Type. . . . . . . . . . . . . . . . . . . . . 4-53
DATETIME Field Qualifier . . . . . . . . . . . . . . . 4-71
Expression . . . . . . . . . . . . . . . . . . . . 4-73
External Routine Reference. . . . . . . . . . . . . . . 4-202
Identifier . . . . . . . . . . . . . . . . . . . . . 4-205
INTERVAL Field Qualifier . . . . . . . . . . . . . . . 4-223
Jar Name . . . . . . . . . . . . . . . . . . . . . 4-226
Literal Collection . . . . . . . . . . . . . . . . . . 4-227
Literal DATETIME . . . . . . . . . . . . . . . . . 4-231
Literal INTERVAL . . . . . . . . . . . . . . . . . . 4-234
Literal Number . . . . . . . . . . . . . . . . . . . 4-237
Literal Row . . . . . . . . . . . . . . . . . . . . 4-239
Optimizer Directives . . . . . . . . . . . . . . . . . 4-244
Owner Name . . . . . . . . . . . . . . . . . . . 4-257
Quoted String . . . . . . . . . . . . . . . . . . . 4-260
Relational Operator . . . . . . . . . . . . . . . . . 4-265
Return Clause . . . . . . . . . . . . . . . . . . . 4-270
Routine Modifier . . . . . . . . . . . . . . . . . . 4-274
Routine Parameter List . . . . . . . . . . . . . . . . 4-286
Shared-Object Filename . . . . . . . . . . . . . . . . 4-292
Specific Name . . . . . . . . . . . . . . . . . . . 4-296
Statement Block . . . . . . . . . . . . . . . . . . 4-298
4-2 Informix Guide to SQL: Syntax
In This Chapter
Segments are language elements, such as table names and expressions, that
occur repeatedly in the syntax diagrams for SQL and SPL statements. These
language elements are discussed separately in this section for the sake of
clarity, ease of use, and comprehensive treatment.
Whenever a segment occurs within the syntax diagram for an SQL or SPL
statement, the diagram references the description of the segment in this
section.
Segments 4-3
Use of Segment Descriptions
The syntax diagram within each segment description is not a stand-alone
diagram. Instead it is a subdiagram that is subordinate to the syntax diagram
for an SQL or SPL statement.
First look up the syntax for the statement, and then turn to the segment
description to find out the complete syntax for the segment.
For example, if you want to enter a CREATE VIEW statement that includes a
database name and database server name in the view name, first look up the
syntax diagram for the CREATE VIEW statement. The table beneath the
diagram refers to the Database Object Name segment for the syntax for view.
The subdiagram for the Database Object Name segment shows you how to
qualify the simple name of a view with the name of the database or with the
name of both the database and the database server. Use the syntax in the
subdiagram to enter a CREATE VIEW statement that includes the database
name and database server name in the view name. The following example
creates the name_only view in the sales database on the boston database
server:
CREATE VIEW sales@boston:name_only AS
SELECT customer_num, fname, lname FROM customer
Segments 4-5
Argument
Argument
Use the Argument segment to pass a specific value to a routine parameter.
Use the Argument segment wherever you see a reference to an argument in
a syntax diagram.
Syntax
Argument
Subset of Expression
p. 4-8
parameter =
NULL
( singleton_select )
Usage
A parameter list for a user-defined routine (UDR) is defined in the CREATE
PROCEDURE or CREATE FUNCTION statement. If the UDR has a parameter
list, you can enter arguments when you execute the UDR. An argument is a
specific data element that matches the data type of one of the parameters for
the UDR.
When you execute a UDR, you can enter arguments in one of two ways:
If you use a parameter name for one argument, you must use a parameter
name for all the arguments.
If you attempt to execute a UDR with more arguments than the UDR expects,
you receive an error.
If you execute a UDR with fewer arguments than the UDR expects, the
arguments are said to be missing. The database server initializes missing
arguments to their corresponding default values. This initialization occurs
before the first executable statement in the body of the UDR.
Segments 4-7
Argument
Syntax
TABLE ( collection_expr )
,
alias
+ ( derived_column )
AS
E/C
( collection_var )
SPL
E/C
row_var
Segments 4-9
Collection Derived Table
Usage
A collection derived table is a virtual table in which the values in the rows of the
table are equivalent to the elements of a collection. In other words, a
collection derived table appears as a table in an SQL statement.
The TABLE keyword table converts a collection into a virtual table. You can
use the collection expression format to query a collection column or you can
use the collection variable or row variable format to manipulate the data in a
collection column.
With this format you can use joins, aggregates, WHERE clause, expressions,
the ORDER BY clause and other operations not available to you when you use
the collection-variable format. This format reduces the need for multiple
cursors and temporary tables.
Segments 4-11
Collection Derived Table
If the data type of the elements of the underlying collection expression is type,
the database server determines the row type of the collection derived table by
the following rules:
■ If type is a row type, and no derived column list is specified, then the
row type of the collection derived table is type.
■ If type is a row type and a derived column list is specified, then the
row type of the collection derived table is an unnamed row type
whose column types are the same as those of type and whose column
names are taken from the derived column list.
■ If type is not a row type, the row type of the collection derived table
is an unnamed row type that contains one column of type, and
whose name is specified in the derived column list. If a name is not
specified, the database server assigns an implementation-dependent
name to the column.
The extended examples shown in the following table illustrate these rules.
The table uses the following schema for its examples.
CREATE ROW TYPE person (name CHAR(255), id INT);
CREATE TABLE parents
(
name CHAR(255),
id INT,
children LIST (person NOT NULL)
);
CREATE TABLE parents2
(
name CHAR(255),
id INT,
children_ids LIST (INT NOT NULL)
);
Segments 4-13
Collection Derived Table
Derived-
Column Resulting Row Type
List of the Collection
Type Specified Derived Table Example
This format allows you to modify the contents of a variable as you would a
table in the database and then update the actual table with the contents of the
collection variable.
You can use the collection-variable format (the TABLE keyword preceding a
collection variable) in place of the name of a table, synonym, or view name in
the following SQL statements:
Segments 4-15
Collection Derived Table
The collection variable stores the elements of the collection. However, it has
no intrinsic connection with a database column. Once the collection variable
contains the correct elements, you must then save the variable into the actual
collection column of the table with either an INSERT or an UPDATE statement.
Segments 4-17
Collection Derived Table
After the DELETE statement executes, this collection variable contains the
elements {1,8,5,2}. The UPDATE statement at the end of this code fragment
saves the modified collection into the set_col column of the database.
Without this UPDATE statement, the collection column never has element
4 deleted.
CREATE_PROCEDURE test6()
DEFINE a SMALLINT;
DEFINE b SET(SMALLINT NOT NULL);
END PROCEDURE;
This SPL routine defines two variables, a and b, each to hold a set of
SMALLINT values. The first SELECT statement selects a SET column from one
row of table1 into b. Then, the routine declares a cursor that selects one
element at a time from b into a. When the cursor is positioned on the element
with the value 4, the DELETE statement deletes that element from b. Last, the
UPDATE statement updates the row of table1 with the new collection that is
stored in b.
For information on how to use collection variables in an SPL routine, see the
Informix Guide to SQL: Tutorial. ♦
Segments 4-19
Collection Derived Table
After you execute this ESQL/C program, the set_col column in table1
contains the values {1,8,10,5,2}.
This ESQL/C program defines two collection variables, a and b, and selects a
SET from table1 into b. The WHERE clause ensures that only one row is
returned. Then, the program defines a collection cursor, which selects
elements one at a time from b into a. When the program locates the element
with the value 4, the first UPDATE statement changes that element value to 10
and exits the loop.
In the first UPDATE statement, x is a derived column name used to update the
current element in the collection derived table. The second UPDATE
statement updates the base table table1 with the new collection. For infor-
mation on how to use collection host variables in an ESQL/C program, see
the discussion of complex data types in the Informix ESQL/C Programmer’s
Manual.
When you insert elements into a client-collection variable, you cannot specify
a SELECT statement or an EXECUTE FUNCTION statement in the VALUES
clause of the INSERT. However, when you insert elements into a server-
collection variable, the SELECT and EXECUTE FUNCTION statements are valid
in the VALUES clause. For more information on client- and server-collection
variables, see the Informix ESQL/C Programmer’s Manual.
Segments 4-21
Collection Derived Table
Use the TABLE keyword in place of the name of a table, synonym, or view
name in the following SQL statements:
■ The FROM clause of the SELECT statement to access a field of the row
variable
■ The UPDATE statement to modify an existing field in the row variable
The DELETE and INSERT statements do not support a row variable in the
Collection Derived Table segment.
For example, suppose an ESQL/C host variable a_row has the following
declaration:
EXEC SQL BEGIN DECLARE SECTION;
row(x int, y int, length float, width float) a_row;
EXEC SQL END DECLARE SECTION;
The following ESQL/C code fragment adds the fields in the a_row variable to
the row_col column of the tab_row table:
EXEC SQL update table(:a_row)
set x=0, y=0, length=10, width=20;
EXEC SQL update rectangles set rect = :a_row;
Related Information
Related statements: DECLARE, DELETE, DESCRIBE, FETCH, INSERT, PUT,
SELECT, UPDATE, DEFINE, and FOREACH
For information on how to use collection variables in an SPL routine, see the
Informix Guide to SQL: Tutorial.
Segments 4-23
Collection Derived Table
IDS
Collection Subquery
You can use a collection subquery to create a multiset collection from the
results of a subquery.
Syntax
Collection Subquery
MULTISET ( subquery )
SELECT ITEM singleton_select
Usage
The following table indicates the significance of the keywords in the
collection-subquery syntax.
Keywords Purpose
SELECT ITEM When you use the SELECT ITEM keywords, only one
expression is allowed in the projection list.
Do not repeat the SELECT keyword in the singleton subquery.
Restrictions
The following restrictions apply to a collection subquery:
The following table includes examples that access the schema created with
the following statements:
CREATE ROW TYPE rt1 (a INT);
CREATE ROW TYPE rt2 (x int, y rt1);
CREATE TABLE tab1 (col1 rt1, col2 rt2);
CREATE TABLE tab2 OF TYPE rt1;
CREATE TABLE tab3 (a ROW(x INT));
Segments 4-25
Collection Derived Table
Example
SELECT f(MULTISET(select * FROM tab 1 WHERE tab1.x = t.y))
FROM t
WHERE t.name = ‘john doe’;
Condition
Use a condition to test data to determine whether it meets certain qualifica-
tions. Use the Condition segment wherever you see a reference to a condition
in a syntax diagram.
Syntax
AND
OR
Comparison Conditions
p. 4-28
NOT
Condition with Subquery
p. 4-40
Usage
A condition is a collection of one or more search conditions, optionally
connected by the logical operators AND or OR. Search conditions fall into the
following categories:
Restrictions on a Condition
A condition can contain only an aggregate function if it is used in the HAVING
clause of a SELECT statement or the HAVING clause of a subquery. You cannot
use an aggregate function in a comparison condition that is part of a WHERE
clause in a DELETE, SELECT, or UPDATE statement unless the aggregate is on
a correlated column that originates from a parent query and the WHERE
clause is within a subquery that is within a HAVING clause.
Segments 4-27
Condition
NOT
T F
F T
? ?
+ IN Condition
p. 4-34
Column Name
p. 4-30 IS NULL
NOT
Segments 4-29
Condition
Refer to the following sections for more information on the use of the
different types of comparison conditions:
Warning: When you specify a date value in a comparison condition, make sure to
specify 4 digits instead of 2 digits for the year. When you specify a 4-digit year, the
DBCENTURY environment variable has no effect on how the database server
interprets the comparison condition. When you specify a 2-digit year, the
DBCENTURY environment variable can affect how the database server interprets the
comparison condition, so the comparison condition might not work as you intended.
For more information on the DBCENTURY environment variable, see the “Informix
Guide to SQL: Reference.”
Column Name
column
■ If the column has a numeric data type, do not surround the constant
expression with quotation marks.
■ If the column has a character data type, surround the constant
expression with quotation marks.
■ If the column has a date data type, surround the constant expression
with quotation marks. Otherwise, you might get unexpected results.
Segments 4-31
Condition
Relational-Operator Condition
Some relational-operator conditions are shown in the following examples:
city[1,3] = 'San'
quantity <= 3
customer_num != 105
If either expression is null for a row, the condition evaluates to false. For
example, if the paid_date column has a null, you cannot use either of the
following statements to retrieve that row:
SELECT customer_num, order_date FROM orders
WHERE paid_date = ''
BETWEEN Condition
For a BETWEEN test to be true, the value of the expression on the left of the
BETWEEN keyword must be in the inclusive range of the values of the two
expressions on the right of the BETWEEN keyword. Null values do not satisfy
the condition. You cannot use NULL for either expression that defines the
range.
Segments 4-33
Condition
IN Condition
The IN condition is satisfied when the expression to the left of the word IN is
included in the list of items.
,
Expression ( Literal Number )
p. 4-73 IN
p. 4-237
NOT Literal DATETIME
p. 4-231
Literal INTERVAL
p. 4-234
Quoted String
p. 4-260
TODAY
USER
CURRENT
DATETIME
Field
Qualifier
p. 4-71
SITENAME
DBSERVERNAME
Literal Collection
p. 4-227
The NOT option produces a search condition that is satisfied when the
expression is not in the list of items. Null values do not satisfy the condition.
E/C In ESQL/C, the built-in TODAY function is evaluated at execution time; the
built-in CURRENT function is evaluated when a cursor opens or when the
query executes, if it is a singleton SELECT statement. ♦
The built-in USER function is case sensitive; it perceives minnie and Minnie
as different values.
When you use the IN operator to search for an element in a collection, the
expression to the left or right of the IN keyword cannot contain a BYTE or
TEXT data type.
Suppose you create the following table that contains two collection columns:
CREATE TABLE tab_coll
(
set_num SET(INT NOT NULL),
list_name LIST(SET(CHAR(10) NOT NULL) NOT NULL)
);
Segments 4-35
Condition
The following partial examples show how you might use the IN operator for
search conditions on the collection columns of the tab_coll table:
WHERE 5 IN set_num
In general, when you use the IN operator on a collection data type, the
database server checks whether the value on the left of the IN operator is an
element in the set of values on the right of the IN operator.
IS NULL Condition
The IS NULL condition is satisfied if the column contains a null value. If you
use the IS NOT NULL option, the condition is satisfied when the column
contains a value that is not null. The following example shows an IS NULL
condition:
WHERE paid_date IS NULL
You can use the single quote (') only with the quoted string to match a literal
quote; you cannot use the ESCAPE clause. You can use the quote character as
the escape character in matching any other pattern if you write it as ''''.
NOT Option
The NOT option makes the search condition successful when the column on
the left has a value that is not null and does not match the pattern that the
quoted string specifies. For example, the following conditions exclude all
rows that begin with the characters Baxter in the lname column:
WHERE lname NOT LIKE 'Baxter%'
WHERE lname NOT MATCHES 'Baxter*'
LIKE Option
If you use the keyword LIKE, you can use the following wildcard characters
in the quoted string.
Wildcard Purpose
Segments 4-37
Condition
The following condition tests for the string tennis, alone or in a longer
string, such as tennis ball or table tennis paddle:
WHERE description LIKE '%tennis%'
The following condition tests for all descriptions that contain an underscore.
The backslash (\) is necessary because the underscore (_) is a wildcard
character.
WHERE description LIKE '%\_%'
The LIKE operator has an associated operator function called like(). You can
define a like() function to handle your own user-defined data types. For more
information, see the Extending Informix Dynamic Server 2000 manual.
MATCHES Option
If you use the keyword MATCHES, you can use the following wildcard
characters in the quoted string.
Wildcard Purpose
The following condition tests for the string tennis, alone or in a longer
string, such as tennis ball or table tennis paddle:
WHERE description MATCHES '*tennis*'
The following condition is true for the names Frank and frank:
WHERE fname MATCHES '[Ff]rank'
The following condition is true for any name that begins with either F or f:
WHERE fname MATCHES '[Ff]*'
The following condition is true for any name that ends with the letters a, b, c,
or d:
WHERE fname MATCHES '*[a-d]'
You can also use a single-character host variable as an escape character. The
following statement shows the use of a host variable as an escape character:
EXEC SQL BEGIN DECLARE SECTION;
char escp='z';
char fname[20];
EXEC SQL END DECLARE SECTION;
EXEC SQL select fname from customer
into :fname
where company like '%z_%' escape :escp;
Segments 4-39
Condition
The following example retrieves rows from the customer table in which the
value of the company column includes the question mark (?):
SELECT * FROM customer
WHERE company MATCHES '*z?*' ESCAPE 'z'
Stand-Alone Condition
A stand-alone condition can be any expression that is not explicitly listed in
the syntax for the comparison condition. Such an expression is valid only if
its result is of the Boolean type. For example, the following example returns
a value of the Boolean type:
funcname(x)
IN Subquery
p. 4-41
EXISTS Subquery
p. 4-42
You can use a SELECT statement within a condition; this combination is called
a subquery. You can use a subquery in a SELECT statement to perform the
following functions:
The subquery can depend on the current row that the outer SELECT statement
is evaluating; in this case, the subquery is a correlated subquery.
The kinds of subquery conditions are shown in the following sections with
their syntax. For a discussion of the different kinds of subquery conditions in
the context of the SELECT statement, see “Using a Condition in the WHERE
Clause” on page 2-661.
IN Subquery
Expression ( )
p. 4-73 IN subquery
NOT
Segments 4-41
Condition
The following example of an IN subquery finds the order numbers for orders
that do not include baseball gloves (stock_num = 1):
WHERE order_num NOT IN
(SELECT order_num FROM items WHERE stock_num = 1)
Because the IN subquery tests for the presence of rows, duplicate rows in the
subquery results do not affect the results of the main query. Therefore, you
can put the UNIQUE or DISTINCT keyword into the subquery with no effect
on the query results, although eliminating testing duplicates can reduce the
time needed for running the query.
EXISTS Subquery
EXISTS ( subquery )
NOT
The preceding example works equally well if you use SELECT * in the
subquery in place of the column names because the existence of the whole
row is tested; specific column values are not tested.
You use the ALL, ANY, and SOME keywords to specify what makes the search
condition true or false. A search condition that is true when the ANY keyword
is used might not be true when the ALL keyword is used, and vice versa.
Segments 4-43
Condition
In the following example of the ALL subquery, the first condition tests
whether each total_price is greater than the total price of every item in order
number 1023. The second condition uses the MAX aggregate function to
produce the same results.
total_price > ALL (SELECT total_price FROM items
WHERE order_num = 1023)
Using the NOT keyword with an ALL subquery tests whether an expression
is not true for at least one element returned by the subquery. For example, the
following condition is true when the expression total_price is not greater
than all the selected values. That is, it is true when total_price is not greater
than the highest total price in order number 1023.
NOT total_price > ALL (SELECT total_price FROM items
WHERE order_num = 1023)
The following conditions are true when the total price is greater than the total
price of at least one of the items in order number 1023. The first condition
uses the ANY keyword; the second uses the MIN aggregate function.
total_price > ANY (SELECT total_price FROM items
WHERE order_num = 1023)
Using the NOT keyword with an ANY subquery tests whether an expression
is not true for all elements returned by the subquery. For example, the
following condition is true when the expression total_price is not greater
than any selected value. That is, it is true when total_price is greater than
none of the total prices in order number 1023.
NOT total_price > ANY (SELECT total_price FROM items
WHERE order_num = 1023)
Segments 4-45
Condition
The following truth tables show the effect of the AND and OR operators.The
letter T represents a true condition, F represents a false condition, and the
question mark (?) represents an unknown value. Unknown values occur
when part of an expression that uses a logical operator is null.
AND T F ? OR T F ?
T T F ? T T T T
F F F F F T F ?
? ? F ? ? T ? ?
The row where order_num = 1023 is the row where ship_weight is null.
Because ship_weight is null, ship_charge/ship_weight is also null;
therefore, the truth value of ship_charge/ship_weight < 5 is UNKNOWN.
Because order_num = 1023 is TRUE, the AND table states that the truth value
of the entire condition is UNKNOWN. Consequently, that row is not chosen. If the
condition used an OR in place of the AND, the condition would be true.
Related Information
For discussions of comparison conditions in the SELECT statement and of
conditions with a subquery, see the Informix Guide to SQL: Tutorial.
For information on the GLS aspects of conditions, see the Informix Guide to
GLS Functionality.
Database Name
Use the Database Name segment to specify the name of a database. Use the
Database Name segment whenever you see a reference to a database name in
a syntax diagram.
Syntax
dbname
@dbservername
E/C db_var
Segments 4-47
Database Name
Usage
Database names are not case sensitive. You cannot use delimited identifiers
for a database name.
GLS If you are using a nondefault locale, you can use characters from the code set
of your locale in the names of databases.
If you are using a multibyte code set, keep in mind that the maximum length
of the database name refers to the number of bytes, not the number of
characters.
For further information on the GLS aspects of naming databases, see the
Informix Guide to GLS Functionality. ♦
In these examples, empinfo is the name of the database and personnel is the
name of the database server.
In this example, empinfo is the name of the database and personnel is the
name of the database server.
Segments 4-49
Database Object Name
Syntax
object
+
database : Owner Name .
p. 4-257
@ dbservername
Usage
If you are creating or renaming a database object, the name that you specify
must be unique in relation to other database objects of the same type in the
database. For example, a new constraint name must be unique among
constraint names that exist in the database.
A new name for a table, synonym, or view, must be unique among all the
tables, synonyms, views, and temporary tables that already exist in the
database.
IDS In Dynamic Server, the uniqueness requirement does not apply to UDR
names. For more information, see “Routine Overloading and Naming UDRs
with a Routine Signature” on page 4-52. ♦
A database object name must include the owner name for a database object
that you do not own. For example, if you specify a table that you do not own,
you must specify the owner of the table also. The owner of all the system
catalog tables is informix. ♦
GLS If you are using a nondefault locale, you can use characters from the code set
of your locale in database object names. For more information, see the
Informix Guide to GLS Functionality. ♦
In this example, the name of the database is empinfo. The name of the
database server is personnel. The name of the owner of the table is markg.
The name of the table is emp_names.
■ All of the arguments passed to the UDR are of built-in data types.
■ All of the parameters that the UDR accepts are of built-in data types.
■ Any values that a user-defined function returns are of built-in data
types.
Segments 4-51
Database Object Name
In other words, you cannot specify a remote UDR if any of its parameters or
return values are opaque, distinct, collection, or row types.
For any given UDR, at least one item in the signature must be unique among
all the UDRs stored in a name space or database.
As an alternative you can specify the specific name for the UDR if one was
given to it when it was created.
Data Type
The Data Type segment specifies the data type of a column or value. Use the
Data Type segment whenever you see a reference to a data type in a syntax
diagram.
Syntax
Built-In
Data Type
p. 4-53
+
IDS
User-Defined
Data Type
p. 4-66
Complex
Data Type
p. 4-67
Usage
The following sections summarize each of the categories of data types that
the various database server configurations support. For more information,
see the discussion of all data types in the Informix Guide to SQL: Reference.
Segments 4-53
Data Type
Numeric
Data Type
p. 4-57
Large-Object
+ Data Type
p. 4-62
Time
Data Type
p. 4-65
IDS BOOLEAN
The database server supports the following categories of built-in data types:
CHAR
CHARACTER ( size )
GLS NCHAR (1)
VARCHAR ( max )
CHARACTER VARYING , reserve
,0
GLS NVARCHAR
IDS LVARCHAR
Segments 4-55
Data Type
The TEXT and CLOB data types also support character data. For more infor-
mation, see “Large-Object Data Types” on page 4-62.
A varying-length column requires only the number of bytes that its data uses.
The VARCHAR and LVARCHAR data types are varying-length character data
types. For example, a VARCHAR(25) column reserves up to 25 bytes of storage
for the column value, but the string “This is a text string” uses only 21
bytes of the reserved 25 bytes.
The VARCHAR data type can store up to 255 bytes of varying data while the
LVARCHAR data type can store up to 2 kilobytes of text data.
Exact Numeric
Data Type
p. 4-58
Approximate Numeric
Data Type
p. 4-61
Segments 4-57
Data Type
DECIMAL
+ MONEY
( precision )
16 , scale
,2
INTEGER
INT
SMALLINT
IDS INT8
SERIAL
The precision of a number is the number of digits that the data type stores.
The scale is the number of digits to the right of the decimal separator.
The following table summarizes the exact numeric data types available.
INTEGER Stores a 4-byte integer value. These values can be in the range
-((2**31)-1) to (2**31)-1 (the values -2,147,483,647 to
2,147,483,647).
INT8 Stores an 8-byte integer value. These values can be in the range
(IDS) -((2**63)-1) to (2**63)-1 (the values -9,223,372,036,854,775,807 to
9,223,372,036,854,775,807).
MONEY(p,s) Stores fixed-point currency values. Has the same internal data
type as a fixed-point DECIMAL value.
Segments 4-59
Data Type
SERIAL Stores a 4-byte integer value that the database server generates.
These values can be in the range -((2**31)-1) to (2**31)-1 (the
values -2,147,483,647 to 2,147,483,647).
If you want to insert an explicit value in a serial column, you can
use any nonzero number. However, you cannot start or reset the
value (begin the sequence) of a serial column with a negative
number.
A serial column is not unique by definition. A unique index must
exist on the column to ensure unique values. (The index can also
be in the form of a primary key or unique constraint.) With such
an index, values in serial columns are guaranteed to be unique
but not contiguous.
SERIAL8 Stores an 8-byte integer value that the database server generates.
(IDS) These values can be in the range -((2**63)-1) to (2**63)-1 (the
values -9,223,372,036,854,775,807 to 9,223,372,036,854,775,807).
If you want to insert an explicit value in a serial column, you can
use any nonzero number. However, you cannot start or reset the
value (begin the sequence) of a serial column with a negative
number.
A serial column is not unique by definition. A unique index must
exist on the column to ensure unique values. (The index can also
be in the form of a primary key or unique constraint.) With such
an index, values in serial columns are guaranteed to be unique
but not contiguous.
SMALLINT Stores a 2-byte integer value. These values can be in the range
-((2**15)-1) to (2**15)-1 (-32,767 to 32,767).
(2 of 2)
DECIMAL
DEC ( precision )
FLOAT
( float_precision )
DOUBLE PRECISION
+ SMALLFLOAT
REAL
Use approximate numeric data types for very large and very small numbers
that can tolerate some degree of rounding during arithmetic operations.
Segments 4-61
Data Type
TEXT
BYTE IN TABLE
blobspace
OP
IDS family_name
CLOB
BLOB
Segments 4-63
Data Type
You can store data for a BYTE or TEXT column with the table or in a separate
blobspace. The following example shows how blobspaces and dbspaces are
specified. The user creates the resume table. The data for the table is stored
in the employ dbspace. The data in the vita column is stored with the table,
but the data associated with the photo column is stored in a blobspace named
photo_space.
CREATE TABLE resume
(
fname CHAR(15),
lname CHAR(15),
phone CHAR(18),
recd_date DATETIME YEAR TO HOUR,
contact_date DATETIME YEAR TO HOUR,
comments VARCHAR(250, 100),
vita TEXT IN TABLE,
photo BYTE IN photo_space
)
IN employ
If you are creating a named row type that includes a BYTE or TEXT column,
you cannot use the IN clause to specify a separate storage space.
For more information, see the entries for these data types in the Informix
Guide to SQL: Reference. For information about the built-in functions you use
to import, export, and copy smart large objects, see “Smart-Large-Object
Functions” on page 4-146 and the Informix Guide to SQL: Tutorial.
DATE
INTERVAL
INTERVAL Field Qualifier
p. 4-223
+
DATETIME
DATETIME Field Qualifier
p. 4-71
Segments 4-65
Data Type
opaque_type
For complete information about how to create an opaque type and its
support functions, see Extending Informix Dynamic Server 2000.
row_type_name
Owner Name
p. 4-257
When you create a complex type, you define the components of the complex
type. However, unlike an opaque type, a complex type is not encapsulated.
You can use SQL to access the individual components of a complex data type.
Dynamic Server supports the following categories of complex data types:
■ Row types
❑ Named row types
❑ Unnamed row types
Segments 4-67
Data Type
ROW ( )
,
field data_type
An unnamed row type is identified by its structure. For the syntax you use to
specify row values for an unnamed row type, see “Expression” on page 4-73.
For the syntax you use to specify collection values for a collection data type,
see “Collection Constructors” on page 4-118.
LIST
Privileges on a collection type are those of the column. You cannot specify
privileges on specific elements of a collection.
Segments 4-69
Data Type
Every element in the collection must be of the same type. For example, if the
element type of a collection type is INTEGER, every element in the collection
must be of type INTEGER.
If the element type of a collection is an unnamed row type, the unnamed row
type cannot contain fields that hold unnamed row types. That is, a collection
cannot contain nested unnamed row types.
When you define a column as a collection type, you must specify that the
elements of the collection cannot be null. That is, you must use the NOT NULL
keywords after you specify the element type.
Related Information
For more information about choosing a data type for your database, see the
Informix Guide to Database Design and Implementation.
For more information about the specific qualities of individual data types, see
the chapter on data types in the Informix Guide to SQL: Reference.
For more information about multi-byte data types, see the discussion of the
NCHAR and NVARCHAR data types and the GLS aspects of other character
data types in the Informix Guide to GLS Functionality.
Syntax
YEAR
MONTH TO YEAR
DAY TO MONTH
HOUR TO DAY
MINUTE TO HOUR
SECOND TO MINUTE
FRACTION TO SECOND
TO FRACTION
(3)
(digit)
Segments 4-71
DATETIME Field Qualifier
Usage
Specify the largest unit for the first DATETIME value; after the word TO,
specify the smallest unit for the value. The keywords imply that the
following values are used in the DATETIME column.
YEAR TO MINUTE
DAY TO FRACTION(4)
MONTH TO MONTH
Related Information
For an explanation of the DATETIME field qualifier, see the discussion of the
DATETIME data type in the Informix Guide to SQL: Reference.
Expression
An expression is one or more pieces of data that is contained in a table or
derived from data in the table. Typically you use expressions to express
values in data manipulation statements. Use the Expression segment
whenever you see a reference to an expression in a syntax diagram.
For an alphabetical listing of the built-in functions in this segment, see “List
of Expressions” on page 4-76.
Segments 4-73
Expression
Syntax
+
-
*
/
||
Cast Expressions
p. 4-88
-
Column Expressions
+ p. 4-91
Conditional Expressions
p. 4-99
Constant Expressions
p. 4-108
Constructor Expressions
p. 4-116
Function Expressions
p. 4-121
Aggregate Expressions
p. 4-185
variable_name
SPL SPL_variable_name
( Expression )
Usage
This segment describes SQL expressions. The following table shows the
different types of SQL expressions as shown in the diagram for “Syntax” on
page 4-74 and states the purpose of each type.
Cast operators Provide the ability to explicit cast from one data type to
another
Column expressions Provide the ability to use full or partial column values in
data manipulation statements
Conditional expressions Provide the ability to return values that depend on the
outcome of conditional tests
Constant expressions Provide the ability to use literal values in data manipu-
lation statements
Segments 4-75
Expression
You can also use host variables or SPL variables as expressions. For a
complete list of SQL expressions, see “List of Expressions” on page 4-76.
List of Expressions
Each category of SQL expression includes many individual expressions. The
following table lists all the SQL expressions in alphabetical order and states
the purpose of each expression. The columns in this table have the following
meanings:
ABS function Returns the absolute value of a given expression p. 4-123 p. 4-125
ACOS function Returns the arc cosine of a numeric expression p. 4-159 p. 4-161
Addition operator (+) Adds two expressions to make a complex p. 4-74 p. 4-85
expression
ASIN function Returns the arc sine of a numeric expression p. 4-159 p. 4-161
ATAN function Returns the arc tangent of a numeric expression p. 4-159 p. 4-161
ATAN2 function Computes the angular component of the polar p. 4-159 p. 4-162
coordinates (r, θ) associated with (x, y)
AVG function Returns the average of all values in the specified p. 4-185 p. 4-194
column or expression
CHAR_LENGTH function Returns the number of logical characters (not p. 4-143 p. 4-145
bytes) in a character column
Column expression Complete or partial column value from a table p. 4-91 p. 4-91
Segments 4-77
Expression
COUNT (as a set of Provides a set of functions for counting column p. 4-185 p. 4-189
functions) values and expressions
You invoke each function by specifying the
appropriate argument after the COUNT
keyword. Each form of the COUNT function
is listed below.
COUNT (column) function Returns the number of non-null values in a p. 4-185 p. 4-190
specified column
COUNT DISTINCT Returns the number of unique non-null values in p. 4-185 p. 4-190
function a specified column
COUNT (*) function Returns the number of rows that satisfy a query. If p. 4-185 p. 4-189
you do not specify a WHERE clause, this function
returns the total number of rows in the table.
DATE function Returns a DATE value that corresponds to the p. 4-152 p. 4-154
non-date expression with which you call it
DAY function Returns an integer that represents the day of the p. 4-152 p. 4-155
month
DBINFO (as a set of Provides a set of functions for retrieving different p. 4-130 p. 4-131
functions) types of database information
You invoke each function by specifying the
appropriate DBINFO option. Each DBINFO
option is listed below.
DBINFO ('coserverid' string Returns the coserver ID of the coserver where p. 4-130 p. 4-139
followed by a column name each row of a specified table is located
qualified by a table name
and the 'currentrow' string)
(XPS)
(2 of 9)
DBINFO ('coserverid' string Returns the coserver ID of the coserver to which p. 4-130 p. 4-139
with no other arguments) the user who entered the query is connected
(XPS)
DBINFO ('dbhostname' Returns the hostname of the database server to p. 4-130 p. 4-136
option) which a client application is connected
DBINFO ('dbspace' string Returns the name of the dbspace where each row p. 4-130 p. 4-140
followed by a column name of a specified table is located
qualified by a table name
and the 'currentrow' string)
(XPS)
DBINFO ('dbspace' string Returns the name of a dbspace corresponding to a p. 4-130 p. 4-133
followed by a tblspace tblspace number
number)
DBINFO ('serial8' option) Returns the last SERIAL8 value inserted in a table p. 4-130 p. 4-138
(IDS)
DBINFO ('sessionid' option) Returns the session ID of the current session p. 4-130 p. 4-135
DBINFO ('sqlca.sqlerrd1' Returns the last serial value inserted in a table p. 4-130 p. 4-133
option)
DBINFO ('sqlca.sqlerrd2' Returns the number of rows processed by selects, p. 4-130 p. 4-134
option) inserts, deletes, updates, EXECUTE
PROCEDURE statements, and EXECUTE
FUNCTION statements
DBINFO ('version' option) Returns the exact version of the database server to p. 4-130 p. 4-136
which a client application is connected
DBSERVERNAME function Returns the name of the database server p. 4-108 p. 4-111
DECODE function Evaluates one or more expression pairs and p. 4-105 p. 4-105
compares the when expression in each pair against
a specified value expression
When the DECODE function finds a match
between the when expression in an expression
pair and the specified value expression, it returns
the value of the then expression in that expression
pair.
(3 of 9)
Segments 4-79
Expression
Division operator (/) Divides one expression by another to make a p. 4-74 p. 4-85
complex expression
Double-colon cast operator Provides the ability to cast an expression to p. 4-88 p. 4-88
(::) (IDS) another data type
FILETOBLOB function Creates a BLOB value for data that is stored in a p. 4-146 p. 4-147
(IDS) specified operating-system file
FILETOCLOB function Creates a CLOB value for data that is stored in a p. 4-146 p. 4-147
(IDS) specified operating-system file
INITCAP function Converts a source expression so that every word p. 4-174 p. 4-177
in the source expression begins with an initial
capital letter and all remaining letters in each
word are lowercase
LIST collection constructor Enables you to specify values for collection p. 4-118 p. 4-118
(IDS) columns
The LIST constructor indicates a collection of
elements with the following qualities:
■ The collection can contain duplicate values.
■ Elements have ordered positions.
Literal collection (as an Provides a constant value in data manipulation p. 4-108 p. 4-115
expression) statements
(IDS)
Literal DATETIME (as an Provides a constant value in data manipulation p. 4-108 p. 4-114
expression) statements
Literal INTERVAL (as an Provides a constant value in data manipulation p. 4-108 p. 4-114
expression) statements
Literal number (as an Provides a constant value in data manipulation p. 4-108 p. 4-110
expression) statements
Literal opaque type (as an Provides a literal representation of an opaque p. 4-108 p. 4-108
expression) data type
(IDS)
Literal row (as an Provides a constant value in data manipulation p. 4-108 p. 4-115
expression) statements
(IDS)
LOCOPY function (IDS) Creates a copy of a smart large object p. 4-146 p. 4-150
LOGN function Returns the natural log of a numeric expression p. 4-141 p. 4-142
LOG10 function Returns the log of a value to the base 10 p. 4-141 p. 4-142
LOTOFILE function (IDS) Copies a smart large object to an operating- p. 4-146 p. 4-149
system file
Segments 4-81
Expression
LPAD function Returns a copy of a source string that is left- p. 4-172 p. 4-172
padded by a specified number of pad characters
MAX function Returns the largest value in the specified column p. 4-185 p. 4-194
or expression
MDY function Returns a DATE value with three expressions that p. 4-152 p. 4-157
evaluate to integers representing the month, day,
and year
MIN function Returns the lowest value in the specified column p. 4-185 p. 4-194
or expression
MOD function Returns the modulus or remainder value for two p. 4-123 p. 4-126
numeric expressions
MONTH function Returns an integer that corresponds to the month p. 4-152 p. 4-155
portion of its DATE or DATETIME argument
Multiplication operator (*) Multiplies two expressions to make a complex p. 4-74 p. 4-85
expression
MULTISET collection Enables you to specify values for collection p. 4-118 p. 4-118
constructor columns
(IDS) The MULTISET constructor indicates a collection
of elements with the following qualities:
■ The collection can contain duplicate values.
■ Elements have no specific order associated with
them.
NVL function Evaluates an expression and returns the value of p. 4-104 p. 4-104
the expression if the value of the expression is not
null
If the value of the expression is null, the NVL
function returns a specified result.
Quoted string (as an Provides a constant value in data manipulation p. 4-108 p. 4-109
expression) statements
RANGE function Computes the range for a sample of a population p. 4-185 p. 4-195
ROOT function Returns the root value of a numeric expression p. 4-123 p. 4-126
ROW constructor Enables you to specify values for columns that are p. 4-116 p. 4-116
(IDS) named row types
SET collection constructor Enables you to specify values for collection p. 4-118 p. 4-118
(IDS) columns
The SET constructor indicates a collection of
elements with the following qualities:
■ The collection must contain unique values.
■ Elements have no specific order associated with
them.
SQRT function Returns the square root of a numeric expression p. 4-123 p. 4-128
Segments 4-83
Expression
STDEV function Computes the standard deviation for a sample of p. 4-185 p. 4-196
a population
Subtraction operator (-) Subtracts one expression from another to make a p. 4-74 p. 4-85
complex expression
SUM function Returns the sum of all values in the specified p. 4-185 p. 4-195
column or expression
TRIM function Removes leading or trailing (or both) pad p. 4-164 p. 4-164
characters from a string
User-defined aggregate An aggregate that you write (as opposed to the p. 4-199 p. 4-199
(IDS) built-in aggregates provided by the database
server)
User-defined function A function that you write (as opposed to the p. 4-179 p. 4-179
built-in functions provided by the database
server)
USER function Returns a string that contains the login name of p. 4-108 p. 4-110
the current user
(8 of 9)
VARIANCE function Returns the variance for a sample of values as an p. 4-185 p. 4-196
unbiased estimate of the variance of a population
WEEKDAY function Returns an integer that represents the day of the p. 4-152 p. 4-155
week
YEAR function Returns a four-digit integer that represents the p. 4-152 p. 4-156
year
The following sections describe the syntax and usage of each expression that
appears in the preceding table.
Addition + plus()
Subtraction - minus()
Multiplication * times()
Division / divide()
Segments 4-85
Expression
price * 2
COUNT(*) + 2
If you combine a DATETIME value with one or more INTERVAL values, all the
fields of the INTERVAL value must be present in the DATETIME value; no
implicit EXTEND function is performed. In addition, you cannot use YEAR to
MONTH intervals with DAY to SECOND intervals.
You cannot combine expressions that use aggregate functions with column
expressions.
The database server provides the operator functions associated with the
relational operators for all built-in data types.You can define new versions of
these binary arithmetic operator functions to handle your own user-defined
data types. For more information, see Extending Informix Dynamic Server 2000.
Positive + positive()
Negative - negate()
The unary arithmetic operators have the associated operator functions that
the preceding table shows. You can define new versions of these arithmetic
operator functions to handle your own user-defined data types. For more
information on how to write versions of operator functions, see Extending
Informix Dynamic Server 2000.
lname[1,3] || zipcode
:file_variable || '.dbg'
'Date:' || TODAY
Segments 4-87
Expression
You can use the concatenation operator in the SELECT, INSERT, EXECUTE
FUNCTION (or EXECUTE PROCEDURE) statement in the DECLARE statement.
You can use the concatenation operator in the SQL statement or statements in
the PREPARE statement. ♦
:: target_data_type
Expression :: target_data_type
p. 4-73
You can use the CAST AS keywords or the double-colon cast operator (::) to
cast an expression to another data type. Both the operator and the keywords
invoke a cast from the data type of the expression to the target data type. To
invoke an explicit cast you must use either the cast operator or the CAST AS
keywords. If you use the cast operator or CAST AS keywords, but no explicit
or implicit cast was defined to perform the conversion between two data
types, the statement returns an error.
Segments 4-89
Expression
The following examples show two different ways of finding the integer
equivalent of the expression expr. Both require the existence of an implicit or
explicit cast from the data type of expr to the INTEGER data type.
CAST expr AS INTEGER
expr::INTEGER
In the following example, the user casts a BYTE column to the BLOB type and
copies the BLOB data to an operating-system file:
SELECT LOTOFILE(mybytecol::blob, 'fname', 'client')
FROM mytab
WHERE pkey = 12345
In the following example, the user casts a TEXT column to a CLOB value and
then updates a CLOB column in the same table to have the CLOB value
derived from the TEXT column:
UPDATE newtab SET myclobcol = mytextcol::clob
Column Expressions
The possible syntax for column expressions is shown in the following
diagram.
column
+
table .
view . [first , last ]
+
synonym . ROWID
IDS
alias .
IDS row_column
.*
3 . field_name
IDS row_col_expr
.*
3 . field_name
Segments 4-91
Expression
items.price
cat_advert [1,15]
You can also use dot notation to directly access the fields of a row column, as
follows:
row-column name.field name
This use of dot notation is called a field projection. For example, suppose you
have a column called rect with the following definition:
CREATE TABLE rectangles
(
area float,
rect ROW(x int, y int, length float, width float)
)
Segments 4-93
Expression
The following SELECT statement uses dot notation to access field length of
the rect column:
SELECT rect.length FROM rectangles
WHERE area = 64
You can also use asterisk notation to project all the fields of a column that has
a row type. For example, if you want to use asterisk notation to select all
fields of the rect column, you can enter the following statement:
SELECT rect.* FROM rectangles
WHERE area = 64
Asterisk notation is a shorthand form of dot notation that is easier than speci-
fying each field of the rect column individually:
SELECT rect.x, rect.y, rect.length,
rect.width
FROM rectangles
WHERE area = 64
Asterisk notation is not necessary with row-type columns because you can
specify just the column name itself to project all of its fields. However,
asterisk notation is quite helpful with row-type expressions such as
subqueries and user-defined functions that return row-type values. For
further information see “Using Dot Notation with Row-Type Expressions”
on page 4-96.
You can use asterisk notation with columns and expressions of row type in
the select list of a SELECT statement only. You cannot use asterisk notation
with columns and expressions of row type in any other clause of a SELECT
statement.
Rules of Precedence
The database server uses the following precedence rules to interpret dot
notation:
For more information about precedence rules and how to use dot notation
with row columns, see the Informix Guide to SQL: Tutorial.
Segments 4-95
Expression
Also assume that you have created a typed table named tab1 that is based on
the row_t row type:
CREATE TABLE tab1 OF TYPE row_t
Assume also that you have inserted the following values into table tab1:
INSERT INTO tab1 VALUES (ROW(1,7));
INSERT INTO tab1 VALUES (ROW(2,10));
Finally, assume that you have created another table named tab2:
CREATE TABLE tab2 (colx INT)
Now you can use dot notation to insert the value from just the part_id
column of table tab1 into the tab2 table:
INSERT INTO tab2
VALUES ((SELECT t FROM tab1 t
WHERE part_id = 1).part_id)
The asterisk form of dot notation is not necessary when you want to select all
fields of a row type column because you can just specify the column name
itself to select all of its fields. However, the asterisk form of dot notation can
be quite helpful when you use a subquery as in the preceding example or
when you call a user-defined function to return row type values.
lname[6,9]
GLS For information on the GLS aspects of column subscripts and substrings, see
the Informix Guide to GLS Functionality. ♦
Segments 4-97
Expression
The last SELECT statement example shows how to get the page number (the
first six digits after 0x) and the slot number (the last two digits) of the location
of your row.
You cannot use the ROWID keyword in the select list of a query that contains
an aggregate function.
To access the data of a smart-large-object column, you must use one of the
following application programming interfaces (APIs):
When you select a smart-large-object column, you can assign the handle
value to any number of columns: all columns with the same handle value
share the CLOB or BLOB value across several columns. This storage
arrangement reduces the amount of disk space that the CLOB or BLOB data
takes. However, when several columns share the same smart-large-object
value, the following conditions result:
To remove these constraints, you can create separate copies of the BLOB or
CLOB data for each column that needs to access it. You can use the LOCOPY
function to create a copy of an existing smart large object. You can also use
the built-in functions LOTOFILE, FILETOCLOB, and FILETOBLOB to access
smart-large-object values. For more information on these functions, see
“Smart-Large-Object Functions” on page 4-146. For more information on the
BLOB and CLOB data types, see the Informix Guide to SQL: Reference.
Conditional Expressions
Conditional expressions return values that depend on the outcome of condi-
tional tests. The following diagram shows the syntax for Conditional
Expressions.
CASE Expressions
p. 4-100
NVL Function
p. 4-104
DECODE Function
p. 4-105
Segments 4-99
Expression
CASE Expressions
The CASE expression allows an SQL statement such as the SELECT statement
to return one of several possible results, depending on which of several
condition tests evaluates to true. The CASE expression has two forms as the
following diagram shows: generic CASE expressions and linear CASE
expressions.
The expressions in the search condition or the result value expression can
contain subqueries.
You can nest a CASE expression in another CASE expression.
NULL
The database server processes the WHEN clauses in the order that they
appear in the statement. As soon as the database server finds a WHEN clause
whose search condition evaluates to true, it takes the corresponding result
value expression as the overall result of the CASE expression, and it stops
processing the CASE expression.
If no WHEN condition evaluates to true, the database server takes the result
of the ELSE clause as the overall result. If no WHEN condition evaluates to
true, and no ELSE clause was specified, the resulting value is null. You can use
the IS NULL condition to handle null results. For information on how to
handle null values, see “IS NULL Condition” on page 4-36.
Segments 4-101
Expression
The following example shows the use of a generic CASE expression in the
select list of a SELECT statement. In this example the user retrieves the name
and address of each customer as well as a calculated number that is based on
the number of problems that exist for that customer.
SELECT cust_name,
CASE
WHEN number_of_problems = 0
THEN 100
WHEN number_of_problems > 0 AND number_of_problems < 4
THEN number_of_problems * 500
WHEN number_of_problems >= 4 and number_of_problems <= 9
THEN number_of_problems * 400
ELSE
(number_of_problems * 300) + 250
END,
cust_address
FROM custtab
In a generic CASE expression, all the results should be of the same type, or
they should evaluate to a common compatible type. If the results in all the
WHEN clauses are not of the same type, or if they do not evaluate to values of
mutually compatible types, an error occurs.
NULL
First the database server evaluates the value expression that follows the CASE
keyword. Then the database server processes the WHEN clauses in the order
that they appear in the CASE expression. As soon as the database server finds
a WHEN clause where the value expression after the WHEN keyword
evaluates to the same value as the value expression that follows the CASE
keyword, it takes the value expression that follows the THEN keyword as the
overall result of the CASE expression. Then the database server stops
processing the CASE expression.
If none of the value expressions that follow the WHEN keywords evaluates to
the same value as the value expression that follows the CASE keyword, the
database server takes the result value expression of the ELSE clause as the
overall result of the CASE expression. If all of the value expressions that
follow the WHEN keyword in all the WHEN clauses do not evaluate to the
same value as the value expression that follows the CASE keyword, and the
user did not specify an ELSE clause, the resulting value is null.
Segments 4-103
Expression
The following example shows a linear CASE expression in the select list of a
SELECT statement. For each movie in a table of movie titles, the SELECT
statement displays the title of the movie, the cost of the movie, and the type
of movie. The statement uses a CASE expression to derive the type of each
movie.
SELECT title,
CASE movie_type
WHEN 1 THEN 'HORROR'
WHEN 2 THEN 'COMEDY'
WHEN 3 THEN 'ROMANCE'
WHEN 4 THEN 'WESTERN'
ELSE 'UNCLASSIFIED'
END,
our_cost
FROM movie_titles
In linear CASE expressions, the types of value expressions in all the WHEN
clauses have to be compatible with the type of the value expression that
follows the CASE keyword.
NVL Function
The NVL expression returns different results depending on whether its first
argument evaluates to null.
NVL evaluates expression1. If expression1 is not null, NVL returns the value of
expression1. If expression1 is null, NVL returns the value of expression2. The
expressions expression1 and expression2 can be of any data type, as long as
they evaluate to a common compatible type.
Suppose that the addr column of the employees table has null values in some
rows, and the user wants to be able to print the label Address unknown for
these rows. The user enters the following SELECT statement to display the
label Address unknown when the addr column has a null value.
SELECT fname, NVL (addr, 'Address unknown') AS address
FROM employees
DECODE Function
The DECODE expression is similar to the CASE expression in that it can print
different results depending on the values found in a specified column.
NULL
Segments 4-105
Expression
The expressions when_expr and then_expr are an expression pair, and you can
specify any number of expression pairs in the DECODE function. In all cases,
DECODE compares the first member of the pair against expr and returns the
second member of the pair if the first member matches expr.
You can specify any data type as input, but two limitations exist.
■ All occurrences of the parameter when_expr must have the same data
type, or they must evaluate to a common compatible type. Similarly,
all occurrences of when_expr must have the same data type as expr, or
they must evaluate to a common compatible type.
■ All occurrences of the parameter then_expr must have the same data
type, or they must evaluate to a common compatible type. Similarly,
all occurrences of then_expr must have the same data type as
else_expr, or they must evaluate to a common compatible type.
firstname evaluation
Edward Great
Mary Good
Jim Poor
The user now enters a SELECT statement with the DECODE function to
convert the descriptive values in the evaluation column to numeric
equivalents.
SELECT firstname, DECODE(evaluation,
'Poor', 0,
'Fair', 25,
'Good', 50,
'Very Good', 75,
'Great', 100,
-1) as grade
FROM students
firstname grade
Edward 100
Joe -1
Mary 50
Jim 0
Segments 4-107
Expression
Constant Expressions
The following diagram shows the possible syntax for constant expressions.
Quoted String
p. 4-260
Literal Number
p. 4-237
USER
+
SITENAME
DBSERVERNAME
TODAY
Literal DATETIME
p. 4-231
Literal INTERVAL
p. 4-234
Literal Row
p. 4-239
literal BOOLEAN
Segments 4-109
Expression
USER Function
The USER function returns a string that contains the login name of the current
user (that is, the person running the process).
The following statements show how you might use the USER function:
INSERT INTO cust_calls VALUES
(221,CURRENT,USER,'B','Decimal point off', NULL, NULL)
The USER function does not change the case of a user ID. If you use USER in
an expression and the present user is Robertm, the USER function returns
Robertm, not robertm.
If you specify USER as the default value for a column, the column must have
a CHAR, VARCHAR, NCHAR, or NVARCHAR data type.
IDS If you specify USER as the default value for a column, Informix recommends
that the size of the column be at least 32 bytes long. You risk getting an error
message during INSERT and ALTER TABLE operations if the length of the
column is too small to store the default value. ♦
XPS If you specify USER as the default value for a column, Informix recommends
that the size of the column be at least 8 bytes long. You risk getting an error
message during INSERT and ALTER TABLE operations if the length of the
column is too small to store the default value. ♦
ANSI In an ANSI-compliant database, if you do not use quotes around the owner
name, the name of the table owner is stored as uppercase letters. If you use
the USER keyword as part of a condition, you must be sure that the way the
user name is stored agrees with the values that the USER function returns,
with respect to case. ♦
IDS If you specify DBSERVERNAME as the default value for a column, Informix
recommends that the size of the column be at least 128 bytes long. You risk
getting an error message during INSERT and ALTER TABLE operations if the
length of the column is too small to store the default value. ♦
XPS If you specify DBSERVERNAME as the default value for a column, Informix
recommends that the size of the column be at least 18 bytes long. You risk
getting an error message during INSERT and ALTER TABLE operations if the
length of the column is too small to store the default value. ♦
Segments 4-111
Expression
In the following example, the first statement returns the name of the database
server where the customer table resides. Because the query is not restricted
with a WHERE clause, it returns DBSERVERNAME for every row in the table.
If you add the DISTINCT keyword to the SELECT clause, the query returns
DBSERVERNAME once. The second statement adds a row that contains the
current site name to a table. The third statement returns all the rows that have
the site name of the current system in site_col. The last statement changes the
company name in the customer table to the current system name.
SELECT DBSERVERNAME FROM customer
TODAY Function
Use the TODAY function to return the system date as a DATE data type. If you
specify TODAY as a default value for a column, it must be a DATE column.
The following examples show how you might use the TODAY function in an
INSERT, UPDATE, or SELECT statement:
CURRENT Function
The CURRENT function returns a DATETIME value with the date and time of
day, showing the current instant.
You can use the CURRENT function in any context in which you can use a
literal DATETIME (see “Literal DATETIME” on page 4-231). If you specify
CURRENT as the default value for a column, it must be a DATETIME column
and the qualifier of CURRENT must match the column qualifier, as the
following example shows:
CREATE TABLE new_acct (col1 int, col2 DATETIME YEAR TO DAY
DEFAULT CURRENT YEAR TO DAY)
If you use the CURRENT keyword in more than one place in a single
statement, identical values can be returned at each point of the call. You
cannot rely on the CURRENT function to provide distinct values each time it
executes.
The returned value comes from the system clock and is fixed when any SQL
statement starts. For example, any call to CURRENT from inside the SPL
function that an EXECUTE FUNCTION (or EXECUTE PROCEDURE) statement
names returns the value when the SPL function starts.
The CURRENT function is always evaluated in the database server where the
current database is located. If the current database is in a remote database
server, the returned value is from the remote host.
The CURRENT function might not execute in the physical order in which it
appears in a statement. You should not use the CURRENT function to mark
the start, end, or a specific point in the execution of a statement.
If your platform does not provide a system call that returns the current time
with subsecond precision, the CURRENT function returns a zero for the
FRACTION field.
In the following example, the first statement uses the CURRENT function in
a WHERE condition. The second statement uses the CURRENT function as the
input for the DAY function. The last query selects rows whose call_dtime
value is within a range from the beginning of 1997 to the current instant.
DELETE FROM cust_calls WHERE
res_dtime < CURRENT YEAR TO MINUTE
Segments 4-113
Expression
The second statement in the preceding example adds five days to each value
of lead_time selected from the manufact table.
UNITS Keyword
The UNITS keyword enables you to display a simple interval or increase or
decrease a specific interval or datetime value.
In the following example, the first SELECT statement uses the UNITS keyword
to select all the manufacturer lead times, increased by five days. The second
SELECT statement finds all the calls that were placed more than 30 days ago.
If the expression in the WHERE clause returns a value greater than 99
(maximum number of days), the query fails. The last statement increases the
lead time for the ANZA manufacturer by two days.
For more information, see “Literal Collection” on page 4-227. For syntax that
allows you to use expressions that evaluate to element values, see “Collection
Constructors” on page 4-118.
UPDATE rectangles
SET rect = ROW(8, 3, 7, 20)
WHERE area = 140
For more information, see “Literal Row” on page 4-239. For syntax that
allows you to use expressions that evaluate to field values, see “ROW
Constructors” on page 4-116.
Segments 4-115
Expression
ROW ( Expression )
p. 4-73
Collection Constructors
p. 4-118
ROW Constructors
You use ROW constructors to generate values for row-type columns. Suppose
you create the following named row type and a table that contains the named
row type row_t and an unnamed row type:
CREATE ROW TYPE row_t ( x INT, y INT);
CREATE TABLE new_tab
(
col1 row_t,
col2 ROW( a CHAR(2), b INT
)
When you define a column as a named row type or unnamed row type, you
must use a ROW constructor to generate values for the row column. To create
a value for either a named row type or unnamed row type, you must
complete the following steps:
■ Begin the expression with the ROW keyword.
■ Specify a value for each field of the row type.
■ Enclosed the field values within parentheses.
The format of the value for each field must be compatible with the data type
of the row field to which it is assigned.
You can use any kind of expression as a value with a ROW constructor,
including literals, functions, and variables. The following examples show the
use of different types of expressions with ROW constructors to specify values:
ROW(5, 6.77, 'HMO')
ROW(col1.lname, 45000)
ROW(USER, SITENAME)
The following statement uses literal numbers and quoted strings with ROW
constructors to insert values into col1 and col2 of the new_tab table:
INSERT INTO new_tab
VALUES
(
ROW(32, 65)::row_t,
ROW('CA', 34)
)
When you use a ROW constructor to generate values for a named row type,
you must explicitly cast the row value to the appropriate named row type.
The cast is necessary to generate a value of the named row type. To cast the
row value as a named row type, you can use the cast operator (::) or the CAST
AS keywords, as shown in the following examples:
ROW(4,5)::row_t
CAST (ROW(3,4) AS row_t)
You can use a ROW constructor to generate row type values not only in
INSERT and UPDATE statements but also in SELECT statements. In the
following example, the WHERE clause of a SELECT statement specifies a row
type value that is cast as type person_t
SELECT *
FROM person_tab
WHERE col1 = ROW('charlie','hunter')::person_t
Segments 4-117
Expression
Collection Constructors
Use a collection constructor to specify values for a collection column.
SET { }
,
MULTISET
LIST Expression
p. 4-73
You can use collection constructors in the WHERE clause of the SELECT
statement and the VALUES clause of the INSERT statement. You can also pass
collection constructors to UDRs.
The following table differentiates the types of collections that you can
construct.
Keyword Purpose
You can use any kind of expression with a collection constructor, including
literals, functions, and variables. When you use a collection constructor with
a list of arbitrary expressions, the database server evaluates each expression
to its equivalent literal form and uses the literal values to construct the
collection.
The element type of the collection can be any built-in or extended data type.
The element type of each expression must be homogeneous, that is, they
must be exactly the same type. This can be accomplished by casting the entire
collection constructor expression to a collection type, or by casting individual
element expressions to the same type.
If the database server cannot determine the collection type and the element
types are not homogeneous, then the collection constructor will return an
error. In the case of host variables, this determination is made at bind time
when the client informs the database server the element type of the host
variable.
Segments 4-119
Expression
For information about a more restrictive, but still-supported syntax for how
to specify values for a collection column, see “Literal Collection” on
page 4-227.
Function Expressions
A function expression can call built-in functions or user-defined functions, as
the following diagram shows.
+ Algebraic Functions
p. 4-123
CARDINALITY Function
p. 4-129
DBINFO Function
p. 4-130
HEX Function
p. 4-142
Length Functions
p. 4-143
IFX_REPLACE_MODULE Function
p. 4-145
Smart-Large-Object Functions
p. 4-146
Time Functions
p. 4-152
Trigonometric Functions
p. 4-159
String-Manipulation Functions
p. 4-163
IFX_ALLOW_NEWLINE Function
p. 4-177
User-Defined Functions
p. 4-179
Segments 4-121
Expression
DATE (365/2)
HEX (customer_num)
HEX (LENGTH(123))
TAN (radians)
ABS (-32)
EXP (3)
MOD (10,3)
Algebraic Functions
An algebraic function takes one or more arguments, as the following diagram
shows.
ABS ( num_expression )
MOD ( dividend, divisor )
ROOT ( radicand )
, index
,2
ROUND ( Expression )
p. 4-73
, rounding_factor
,0
SQRT ( sqrt_radicand )
TRUNC ( Expression )
p. 4-73
, truncate_factor
,0
Segments 4-123
Expression
ABS Function
The ABS function gives the absolute value for a given expression. The
function requires a single numeric argument. The value returned is the same
as the argument type. The following example shows all orders of more than
$20 paid in cash (+) or store credit (-). The stores_demo database does not
contain any negative balances; however, you might have negative balances in
your application.
SELECT order_num, customer_num, ship_charge
FROM orders WHERE ABS(ship_charge) > 20
Segments 4-125
Expression
MOD Function
The MOD function returns the modulus or remainder value for two numeric
expressions. You provide integer expressions for the dividend and divisor.
The divisor cannot be 0. The value returned is INT8. The following example
uses a 30-day billing cycle to determine how far into the billing cycle today is:
SELECT MOD(today - MDY(1,1,year(today)),30) FROM orders
POW Function
The POW function raises the base to the exponent. This function requires two
numeric arguments. The return type is FLOAT. The following example
returns all the information for circles whose areas (π r2) are less than
1,000 square units:
SELECT * FROM circles WHERE (3.1416 * POW(radius,2)) < 1000
If you want to use e, the base of natural logarithms, as the base, see the “EXP
Function” on page 4-141.
ROOT Function
The ROOT function returns the root value of a numeric expression. This
function requires at least one numeric argument (the radicand argument) and
allows no more than two (the radicand and index arguments). If only the
radicand argument is supplied, the value 2 is used as a default value for the
index argument. The value 0 cannot be used as the value of index. The value
that the ROOT function returns is FLOAT. The first SELECT statement in the
following example takes the square root of the expression. The second
SELECT statement takes the cube root of the expression.
ROUND Function
The ROUND function returns the rounded value of an expression. The
expression must be numeric or must be converted to numeric.
If you omit the digit indication, the value is rounded to zero digits or to the
ones place. The digit limitation of 32 (+ and -) refers to the entire decimal
value.
Expression: 24536.8746
The following example shows how you can use the ROUND function with a
column expression in a SELECT statement. This statement displays the order
number and rounded total price (to zero places) of items whose rounded total
price (to zero places) is equal to 124.00.
SELECT order_num , ROUND(total_price) FROM items
WHERE ROUND(total_price) = 124.00
If you use a MONEY data type as the argument for the ROUND function and
you round to zero places, the value displays with .00. The SELECT statement
in the following example rounds an INTEGER value and a MONEY value. It
displays 125 and a rounded price in the form xxx.00 for each row in items.
SELECT ROUND(125.46), ROUND(total_price) FROM items
Segments 4-127
Expression
SQRT Function
The SQRT function returns the square root of a numeric expression.
The following example returns the square root of 9 for each row of the angles
table:
SELECT SQRT(9) FROM angles
TRUNC Function
The TRUNC function returns the truncated value of a numeric expression.
Positive digit values indicate truncating to the right of the decimal point;
negative digit values indicate truncating to the left of the decimal point, as
Figure 4-2 shows.
Figure 4-2
TRUNC Function
Expression: 24536.8746
If you use a MONEY data type as the argument for the TRUNC function and
you truncate to zero places, the .00 places are removed. For example, the
following SELECT statement truncates a MONEY value and an INTEGER
value. It displays 125 and a truncated price in integer format for each row in
items.
SELECT TRUNC(125.46), TRUNC(total_price) FROM items
CARDINALITY ( collection_col )
collection_var
Suppose that the set_col SET column contains the following value:
{3, 7, 9, 16, 0}
Segments 4-129
Expression
DBINFO Function
The following diagram shows the syntax of the DBINFO function.
DBINFO Options
The DBINFO function is actually a set of functions that return different types
of information about the database. You invoke each function by specifying a
particular option after the DBINFO keyword. You can use any DBINFO
option anywhere within SQL statements and within UDRs.
Segments 4-131
Expression
The following table shows the different types of database information that
you can retrieve with the DBINFO options. The Option column shows the
name of each DBINFO option. The Purpose column shows the type of
database information that the option retrieves. The next three columns give
the names of the database servers on which each option is supported. A
check mark in these columns shows that the given database server supports
the given option. The Page column shows the page where you can find more
information about a given option.
'coserverid' table.column 'currentrow' Returns the coserver ID of the coserver where each 4-139
(XPS) row of a specified table is located
'dbspace' table.column 'currentrow' Returns the name of the dbspace where each row of 4-140
(XPS) a specified table is located
If the statement returns a partition number of 1048892, you insert that value
into the second argument to find which dbspace contains the customer table,
as shown in the following example:
SELECT DBINFO ('dbspace', 1048892) FROM systables
where tabname = 'customer'
If the table for which you want to know the dbspace name is fragmented, you
must query the sysfragments system catalog table to find out the tblspace
number of each table fragment. Then you must supply each tblspace number
in a separate DBINFO query to find out all the dbspaces across which a table
is fragmented.
Tip: To obtain the value of the last SERIAL8 value that is inserted into a table, use the
'serial8' option of DBINFO. For more information, see “Using the 'serial8' Option”
on page 4-138.
Segments 4-133
Expression
This example inserts a row that contains a primary-key serial value into the
fst_tab table, and then uses the DBINFO function to insert the same serial
value into the sec_tab table. The value that the DBINFO function returns is
the serial value of the last row that is inserted into fst_tab.
The following example shows an SPL routine that uses the 'sqlca.sqlerrd2'
option to determine the number of rows that are deleted from a table:
CREATE FUNCTION del_rows (pnumb int)
RETURNING int;
END FUNCTION
When you specify the 'sessionid' option, the database server retrieves the
session ID of your current session from the session control block and returns
this value to you as an integer. Some of the System-Monitoring Interface
(SMI) tables in the sysmaster database include a column for session IDs, so
you can use the session ID that the DBINFO function obtained to extract infor-
mation about your own session from these SMI tables. For further
information on the session control block, see the Administrator’s Guide. For
further information on the sysmaster database and the SMI tables, see the
Administrator’s Reference.
In the following example, the user specifies the DBINFO function in a SELECT
statement to obtain the value of the current session ID. The user poses this
query against the systables system catalog table and uses a WHERE clause to
limit the query result to a single row.
SELECT DBINFO('sessionid') AS my_sessionid
FROM systables
WHERE tabname = 'systables'
In the preceding example, the SELECT statement queries against the systables
system catalog table. However, you can obtain the session ID of the current
session by querying against any system catalog table or user table in the
database. For example, you can enter the following query to obtain the
session ID of your current session:
SELECT DBINFO('sessionid') AS user_sessionid
FROM customer
where customer_num = 101
Segments 4-135
Expression
You can use the DBINFO 'sessionid' option not only in SQL statements but
also in SPL routines. The following example shows an SPL function that
returns the value of the current session ID to the calling program or routine:
CREATE FUNCTION get_sess()
RETURNING INT;
RETURN DBINFO('sessionid');
END FUNCTION;
In the following example, the user enters the 'dbhostname' option of DBINFO
in a SELECT statement to retrieve the hostname of the database server to
which DB-Access is connected:
SELECT DBINFO('dbhostname')
FROM systables
WHERE tabid = 1
(constant)
rd_lab1
You use the specifier parameter of the 'version' option to specify which part of
the version string you want to retrieve. The following table lists the values
you can enter in the specifier parameter, shows which part of the version
string is returned for each specifier value, and gives an example of what is
returned by each value of specifier. Each example returns part of the complete
version string Dynamic Server Version 9.20.UC1.
'os' Operating-system U
identifier within the
version string:
T = Windows NT
U = UNIX 32 bit running on
a 32-bit operating system
H = UNIX 32 bit running on
a 64-bit operating system
F = UNIX 64 bit running on
a 64-bit operating system
The following example shows how to use the 'version' option of DBINFO in
a SELECT statement to retrieve the major version number of the database
server that the DB-Access client is connected to.
SELECT DBINFO('version', 'major')
FROM systables
WHERE tabid = 1
Segments 4-137
Expression
(constant)
Tip: To obtain the value of the last SERIAL value that is inserted into a table, use the
'sqlca.sqlerrd1' option of DBINFO(). For more information, see “Using the
'sqlca.sqlerrd1' Option” on page 4-133.
This example inserts a row that contains a primary-key SERIAL8 value into
the fst_tab table, and then uses the DBINFO function to insert the same
SERIAL8 value into the sec_tab table. The value that the DBINFO function
returns is the SERIAL8 value of the last row that is inserted into fst_tab. The
subquery in the last line contains a WHERE clause so that a single value is
returned.
Suppose that you use the following statement to create the mytab table:
CREATE TABLE mytab (mycol INT)
FRAGMENT BY EXPRESSION
mycol < 5 in rootdbs.1
mycol > 5 in rootdbs.2
Also suppose that the dbspace named rootdbs.1 resides on coserver 1, and
the dbspace named rootdbs.2 resides on coserver 2.
Also suppose that you use the following statements to insert rows into the
mytab table:
INSERT INTO mytab VALUES ('1');
INSERT INTO mytab VALUES ('6');
Finally, suppose that you are logged on to coserver 1 when you make the
following query. This query displays the values of all columns in the row
where the value of the mycol column is 1. This query also displays the
coserver ID of the coserver to which you are logged on when you enter the
query.
SELECT *, DBINFO ('coserverid') AS cid
FROM mytab
WHERE mycol = 1
mycol cid
1 1
XPS Using the 'coserverid' Option Followed by Table and Column Names
Use the 'coserverid' option followed by the table name and column name and
the 'currentrow' string to find out the coserver ID where each row in a
specified table is located. This option is especially useful when you fragment
a table across multiple coservers.
Segments 4-139
Expression
In the following example, the user asks to see all columns and rows of the
mytab table as well as the coserver ID of the coserver where each row resides.
For a description of the mytab table, see “Using the 'coserverid' Option with
No Other Arguments” on page 4-139.
SELECT *, DBINFO ('coserverid', mytab.mycol, 'currentrow')
AS cid
FROM mytab
mycol cid
1 1
6 2
The column that you specify in the DBINFO function can be any column in
the specified table.
XPS Using the 'dbspace' Option Followed by Table and Column Names
Use the 'dbspace ' option followed by the table name and column name and
the 'currentrow' string to find out the name of the dbspace where each row
in a specified table is located. This option is especially useful when you
fragment a table across multiple dbspaces.
In the following example, the user asks to see all columns and rows of the
mytab table as well as the name of the dbspace where each row resides. For
a description of the mytab table, see “Using the 'coserverid' Option with No
Other Arguments” on page 4-139.
SELECT *, DBINFO ('dbspace', mytab.mycol, 'currentrow')
AS dbsp
FROM mytab
mycol dbspace
1 rootdbs.1
6 rootdbs.2
The column that you specify in the DBINFO function can be any column in
the specified table.
EXP ( float_expression )
LOGN ( float_expression )
LOG10 ( float_expression )
EXP Function
The EXP function returns the exponent of a numeric expression. The
following example returns the exponent of 3 for each row of the angles table:
SELECT EXP(3) FROM angles
For this function, the base is always e, the base of natural logarithms, as the
following example shows.
e=exp(1)=2.718281828459
Segments 4-141
Expression
When you want to use the base of natural logarithms as the base value, use
the EXP function. If you want to specify a particular value to raise to a specific
power, see the “POW Function” on page 4-126.
LOGN Function
The LOGN function returns the natural log of a numeric expression. The
logarithmic value is the inverse of the exponential value. The following
SELECT statement returns the natural log of population for each row of the
history table:
SELECT LOGN(population) FROM history WHERE country='US'
ORDER BY date
LOG10 Function
The LOG10 function returns the log of a value to base 10. The following
example returns the log base 10 of distance for each row of the travel table:
SELECT LOG10(distance) + 1 digits FROM travel
HEX Function
The HEX function returns the hexadecimal encoding of an integer expression.
HEX ( int_expression )
The following example displays the data type and column length of the
columns of the orders table in hexadecimal format. For MONEY and
DECIMAL columns, you can then determine the precision and scale from the
lowest and next-to-the-lowest bytes. For VARCHAR and NVARCHAR
columns, you can determine the minimum space and maximum space from
the lowest and next to the lowest bytes. For more information about encoded
information, see the Informix Guide to SQL: Reference.
SELECT colname, coltype, HEX(collength)
FROM syscolumns C, systables T
WHERE C.tabid = T.tabid AND T.tabname = 'orders'
The following example lists the names of all the tables in the current database
and their corresponding tblspace number in hexadecimal format. This
example is particularly useful because the two most significant bytes in the
hexadecimal number constitute the dbspace number. They identify the table
in oncheck output (in Dynamic Server) and in onutilcheck output (in
Extended Parallel Server).
SELECT tabname, HEX(partnum) FROM systables
Length Functions
You can use length functions to determine the length of a column, string, or
variable.
Quoted String
+ LENGTH ( p. 4-260 )
CHAR_LENGTH
E/C
CHARACTER_LENGTH variable_name
SPL
OCTET_LENGTH column
table.
Segments 4-143
Expression
■ LENGTH
■ OCTET_LENGTH
■ CHAR_LENGTH (also known as CHARACTER_LENGTH)
E/C In ESQL/C, you can use the LENGTH function to return the length of a
character variable. ♦
GLS For information on GLS aspects of the LENGTH function, see the Informix
Guide to GLS Functionality. ♦
IDS
IDS IFX_REPLACE_MODULE Function
C The IFX_REPLACE_MODULE function replaces a loaded shared library with
a new version that has a different name or location.
Segments 4-145
Expression
UNIX For example, to replace the circle.so shared library that resides in the
/usr/apps/opaque_types directory with one that resides in the
/usr/apps/shared_libs directory, you can use the following EXECUTE
FUNCTION statement to execute the IFX_REPLACE_MODULE function:
EXECUTE FUNCTION
ifx_replace_module("/usr/apps/opaque_types/circle.so",
"/usr/apps/shared_libs/circle.so", "c") ♦
WIN NT For example, to replace the circle.so shared library that resides in the
C:\usr\apps\opaque_types directory with one that resides in the
C:\usr\apps\shared_libs directory, you can use the following EXECUTE
FUNCTION statement to execute the IFX_REPLACE_MODULE function:
EXECUTE FUNCTION
ifx_replace_module("C:\usr\apps\opaque_types\circle.so",
"C:\usr\apps\shared_libs\circle.so", "c") ♦
, table , column
LOCOPY ( BLOB_column )
CLOB_column , table , column
■ The pathname parameter identifies the directory path and name of the
source file.
■ The file destination parameter identifies the computer, client or server,
on which this file resides:
❑ Set file destination to client to identify the client computer as the
location of the source file. The pathname can be either a full
pathname or relative to the current directory.
❑ Set file destination to server to identify the server computer as
the location of the source file. The pathname must be a full
pathname.
Segments 4-147
Expression
The FILETOBLOB function returns a handle value (a pointer) to the new BLOB
value. Similarly, the FILETOCLOB function returns a handle value to the new
CLOB value. Neither of these functions actually stores the smart-large-object
value into a column in the database. You must assign the BLOB or CLOB value
to the appropriate column.
GLS The FILETOCLOB function performs any code-set conversion that might be
required when it copies the file from the client or server computer to the
database. ♦
In the preceding example, the FILETOCLOB function reads the haven.rsm file
in the current directory on the client computer and returns a handle value to
a CLOB value that contains the data in this file. Because the FILETOCLOB
function does not specify a table and column name, this new CLOB value has
the system-specified storage characteristics. The INSERT statement then
assigns this CLOB value to the resume column in the candidate table.
LOTOFILE Function
The LOTOFILE function copies a smart large object to an operating-system
file. The first parameter specifies the BLOB or CLOB column to copy. The
function determines the operating-system file to create from the following
parameters:
■ The pathname parameter identifies the directory path and name of the
source file.
■ The file destination parameter identifies the computer, client or server,
on which this file resides:
❑ Set file destination to client to identify the client computer as the
location of the source file. The pathname can be either a full
pathname or relative to the current directory.
❑ Set file destination to server to identify the server computer as
the location of the source file. The pathname must be a full
pathname.
In this format, file is the filename you specify in pathname and hex_id is the
unique hexadecimal smart-large-object identifier. The maximum number of
digits for a smart-large-object identifier is 17; however most smart large
objects would have an identifier with significantly fewer digits.
If the CLOB column has an identifier of 203b2, the LOTOFILE function would
create the file:
/tmp/resume.203b2 ♦
If the CLOB column has an identifier of 203b2, the LOTOFILE function would
create the file:
C:\tmp\resume.203b2 ♦
Segments 4-149
Expression
To change the default filename, you can specify the following wildcards in
the filename of the pathname:
GLS The LOTOFILE function performs any code-set conversion that might be
required when it copies a CLOB value from the database to a file on the client
or server computer. ♦
LOCOPY Function
The LOCOPY function creates a copy of a smart large object. The first
parameter specifies the BLOB or CLOB column to copy. The table and column
parameters are optional:
■ If you omit table and column, the LOCOPY function creates a smart
large object with system-specified storage defaults and copies the
data in the BLOB or CLOB column into it.
The LOCOPY function returns a handle value (a pointer) to the new BLOB or
CLOB value. This function does not actually store the new smart-large-object
value into a column in the database. You must assign the BLOB or CLOB value
to the appropriate column.
The following ESQL/C code fragment copies the CLOB value in the resume
column of the candidate table to the resume column of the interview table:
/* Insert a new row in the interviews table and get the
* resulting SERIAL value (from sqlca.sqlerrd[1])
*/
EXEC SQL insert into interviews (intrv_num, intrv_time)
values (0, '09:30');
intrv_num = sqlca.sqlerrd[1];
In the preceding example, the LOCOPY function returns a handle value for
the copy of the CLOB resume column in the candidate table. Because the
LOCOPY function specifies a table and column name, this new CLOB value
has the storage characteristics of this resume column. If you omit the table
(candidate) and column (resume) names, the LOCOPY function uses the
system-defined storage defaults for the new CLOB value. The UPDATE
statement then assigns this new CLOB value to the resume column in the
interviews table.
Segments 4-151
Expression
Time Functions
DATE ( non_date_expr )
DAY ( date/dtime_expr )
MONTH
WEEKDAY
YEAR
EXTEND ( date/dtime_expr )
, first TO last
TO_CHAR ( source_date )
, format_string
TO_DATE ( char_expression )
, format_string
Segments 4-153
Expression
DATE Function
The DATE function returns a DATE value that corresponds to the non-date
expression with which you call it. The argument can be any expression that
can be converted to a DATE value, usually a CHAR, DATETIME, or INTEGER
value. The following WHERE clause specifies a CHAR value for the non-date
expression:
WHERE order_date < DATE('12/31/97')
This SELECT statement generates an error because the DATE function cannot
convert this non-date expression. The DATE function interprets the first part
of the date string (02) as the year and the second part (01) as the month. For
the third part (1998), the DATE function encounters four digits when it
expects a two-digit day (valid day values must be between 01 and 31). It
therefore cannot convert the value. For the SELECT statement to execute
successfully with the Y2MD/ value for DBDATE, the non-date expression
would need to be '98/02/01'. For information on the format of DBDATE, see
the Informix Guide to SQL: Reference.
When you specify a positive INTEGER value for the non-date expression, the
DATE function interprets the value as the number of days after the default
date of December 31, 1899. If the integer value is negative, the DATE function
interprets the value as the number of days before December 31, 1899. The
following WHERE clause specifies an INTEGER value for the non-date
expression:
WHERE order_date < DATE(365)
The database server searches for rows with an order_date value less than
December 31, 1900 (12/31/1899 plus 365 days).
DAY Function
The DAY function returns an integer that represents the day of the month.
The following example uses the DAY function with the CURRENT function to
compare column values to the current day of the month:
WHERE DAY(order_date) > DAY(CURRENT)
MONTH Function
The MONTH function returns an integer that corresponds to the month
portion of its type DATE or DATETIME argument. The following example
returns a number from 1 through 12 to indicate the month when the order
was placed:
SELECT order_num, MONTH(order_date) FROM orders
WEEKDAY Function
The WEEKDAY function returns an integer that represents the day of the
week; zero (0) represents Sunday, one represents Monday, and so on. The
following lists all the orders that were paid on the same day of the week,
which is the current day:
SELECT * FROM orders
WHERE WEEKDAY(paid_date) = WEEKDAY(CURRENT)
Segments 4-155
Expression
YEAR Function
The YEAR function returns a four-digit integer that represents the year. The
following example lists orders in which the ship_date is earlier than the
beginning of the current year:
SELECT order_num, customer_num FROM orders
WHERE year(ship_date) < YEAR(TODAY)
Similarly, because a DATE value is a simple calendar date, you cannot add or
subtract a DATE value with an INTERVAL value whose last qualifier is smaller
than DAY. In this case, convert the DATE value to a DATETIME value.
EXTEND Function
The EXTEND function adjusts the precision of a DATETIME or DATE value.
The expression cannot be a quoted string representation of a DATE value.
If you do not specify first and last qualifiers, the default qualifiers are YEAR
TO FRACTION(3).
If the expression contains fields that are not specified by the qualifiers, the
unwanted fields are discarded.
If the first qualifier specifies a larger (that is, more significant) field than what
exists in the expression, the new fields are filled in with values returned by
the CURRENT function. If the last qualifier specifies a smaller field (that is,
less significant) than what exists in the expression, the new fields are filled in
with constant values. A missing MONTH or DAY field is filled in with 1, and
the missing HOUR to FRACTION fields are filled in with 0.
In the following example, the first EXTEND call evaluates to the call_dtime
column value of YEAR TO SECOND. The second statement expands a literal
DATETIME so that an interval can be subtracted from it. You must use the
EXTEND function with a DATETIME value if you want to add it to or subtract
it from an INTERVAL value that does not have all the same qualifiers. The
third example updates only a portion of the datetime value, the hour
position. The EXTEND function yields just the hh:mm part of the datetime.
Subtracting 11:00 from the hours and minutes of the datetime yields an
INTERVAL value of the difference, plus or minus, and subtracting that from
the original value forces the value to 11:00.
MDY Function
The MDY function returns a type DATE value with three expressions that
evaluate to integers representing the month, day, and year. The first
expression must evaluate to an integer representing the number of the month
(1 to 12).
The third expression must evaluate to a four-digit integer that represents the
year. You cannot use a two-digit abbreviation for the third expression. The
following example sets the paid_date associated with the order number 8052
equal to the first day of the present month:
UPDATE orders SET paid_date = MDY(MONTH(TODAY), 1,
YEAR(TODAY))
WHERE po_num = '8052'
TO_CHAR Function
The TO_CHAR function converts a DATE or DATETIME value to a character
string. The character string contains the date that was specified in the
source_date parameter, and represents this date in the format that was
specified in the format_string parameter.
IDS You can use this function only with built-in data types. ♦
If the value of the source_date parameter is null, the result of the function is a
null value.
If you omit the format_string parameter, the TO_CHAR function uses the
default date format to format the character string. The default date format is
specified by environment variables such as GL_DATETIME and GL_DATE.
Segments 4-157
Expression
The format_string parameter does not have to imply the same qualifiers as the
source_date parameter. When the implied formatting mask qualifier in format_
string is different from the qualifier in source_date, the TO_CHAR function
extends the DATETIME value as if it had called the EXTEND function.
In the following example, the user wants to convert the begin_date column
of the tab1 table to a character string. The begin_date column is defined as a
DATETIME YEAR TO SECOND data type. The user uses a SELECT statement
with the TO_CHAR function to perform this conversion.
SELECT TO_CHAR(begin_date, '%A %B %d, %Y %R')
FROM tab1
Symbol Meaning
TO_DATE Function
The TO_DATE function converts a character string to a DATETIME value. The
function evaluates the char_expression parameter as a date according to the
date format you specify in the format_string parameter, and returns the equiv-
alent date.
IDS You can use this function only with built-in data types. ♦
If the value of the char_expression parameter is null, the result of the function
is a null value.
If you omit the format_string parameter, the TO_DATE function applies the
default DATETIME format to the DATETIME value. The default DATETIME
format is specified by the GL_DATETIME environment variable.
The format_string parameter in this example tells the TO_DATE function how
to format the converted character string in the begin_date column. For a
table that shows the meaning of each format symbol in this format string, see
“TO_CHAR Function” on page 4-157.
Trigonometric Functions
A trigonometric function takes an argument, as the following diagram
shows.
TAN
ASIN ( numeric_expr )
ACOS
ATAN
ATAN2 ( y, x )
Segments 4-159
Expression
If you are using degrees and want to convert degrees to radians, use the
following formula:
# degrees * p/180= # radians
If you are using radians and want to convert radians to degrees, use the following
formula:
# radians * 180/p = # degrees
COS Function
The COS function returns the cosine of a radian expression. The following
example returns the cosine of the values of the degrees column in the
anglestbl table. The expression passed to the COS function in this example
converts degrees to radians.
SELECT COS(degrees*180/3.1416) FROM anglestbl
SIN Function
The SIN function returns the sine of a radian expression. The following
example returns the sine of the values in the radians column of the anglestbl
table:
SELECT SIN(radians) FROM anglestbl
TAN Function
The TAN function returns the tangent of a radian expression. The following
example returns the tangent of the values in the radians column of the
anglestbl table:
SELECT TAN(radians) FROM anglestbl
ACOS Function
The ACOS function returns the arc cosine of a numeric expression. The
following example returns the arc cosine of the value (-0.73) in radians:
SELECT ACOS(-0.73) FROM anglestbl
ASIN Function
The ASIN function returns the arc sine of a numeric expression. The
following example returns the arc sine of the value (-0.73) in radians:
SELECT ASIN(-0.73) FROM anglestbl
ATAN Function
The ATAN function returns the arc tangent of a numeric expression. The
following example returns the arc tangent of the value (-0.73) in radians:
SELECT ATAN(-0.73) FROM anglestbl
Segments 4-161
Expression
ATAN2 Function
The ATAN2 function computes the angular component of the polar
coordinates (r, θ) associated with (x, y). The following example compares
angles to θ for the rectangular coordinates (4, 5):
WHERE angles > ATAN2(4,5) --determines θ for (4,5) and
compares to angles
You can determine the length of the radial coordinate r using the expression
shown in the following example:
SQRT(POW(x,2) + POW(y,2)) --determines r for (x,y)
You can determine the length of the radial coordinate r for the rectangular
coordinates (4,5) using the expression shown in the following example:
SQRT(POW(4,2) + POW(5,2)) --determines r for (4,5)
String-Manipulation Functions
String-manipulation functions perform various operations on strings of
characters. The syntax for string-manipulation functions is as follows.
TRIM Function
p. 4-164
SUBSTRING Function
p. 4-166
+
SUBSTR Function
p. 4-168
REPLACE Function
p. 4-170
LPAD Function
p. 4-172
RPAD Function
p. 4-173
Case-Conversion Functions
p. 4-174
Segments 4-163
Expression
TRIM Function
Use the TRIM function to remove leading or trailing (or both) pad characters
from a string.
TRIM ( source_expression )
LEADING FROM
TRAILING
BOTH trim_expression
trim_expression FROM
The TRIM function returns a VARCHAR string that is identical to the character
string passed to it, except that any leading or trailing pad characters, if
specified, are removed. If no trim specification (LEADING, TRAILING, or
BOTH) is specified, then BOTH is assumed. If no trim_expression is used, a
single space is assumed. If either the trim_expression or the source_expression
evaluates to null, the result of the TRIM function is null. The maximum
length of the resultant string must be 255 or less, because the VARCHAR data
type supports only 255 characters.
Some generic uses for the TRIM function are shown in the following example:
SELECT TRIM (c1) FROM tab;
SELECT TRIM (TRAILING '#' FROM c1) FROM tab;
SELECT TRIM (LEADING FROM c1) FROM tab;
UPDATE c1='xyz' FROM tab WHERE LENGTH(TRIM(c1))=5;
SELECT c1, TRIM(LEADING '#' FROM TRIM(TRAILING '%' FROM
'###abc%%%')) FROM tab;
GLS When you use the DESCRIBE statement with a SELECT statement that uses the
TRIM function in the select list, the described character type of the trimmed
column depends on the database server you are using and the data type of
the source_expression. For further information on the GLS aspects of the TRIM
function in ESQL/C, see the Informix Guide to GLS Functionality. ♦
If you want to trim the pound sign (#) trim_expression from the column, you
need to consider the blank padded spaces as well as the actual characters. For
example, if you specify the trim specification BOTH, the result from the trim
operation is A2T##, because the TRIM function does not match the blank
padded space that follows the string. In this case, the only pound signs (#)
trimmed are those that precede the other characters. The SELECT statement is
shown, followed by Figure 4-4, which presents the result.
SELECT TRIM(LEADING '#' FROM col1) FROM taba
Figure 4-4
1 2 3 4 5 6 7 8 9 10
Result of TRIM
Operation
A 2 T # #
Segments 4-165
Expression
SUBSTRING Function
The SUBSTRING function returns a subset of a source string.
IDS You can use this function only with built-in data types. ♦
The subset begins at the column position that start_position specifies. The
following table shows how the database server determines the starting
position of the returned subset based on the input value of the start_position.
Zero (0) Counts from one position before (that is, left of) the first character
in source_string
For example, if start_position = 0 and length = 1, the database server
returns null, whereas if length = 2, the database server returns the
first character in source_string.
Negative Counts backward from one position before (that is, left of) the first
character in source_string
For example, if start_position = -1, the starting position of the
return subset is two positions (0 and -1) before the first character
in source_string.
The size of the subset is specified by length. The length parameter refers to the
number of logical characters rather than to the number of bytes. If you omit
the length parameter, the SUBSTRING function returns the entire portion of
source_ string that begins at start_position.
In the following example, the user specifies that the subset of the source
string that begins in column position 3 and is two characters long should be
returned.
SELECT SUBSTRING('ABCDEFG' FROM 3 FOR 2)
FROM mytable
(constant)
CD
Segments 4-167
Expression
In the following example, the user specifies a negative start_position for the
return subset.
SELECT SUBSTRING('ABCDEFG' FROM -3 FOR 7)
FROM mytable
The database server starts at the -3 position (four positions before the first
character) and counts forward for 7 characters. The following table shows the
output of this SELECT statement.
(constant)
ABC
SUBSTR Function
The SUBSTR function has the same purpose as the SUBSTRING function (to
return a subset of a source string), but it uses different syntax.
IDS You can use this function only with built-in data types. ♦
Zero (0) Counts forward from the first character in source_string (that is,
treats a start_position of 0 as equivalent to 1)
The length parameter specifies the number of characters (not bytes) in the
subset. If you omit the length parameter, the SUBSTR function returns the
entire portion of source_ string that begins at start_position.
Segments 4-169
Expression
In the following example, the user specifies that the subset of the source
string to be returned begins at a starting position 3 characters back from the
end of the string. Because the source string is 7 characters long, the starting
position is the fifth column of source_string. Because the user does not
specify a value for length, the database server returns the entire portion of the
source string that begins in column position 5.
SELECT SUBSTR('ABCDEFG', -3)
FROM mytable
(constant)
EFG
REPLACE Function
The REPLACE function replaces specified characters within a source string
with different characters.
IDS You can use this function only with built-in data types. ♦
(constant)
Mighty time
Segments 4-171
Expression
LPAD Function
The LPAD function returns a copy of source_string that is left-padded to the
total number of characters specified by length.
IDS You can use this function only with built-in data types. ♦
In the following example, the user specifies that the source string is to be left-
padded to a total length of 16 characters. The user also specifies that the pad
characters are a sequence consisting of a dash and an underscore (-_).
SELECT LPAD('Here we are', 16, '-_')
FROM mytable
(constant)
-_-_-Here we are
RPAD Function
The RPAD function returns a copy of source_string that is right-padded to the
total number of characters that length specifies.
Segments 4-173
Expression
IDS You can use this function only with built-in data types. ♦
In the following example, the user specifies that the source string is to be
right-padded to a total length of 18 characters. The user also specifies that the
pad characters to be used are a sequence consisting of a question mark and
an exclamation point (?!)
SELECT RPAD('Where are you', 18, '?!')
FROM mytable
(constant)
Case-Conversion Functions
The case-conversion functions enable you to perform case-insensitive
searches in your queries and specify the format of the output. The case-
conversion functions are UPPER, LOWER, and INITCAP. The following
diagram shows the syntax of these case-conversion functions.
UPPER ( source_expression )
LOWER
INITCAP
The input type of source_expression must be a character data type. When the
column is described, the data type the database server returns is the same as
the input type. For example, if the input type is CHAR, the output type is also
CHAR.
IDS You can use these functions only with built-in data types. ♦
GLS The byte length returned from the describe of a column with a case-
conversion function is the input byte length of the source string. If you use a
case-conversion function with a multibyte source_expression, the conversion
might increase or decrease the length of the string. If the byte length of the
result string exceeds the byte length of source_expression, the database server
truncates the result string to fit into the byte length of source_expression. ♦
■ If it has no argument
■ If it has one argument, and that argument is a named argument
■ If it has more than one argument
■ If it appears in a SELECT list with a host variable as an argument
If none of the conditions in the preceding list are met, the database server
treats a case-conversion function as a system function.
Segments 4-175
Expression
The following example shows how you can use all the case-conversion
functions in the same query to specify multiple output formats for the same
value:
Input value:
SAN Jose
Query:
Query output:
UPPER Function
The UPPER function returns a copy of the source_expression in which every
lowercase alphabetical character in the source_expression is replaced by a
corresponding uppercase alphabetic character.
The following example shows how to use the UPPER function to perform a
case-insensitive search on the lname column for all employees with the last
name of curran:
SELECT title, INITCAP(fname), INITCAP(lname) FROM employees
WHERE UPPER (lname) = "CURRAN"
Because the INITCAP function is specified in the select list, the database
server returns the results in a mixed-case format. For example, the output of
one matching row might read: accountant James Curran.
LOWER Function
The LOWER function returns a copy of the source_expression in which every
uppercase alphabetic character in the source_expression is replaced by a corre-
sponding lowercase alphabetic character.
The following example shows how to use the LOWER function to perform a
case-insensitive search on the City column. This statement directs the
database server to replace all instances (that is, any variation) of the words
san jose, with the mixed-case format, San Jose.
INITCAP Function
The INITCAP function returns a copy of the source_expression in which every
word in the source_expression begins with uppercase letter. With this function,
a word begins after any character other than a letter. Thus, in addition to a
blank space, symbols such as commas, periods, colons, and so on, introduce
a new word.
IFX_ALLOW_NEWLINE Function
The IFX_ALLOW_NEWLINE function sets a newline mode that allows
newline characters in quoted strings or disallows newline characters in
quoted strings within a given session.
IFX_ALLOW_NEWLINE ( 't' )
'f'
If you enter 't' as the argument of this function, you enable newline
characters in quoted strings in the session. If you enter 'f' as the argument
of this function, you disallow newline characters in quoted strings in the
session.
Segments 4-177
Expression
You can set the newline mode for all sessions by setting the
ALLOW_NEWLINE parameter in the ONCONFIG file to a value of 0 (newline
characters not allowed) or to a value of 1 (newline characters allowed). If you
do not set this configuration parameter, the default value is 0. Each time you
start a session, the new session inherits the newline mode set in the
ONCONFIG file. To change the newline mode for the session, execute the
IFX_ALLOW_NEWLINE function. Once you have set the newline mode for a
session, the mode remains in effect until the end of the session or until you
execute the IFX_ALLOW_NEWLINE function again within the session.
In the following example, assume that you did not specify any value for the
ALLOW_NEWLINE parameter in the ONCONFIG file, so by default newline
characters are not allowed in quoted strings in any session. After you start a
new session, you can enable newline characters in quoted strings in that
session by executing the IFX_ALLOW_NEWLINE function:
EXECUTE PROCEDURE IFX_ALLOW_NEWLINE('t')
E/C The newline mode that is set by the ALLOW_NEWLINE parameter in the
ONCONFIG file or by the execution of the IFX_ALLOW_NEWLINE function in
a session applies only to quoted-string literals in SQL statements. The
newline mode does not apply to quoted strings contained in host variables in
SQL statements. Host variables can contain newline characters within string
data regardless of the newline mode currently in effect. For example, you can
use a host variable to insert data containing newline characters into a column
even if the ALLOW_NEWLINE parameter in the ONCONFIG file is set to 0. ♦
User-Defined Functions
A user-defined function is a function that you write in SPL or in a language
external to the database, such as C or Java.
function ( Expression )
p. 4-73
IDS
parameter =
You can call user-defined functions within SQL statements. Unlike built-in
functions, user-defined functions can only be used by the creator of the
function, the DBA, and the users who have been granted the Execute
privilege on the function. For more information, see “GRANT” on
page 2-500.
This second example uses the parameter option to specify the argument value:
read_address(lastname = 'Miller')
Segments 4-179
Expression
When you use the parameter option, the parameter name must match the name
of the corresponding parameter in the function registration. For example, the
preceding example assumes that the read_address() function had been regis-
tered as follows:
CREATE FUNCTION read_address(lastname CHAR(20))
RETURNING address_t ...
IDS A statement-local variable (SLV) enables you to transmit a value from a user-
defined function call to another part of the SQL statement. To use an SLV with
a call to a user-defined function, follow these steps:
■ Write an OUT parameter for the user-defined function.
For more information on how to write a user-defined function with
an OUT parameter, see Extending Informix Dynamic Server 2000.
■ When you register the user-defined function, specify the OUT
keyword in front of the OUT parameter.
For more information, see “Specifying an OUT Parameter for a User-
Defined Function” on page 4-290.
■ Declare the SLV in a function expression that calls the user-defined
function with the OUT parameter.
The call to the user-defined function must be made within a WHERE
clause. See “Statement-Local Variable Declaration” on page 4-181 for
information about the syntax to declare the SLV.
■ Use the SLV that the user-defined function has initialized within the
SQL statement.
Once the call to the user defined function has initialized the SLV, you
can use this value in other parts of the SQL statement. See
“Statement-Local Variable Expressions” on page 4-183 for infor-
mation about the use of an SLV within an SQL statement.
opaque_data_type
distinct_data_type
Segments 4-181
Expression
The WHERE clause of the SQL statement must produce an SLV that is used
within other parts of the statement. The following SELECT statement is illegal
because the select list produces the SLV:
-- illegal SELECT statement
SELECT title, contains(body, 'dog and cat', rank # INT), rank
FROM documents
The data type you use when you declare the SLV in a statement must be the
same as the data type of the OUT parameter in the CREATE FUNCTION
statement. If you use different but compatible data types, such as INTEGER
and FLOAT, the database server automatically performs the cast between the
data types.
SLVs shared the name space with UDR variables and the column names of the
table involved in the SQL statement. Therefore, the database uses the
following precedence to resolve ambiguous situations:
■ UDR variables
■ Column names
■ SLVs
Once the user-defined function assigns its OUT parameter to the SLV, you can
use this SLV value in other parts of the SQL statement. For more information,
see “Statement-Local Variable Expressions” on page 4-183.
SLV_variable
You define an SLV in the call to a user-defined function in the WHERE clause
of the SQL statement. This user-defined function must be defined with an
OUT parameter. The call to the user-defined function assigns the value of the
OUT parameter to the SLV. For more information, see “Statement-Local
Variable Declaration” on page 4-181.
Once the user-defined function assigns its OUT parameter to the SLV, you can
use this value in other parts of the SQL statement. You can use the value of
this OUT parameter elsewhere in the statement, subject to the following
scoping rules:
Segments 4-183
Expression
■ In queries that involve UNION, the SLV is only visible in the query in
which it is defined.
The SLV is not visible to all other queries involved in the UNION.
■ For INSERT, DELETE, and UPDATE statements, an SLV is not visible
outside the SELECT portion of the statement.
Within this SELECT portion, all the above scoping rules apply.
Important: A statement-local variable is valid only for the life of a single SQL
statement.
Each user-defined function can have only one OUT parameter and one SLV.
However, a single SQL statement can invoke multiple functions that have
OUT parameters. For example, the following partial statement calls two user-
defined functions with OUT parameters, whose values are referenced with
the SLV names out1 and out2:
SELECT...
WHERE func_2(x, out1 # INTEGER) < 100
AND (out1 = 12 OR out1 = 13)
AND func_3(a, out2 # FLOAT) = "SAN FRANCISCO"
AND out2 = 3.1416;
Aggregate Expressions
An aggregate expression uses an aggregate function to summarize selected
database data.
COUNT ( * )
AVG ( column )
MAX DISTINCT table .
MIN UNIQUE view .
SUM ALL synonym .
COUNT
RANGE
STDEV
VARIANCE
Segments 4-185
Expression
An aggregate function returns one value for a set of queried rows. The
following examples show aggregate functions in SELECT statements:
SELECT SUM(total_price) FROM items WHERE order_num = 1013
If you use an aggregate function and one or more columns in the select list,
you must put all the column names that are not used as part of an aggregate
or time expression in the GROUP BY clause.
Built-in Aggregates
Built-in aggregates are aggregate expressions that are provided by the
database server, such as AVG, SUM, and COUNT. By default, these aggregates
work only with built-in data types, such as INTEGER and FLOAT.
You can extend these built-in aggregates to work with extended data types.
To extend built-in aggregates, you must create UDRs that overload several
binary operators.
Once you have overloaded the binary operators for a built-in aggregate, you
can use that aggregate with an extended data type in an SQL statement. For
example, if you have overloaded the plus operator for the SUM aggregate to
work with a specified row type and assigned this row type to the complex
column of the complex_tab table, you can apply the SUM aggregate to the
complex column:
SELECT SUM(complex) FROM complex_tab
User-Defined Aggregates
A user-defined aggregate is an aggregate that you define to perform an
aggregate computation that is not provided by the database server. For
example, you can create a user-defined aggregate named SUMSQ that returns
the sum of the squared values of a specified column. User-defined aggregates
can work with built-in data types or extended data types or both, depending
on how you define the support functions for the user-defined aggregate.
Segments 4-187
Expression
■ MAX(AVG(order_num))
■ An aggregate function in a WHERE clause, unless it is contained in a
subquery, or if the aggregate is on a correlated column that originates
from a parent query and the WHERE clause is within a subquery that
is within a HAVING clause
■ An aggregate function on a BYTE or TEXT column
The ALL keyword is the opposite of the DISTINCT keyword. If you specify the
ALL keyword, all the values that are selected from the named column or
expression, including any duplicate values, are used in the calculation.
COUNT(*) Function
The COUNT (*) function returns the number of rows that satisfy the WHERE
clause of a SELECT statement. The following example finds how many rows
in the stock table have the value HRO in the manu_code column:
SELECT COUNT(*) FROM stock WHERE manu_code = 'HRO'
If the SELECT statement does not have a WHERE clause, the COUNT (*)
function returns the total number of rows in the table. The following example
finds how many rows are in the stock table:
SELECT COUNT(*) FROM stock
If the SELECT statement contains a GROUP BY clause, the COUNT (*) function
reflects the number of values in each group. The following example is
grouped by the first name; the rows are selected if the database server finds
more than one occurrence of the same name:
SELECT fname, COUNT(*) FROM customer
GROUP BY fname
HAVING COUNT(*) > 1
If the value of one or more rows is null, the COUNT (*) function includes the
null columns in the count unless the WHERE clause explicitly omits them.
Segments 4-189
Expression
Nulls are ignored unless every value in the specified column is null. If every
column value is null, the COUNT DISTINCT function returns a zero (0) for
that column.
The UNIQUE keyword has exactly the same meaning as the DISTINCT
keyword when the UNIQUE keyword is used with the COUNT keyword. The
UNIQUE keyword returns the number of unique non-null values in the
column or expression.
The following example uses the COUNT UNIQUE function, but it is equiv-
alent to the preceding example that uses the COUNT DISTINCT function:
SELECT COUNT (UNIQUE item_num) FROM items
You can include the ALL keyword before the specified column name for
clarity, but the query result is the same whether you include the ALL keyword
or omit it.
The following example shows how to include the ALL keyword in the
COUNT column function:
COUNT (*) Returns the number of rows that satisfy the query
If you do not specify a WHERE clause, this
function returns the total number of rows in the
table.
Some examples can help to show the differences among the different forms
of the COUNT function. The following examples pose queries against the
orders table in the demonstration database. Most of the examples query
against the ship_instruct column in this table. For information on the
structure of the orders table and the data in the ship_instruct column, see the
description of the demonstration database in the Informix Guide to SQL:
Reference.
total_rows
23
Segments 4-191
Expression
In the following example, the user wants to know how many rows in the
orders table have a null value in the ship_instruct column. The user uses the
COUNT(*) function in a SELECT statement with a WHERE clause, and
specifies the IS NULL condition in the WHERE clause.
SELECT COUNT (*) AS no_ship_instruct
FROM orders
WHERE ship_instruct IS NULL
no_ship_instruct
In the following example, the user wants to know how many rows in the
orders table have the value express in the ship_instruct column. So the user
specifies the COUNT (*) function in the select list and the equals (=) relational
operator in the WHERE clause.
SELECT COUNT (*) AS ship_express
FROM ORDERS
WHERE ship_instruct = 'express'
ship_express
total_notnulls
21
The user can also find out how many non-null values are in the ship_instruct
column by including the ALL keyword in the parentheses that follow the
COUNT keyword.
The following table shows that the query result is the same whether you
include or omit the ALL keyword.
all_notnulls
21
unique_notnulls
16
Segments 4-193
Expression
AVG Function
The AVG function returns the average of all values in the specified column or
expression. You can apply the AVG function only to number columns. If you
use the DISTINCT keyword, the average (mean) is greater than only the
distinct values in the specified column or expression. The query in the
following example finds the average price of a helmet:
SELECT AVG(unit_price) FROM stock WHERE stock_num = 110
Nulls are ignored unless every value in the specified column is null. If every
column value is null, the AVG function returns a null for that column.
MAX Function
The MAX function returns the largest value in the specified column or
expression. Using the DISTINCT keyword does not change the results. The
query in the following example finds the most expensive item that is in stock
but has not been ordered:
SELECT MAX(unit_price) FROM stock
WHERE NOT EXISTS (SELECT * FROM items
WHERE stock.stock_num = items.stock_num AND
stock.manu_code = items.manu_code)
Nulls are ignored unless every value in the specified column is null. If every
column value is null, the MAX function returns a null for that column.
MIN Function
The MIN function returns the lowest value in the column or expression.
Using the DISTINCT keyword does not change the results. The following
example finds the least expensive item in the stock table:
SELECT MIN(unit_price) FROM stock
Nulls are ignored unless every value in the specified column is null. If every
column value is null, the MIN function returns a null for that column.
SUM Function
The SUM function returns the sum of all the values in the specified column
or expression, as shown in the following example. If you use the DISTINCT
keyword, the sum is for only distinct values in the column or expression.
SELECT SUM(total_price) FROM items WHERE order_num = 1013
Nulls are ignored unless every value in the specified column is null. If every
column value is null, the SUM function returns a null for that column.
RANGE Function
The RANGE function computes the range for a sample of a population. It
computes the difference between the maximum and the minimum values, as
follows:
range(expr) = max(expr) - min(expr)
You can apply the RANGE function to only numeric columns. The following
query finds the range of ages for a population:
SELECT RANGE(age) FROM u_pop
As with other aggregates, the RANGE function applies to the rows of a group
when the query includes a GROUP BY clause, as shown in the following
example:
SELECT RANGE(age) FROM u_pop
GROUP BY birth
Because DATE data types are stored internally as integers, you can use the
RANGE function on columns of type DATE. When used with a DATE column,
the return value is the number of days between the earliest and latest dates
in the column.
Nulls are ignored unless every value in the specified column is null. If every
column value is null, the RANGE function returns a null for that column.
Important: All computations for the RANGE function are performed in 32-digit
precision, which should be sufficient for many sets of input data. The computation,
however, loses precision or returns incorrect results when all of the input data values
have 16 or more digits of precision.
Segments 4-195
Expression
STDEV Function
The STDEV function computes the standard deviation for a population. It is
the square root of the VARIANCE function.
You can apply the STDEV function only to numeric columns. The following
query finds the standard deviation on a population:
SELECT STDEV(age) FROM u_pop WHERE u_pop.age > 0
As with the other aggregates, the STDEV function applies to the rows of a
group when the query includes a GROUP BY clause, as shown in the following
example:
SELECT STDEV(age) FROM u_pop
GROUP BY birth
WHERE STDEV(age) > 0
Nulls are ignored unless every value in the specified column is null. If every
column value is null, the STDEV function returns a null for that column.
Important: All computations for the STDEV function are performed in 32-digit
precision, which should be sufficient for many sets of input data. The computation,
however, loses precision or returns incorrect results when all of the input data values
have 16 or more digits of precision.
Although DATE data is stored internally as an integer, you cannot use this
function on columns of type DATE.
VARIANCE Function
The VARIANCE function returns the population variance. It computes the
following value:
(SUM(Xi 2) - (SUM(Xi) 2)/N)/N
In this formula, Xi is each value in the column and N is the total number of
values in the column.
As with the other aggregates, the VARIANCE function applies to the rows of
a group when the query includes a GROUP BY clause, as shown in the
following example:
SELECT VARIANCE(age) FROM u_pop
GROUP BY birth
WHERE VARIANCE(age) > 0
When you use the VARIANCE function, nulls are ignored unless every value
in the specified column is null. If every column value is null, the VARIANCE
function returns a null for that column. If the total number of values in the
column is equal to one, the VARIANCE function returns a zero variance. If
you want to omit this special case, you can adjust the query construction. For
example, you might include a HAVING COUNT(*) > 1 clause.
Important: All computations for the VARIANCE function are performed in 32-digit
precision, which should be sufficient for many sets of input data. The computation,
however, loses precision or returns incorrect results when all of the input data values
have 16 or more digits of precision.
Although DATE data is stored internally as an integer, you cannot use this
function on columns of type DATE.
a_number
(null)
Segments 4-197
Expression
average_number
2.66666666666667
You can use the other aggregate functions in SELECT statements that are
similar to the one shown in the preceding example. If you enter a series of
SELECT statements that have different aggregate functions in the select list
and do not have a WHERE clause, you receive the results that the following
table shows.
Function Results
COUNT (*) 7
COUNT (DISTINCT) 3
COUNT (ALL 6
a_number)
COUNT (a_number) 6
AVG 2.66666666666667
MAX 4
MAX(DISTINCT) 4
MIN 2
MIN(DISTINCT) 2
SUM 16
(1 of 2)
Function Results
SUM(DISTINCT) 9
RANGE 2
STDEV 0.74535599249993
VARIANCE 0.55555555555556
(2 of 2)
You can also use the GET DIAGNOSTICS statement for error checking. ♦
Segments 4-199
Expression
aggregate ( column )
DISTINCT table .
UNIQUE view . , setup_expr
ALL synonym .
Subset of Expression
p. 4-188
ALL
When you specify a set-up expression, this value is passed to the INIT
support function that was defined for the user-defined aggregate in the
CREATE AGGREGATE statement.
Related Information
For a discussion of expressions in the context of the SELECT statement, see the
Informix Guide to SQL: Tutorial.
Segments 4-201
External Routine Reference
Syntax
NOT
Usage
The External Routine Reference provides the following information about an
external routine:
Parameter Style
By default, the parameter style is INFORMIX. If you specify an OUT
parameter, the OUT argument is passed by reference.
If the function is nonvariant, the database server might cache the return
variant functions. For more information on functional indexes, see “CREATE
INDEX” on page 2-157.
To register a nonvariant function, add the NOT VARIANT option in this clause
or in the Routine Modifier clause that is discussed in “Routine Modifier” on
page 4-274. However, if you specify the modifier in both places, you must use
the same modifier in both clauses.
Segments 4-203
External Routine Reference
The function returns a single value of type BOOLEAN. The external name
specifies the path to the C shared object file where the object code of the
function is stored. The external name indicates that the library contains
another function, point1_equal, which is invoked while equal(point, point)
is executing.
Identifier
An identifier specifies the simple name of a database object, such as a column,
table, index, or view. Use the Identifier segment whenever you see a reference
to an identifier in a syntax diagram.
Syntax
letter
underscore
letter
digit
underscore
IDS
dollar_sign
Delimited Identifier
p. 4-208
Segments 4-205
Identifier
Usage
The elements of an identifier cannot be separated by blanks. To include a
space character in an identifier, you must specify a delimited identifier. For
more information, see “Delimited Identifiers” on page 4-208.
IDS An identifier can contain up to 128 bytes, inclusive. For example, the
following table name is valid: employee_information. ♦
XPS An identifier can contain up to 18 bytes, inclusive. For example, the following
table name is valid: employee_info. ♦
GLS If you are using a multibyte code set, keep in mind that the maximum length
of an identifier refers to the number of bytes, not the number of characters.
For further information on the GLS aspects of identifiers, see the Informix
Guide to GLS Functionality. ♦
IDS The database server checks the internal version number of the client appli-
cation and the setting of the IFX_LONGID environment variable to determine
E/C whether a client application is capable of handling long identifiers (identi-
fiers that are up to 128 bytes in length). For further information on the
IFX_LONGID environment variable, see the Informix Guide to SQL:
Reference. ♦
IDS For a list of all the reserved words in the Informix implementation of SQL in
Dynamic Server, see Appendix A, “Reserved Words for Dynamic Server”. ♦
XPS For a list of all the reserved words in the Informix implementation of SQL in
Extended Parallel Server, see Appendix B, “Reserved Words for Extended
Parallel Server”. ♦
Delimited identifiers provide the easiest and safest way to use a reserved
word as an identifier without causing syntactic ambiguities. No
workarounds are necessary when you use a reserved word as a delimited
identifier. For the syntax and usage of delimited identifiers, see “Delimited
Identifiers” on page 4-208.
Segments 4-207
Identifier
Tip: If you receive an error message that seems unrelated to the statement that caused
the error, check to determine whether the statement uses a reserved word as an
undelimited identifier.
Delimited Identifiers
underscore
special_character
Delimited identifiers allow you to specify names for database objects that are
otherwise identical to SQL reserved keywords, such as TABLE, WHERE,
DECLARE, and so on. The only database object for which you cannot use
delimited identifiers is database name.
When you create a database object, avoid including one or more trailing
blanks in a delimited identifier. In other words, immediately follow the last
non-blank character of the name with the end quote.
Segments 4-209
Identifier
The following example shows how to create a table whose name includes a
space character. If the table name were not enclosed in double quotes ("), you
could not use a space character in the name.
CREATE TABLE "My Customers" (...)
The following example shows how to create a table that uses a keyword as
the table name:
CREATE TABLE "TABLE" (...)
Using avg as a column name causes the following example to fail because the
database server interprets avg as an aggregate function rather than as a
column name:
SELECT avg FROM mytab -- fails
Segments 4-211
Identifier
The database server interprets user, current, and today in the SELECT
statement as the built-in functions USER, CURRENT, and TODAY. Thus,
instead of returning josh, 11:30:30,1/22/89, the SELECT statement returns
the current user name, the current time, and the current date.
If you want to select the actual columns of the table, you must write the
SELECT statement in one of the following ways:
First, consider what happens when you try to use one of these keywords
without a workaround. In the following example, using all as a column name
causes the SELECT statement to fail because the database server interprets all
as a keyword rather than as a column name:
SELECT all FROM mytab -- fails
The workaround in the following example uses the keyword ALL with the
column name all:
SELECT ALL all FROM mytab
The rest of the examples in this section show workarounds for using the
keywords UNIQUE or DISTINCT as a column name in a CREATE TABLE
statement.
Using unique as a column name causes the following example to fail because
the database server interprets unique as a keyword rather than as a column
name:
CREATE TABLE mytab (unique INTEGER) -- fails
The workaround in the following example uses two SQL statements. The first
statement creates the column mycol; the second renames the column mycol
to unique.
CREATE TABLE mytab (mycol INTEGER)
The workaround in the following example also uses two SQL statements. The
first statement creates the column mycol; the second alters the table, adds the
column unique, and drops the column mycol.
CREATE TABLE mytab (mycol INTEGER)
Segments 4-213
Identifier
The workaround in the following example includes an owner name with the
table name:
SELECT josh.mytab.interval FROM josh.mytab;
Important: Informix recommends that you use primary keys as an access method
rather than exploiting the rowid column.
Using statistics as a table name causes the following example to fail because
the database server interprets it as part of the UPDATE STATISTICS syntax
rather than as a table name in an UPDATE statement:
UPDATE statistics SET mycol = 10
The workaround in the following example specifies an owner name with the
table name, to avoid ambiguity:
UPDATE josh.statistics SET mycol = 10
Using outer as a table name causes the following example to fail because the
database server interprets outer as a keyword for performing an outer join:
SELECT mycol FROM outer -- fails
You can use the AS keyword in front of column labels or table aliases.
The following example uses the AS keyword with a column label:
SELECT column-name AS display-label FROM table-name
Segments 4-215
Identifier
Using units as a column label causes the following example to fail because
the database server interprets it as a DATETIME qualifier for the column
named mycol:
SELECT mycol units FROM mytab
The following examples show how the AS or FROM keyword can be used as
a column label.
Using as as a column label causes the following example to fail because the
database server interprets as as identifying from as a column label and thus
finds no required FROM clause:
SELECT mycol as from mytab -- fails
Using from as a column label causes the following example to fail because
the database server expects a table name to follow the first from:
SELECT mycol from FROM mytab -- fails
The following example uses the AS keyword to identify the first from as a
column label:
SELECT mycol AS from FROM mytab
Using order as a table alias causes the following example to fail because the
database server interprets order as part of an ORDER BY clause:
SELECT * FROM mytab order -- fails
The following two examples show how to use the keyword WITH as a table
alias.
Using with as a table alias causes the following example to fail because the
database server interprets the keyword as part of the WITH CHECK OPTION
syntax:
EXEC SQL select * from mytab with; -- fails
The following two examples show how to use the keyword CREATE (or
GRANT) as a table alias.
Using create as a table alias causes the following example to fail because the
database server interprets the keyword as part of the syntax to create an
entity such as a table, synonym, or view:
EXEC SQL select * from mytab create; -- fails
Segments 4-217
Identifier
For example, if you define a variable called null, when you try to insert the
value null into a column, you receive a syntax error, as shown in the
following example:
CREATE PROCEDURE problem()
.
.
.
DEFINE null INT;
LET null = 3;
INSERT INTO tab VALUES (null); -- error, inserts NULL, not 3
IF x IN (1, 2, 4) THEN
SELECT customer_num, fname INTO y, pfname FROM customer
WHERE customer IN (select , 301 , 302, 303); -- problem in
You can use the variable select in an IN list if you ensure it is not the first
element in the list. The workaround in the following example corrects the IF
statement shown in the preceding example:
IF x IN (10, select, 12) THEN LET y = 1; -- problem if
Segments 4-219
Identifier
TRACE procedure;--ambiguous
TRACE 0+procedure;--ok
The following examples show incorrect and correct use of a SET LOCK MODE
statement inside an ON EXCEPTION statement.
ON EXCEPTION IN (-107)
SET LOCK MODE TO WAIT; -- error, value expected, not 'lock'
END EXCEPTION
Segments 4-221
Identifier
ON EXCEPTION IN (-107)
BEGIN
SET LOCK MODE TO WAIT; -- ok
END
END EXCEPTION
Related Information
For a discussion of owner naming, see your Performance Guide.
Syntax
YEAR
( y-precision ) TO YEAR
(4)
MONTH
( precision ) TO MONTH
(2)
DAY
( precision ) TO DAY
(2)
HOUR
( precision ) TO HOUR
(2)
MINUTE
( precision ) TO MINUTE
(2)
SECOND
( precision ) TO SECOND
(2)
FRACTION TO FRACTION
( f-precision )
(3)
Segments 4-223
INTERVAL Field Qualifier
Usage
The next two examples show INTERVAL data types of the YEAR TO MONTH
type. The first example can hold an interval of up to 999 years and 11 months,
because it gives 3 as the precision of the year field. The second example uses
the default precision on the year field, so it can hold an interval of up to 9,999
years and 11 months.
YEAR (3) TO MONTH
YEAR TO MONTH
When you want a value to contain only one field, the first and last qualifiers
are the same. For example, an interval of whole years is qualified as YEAR TO
YEAR or YEAR (5) TO YEAR, for an interval of up to 99,999 years.
DAY TO DAY
Related Information
For information about how to specify INTERVAL field qualifiers and use
INTERVAL data in arithmetic and relational operations, see the discussion of
the INTERVAL data type in the Informix Guide to SQL: Reference.
Segments 4-225
Jar Name
Syntax
jar_id
schema .
database .
Before you can access a jar_id in any way (including its use in a CREATE
FUNCTION or CREATE PROCEDURE statement), it must be defined in the
current database with the install_jar() procedure. For more information, see
“EXECUTE PROCEDURE” on page 2-444.
IDS
Literal Collection
Use the Literal Collection segment to specify values for a collection column.
For syntax that allows you to use expressions that evaluate to element values,
see “Collection Constructors” on page 4-118.
Syntax
,
" SET { Element Literal Value } "
p .4-228
MULTISET
Nested Literal Nested
Quotation Collection Quotation
LIST Marks Marks
p. 4-229 p. 4-229
,
' SET { Element Literal Value } '
p .4-228
MULTISET
Nested Literal Nested
Quotation Collection Quotation
LIST Marks Marks
p. 4-229 p. 4-229
Usage
You can specify literal collection values for each of the collection data types:
SET, MULTISET, or LIST.
To specify a single literal-collection value, specify the collection type and the
literal values. The following SQL statement inserts four integer values into
the set_col column that is declared as SET(INT NOT NULL):
INSERT INTO table1 (set_col) VALUES ("SET{6, 9, 9, 4}")
Segments 4-227
Literal Collection
You specify an empty collection with a set of empty braces ({}). The following
INSERT statement inserts an empty list into a collection column list_col that
is declared as LIST(INT NOT NULL):
INSERT INTO table2 (list_col) VALUES ("LIST{}")
SQLE If you are passing a literal collection as an argument to an SPL routine, make
sure that there is a space between the parentheses that surround the
arguments and the quotation marks that indicate the beginning and end of
the literal collection. ♦
If you specify a collection as a literal value in a literal row string you need not
include the quotation marks around the collection itself. Only the outermost
quotation marks that delineate the row string literal are necessary. No
quotation marks need surround the nested collection type. For an example,
see “Literals for Nested Rows” on page 4-243.
Elements of a collection can be literal values for the data types in the
following table.
A nested collection is a collection that is the element type for another collection.
Whenever you nest collection literals, you use nested quotation marks. In
these cases, you must follow the rule for nesting quotation marks. Otherwise,
the server cannot correctly parse the strings.
The general rule is that you must double the number of quotation marks for
each new level of nesting. For example, if you use double quotation marks for
the first level, you must use two double quotation marks for the second level,
four double quotation marks for the third level, eight for the fourth level,
sixteen for the fifth level, and so on. Likewise, if you use single quotes for the
first level, you must use two single quotation marks for the second level and
four single quotation marks for the third level.
There is no limit to the number of levels you can nest, as long as you follow
this rule.
Segments 4-229
Literal Collection
For any individual literal value, the opening quotation marks and the closing
quotation marks must match. In other words, if you open a literal with two
double quotes, you must close that literal with two double quotes
(""a literal value"").
For more information, see the chapter on complex data types in the Informix
ESQL/C Programmer’s Manual. ♦
The following statement inserts three elements into the nest_col column:
INSERT INTO tabx (nest_col)
VALUES ("SET{'MULTISET{1, 2, 3}'}")
Literal DATETIME
The literal DATETIME segment specifies a literal DATETIME value. Use the
literal DATETIME segment whenever you see a reference to a literal
DATETIME in a syntax diagram.
Syntax
DATETIME
DATETIME ( Numeric Date ) Field Qualifier
p. 4-71
Numeric Date
yyyy
-
mo
-
dd
space
hh
:
mi
:
ss
.
f
Segments 4-231
Literal DATETIME
Usage
You must specify both a numeric date and a DATETIME field qualifier for this
date in the Literal DATETIME segment. The DATETIME field qualifier must
correspond to the numeric date you specify. For example, if you specify a
numeric date that includes a year as the largest unit and a minute as the
smallest unit, you must specify YEAR TO MINUTE as the DATETIME field
qualifier.
The following example shows a literal DATETIME value used with the
EXTEND function:
Related Information
For discussions of the DATETIME data type and the DBCENTURY
environment variable, see the Informix Guide to SQL: Reference.
Segments 4-233
Literal INTERVAL
Literal INTERVAL
The Literal INTERVAL segment specifies a literal INTERVAL value. Use the
Literal INTERVAL segment whenever you see a reference to a literal
INTERVAL in a syntax diagram.
Syntax
INTERVAL
INTERVAL ( Numeric Date ) Field Qualifier
p. 4-223
Numeric Date
yyyy
-
mo
dd
space
hh
:
mi
:
ss
.
Segments 4-235
Literal INTERVAL
Usage
The following examples show literal INTERVAL values:
INTERVAL (3-6) YEAR TO MONTH
INTERVAL (09:55:30.825) HOUR TO FRACTION
INTERVAL (40 5) DAY TO HOUR
Related Information
For information on how to use INTERVAL data in arithmetic and relational
operations, see the discussion of the INTERVAL data type in the Informix Guide
to SQL: Reference.
Literal Number
A literal number is an integer or noninteger (floating) constant. Use the
Literal Number segment whenever you see a reference to a literal number in
a syntax diagram.
Syntax
digit
+ .
-
digit
. digit E digit
+
-
Usage
Literal numbers do not contain embedded commas; you cannot use a comma
to indicate a decimal point. You can precede literal numbers with a plus or a
minus sign.
Integers
Integers do not contain decimal points. The following examples show some
integers:
10 -27 25567
Segments 4-237
Literal Number
The digits to the right of the decimal point in these examples are the decimal
portions of the numbers.
The E that occurs in two of the examples is the symbol for exponential
notation. The digit that follows E is the value of the exponent. For example,
the number 3E5 (or 3E+5) means 3 multiplied by 10 to the fifth power, and
the number 3E-5 means 3 multiplied by 10 to the minus fifth power.
Related Information
For discussions of numeric data types, such as DECIMAL, FLOAT, INTEGER,
and MONEY, see the Informix Guide to SQL: Reference.
IDS
Literal Row
The Literal Row segment specifies the syntax for literal values of named row
types and unnamed row types. For syntax that allows you to use expressions
that evaluate to field values, see “ROW Constructors” on page 4-116.
Syntax
,
Literal Row
Usage
You can specify literal values for named row types and unnamed row types.
The literal row value is introduced with a ROW constructor. The entire literal
row value must be enclosed in quotes.
The format of the value for each field of the row type must be compatible
with the data type of the corresponding field.
Segments 4-239
Literal Row
Quoted String
p. 4-260
Literal Number
p. 4-237
USER
Literal DATETIME
p. 4-231
Literal INTERVAL
p. 4-234
Literal Collection
p. 4-227
literal_opaque_type
literal_BOOLEAN
Fields of a row can be literal values for the data types in the following table.
Another row type (named or unnamed) For information on a row type value
as literal a row type, see “Literals for
Nested Rows” on page 4-243
Important: You cannot specify the simple-large-object data types (BYTE and TEXT)
as the field type for a row.
Segments 4-241
Literal Row
The following INSERT statement inserts values into the rect column of the
rectangles table:
INSERT INTO rectangles (rect)
VALUES ("ROW(7, 3, 6.0, 2.0)")
The following INSERT statement inserts values into the address column of the
employee table:
INSERT INTO employee (address)
VALUES (
"ROW('103 Baker St', 'Tracy','CA', 94060)"::address_t)
Similarly, if the row string literal contains a nested collection, only the
outermost quotation marks that delineate the row string literal are necessary.
No quotation marks need surround the nested collection type.
Related Information
Related statements: CREATE ROW TYPE, INSERT, UPDATE, and SELECT
For information on ROW constructors, see the Expression segment. See also
the Collection Literal segment.
Segments 4-243
Optimizer Directives
IDS
Optimizer Directives
The Optimizer Directives segment specifies keywords that you can use to
partially or fully specify the query plan of the optimizer. Use this segment
whenever you see a reference to Optimizer Directives in a syntax diagram.
Syntax
,
Join-Order
--+ Directive
p. 4-246
{+ Access-Method
}
Directives
/*+ p. 4-248 */
Join-Method
Directives
p. 4-252
Optimization-Goal
Directives
p. 4-255
EXPLAIN
Usage
Use one or more optimizer directives to partially or fully specify the query
plan of the optimizer.
When you use an optimizer directive, the scope of the optimizer directive is
for the current query only.
After the comment symbol, the first character in a directive is always a plus
(+) sign. No space is allowed between the comment symbol and the plus sign.
For more information on SQL comment symbols, see “How to Enter SQL
Comments” on page 1-6.
If you use multiple directives in one query, you must separate them. You can
separate directives with a space, a comma, or any character that you choose.
However, Informix recommends that you separate directives with a comma.
■ Distributed queries, that is, queries that access one or more remote
tables
E/C ■ In ESQL/C, statements that contain the WHERE CURRENT OF cursor
clause ♦
Segments 4-245
Optimizer Directives
ORDERED
comments
For example, the following query forces the database server to join the dept
and job tables, and then join the result with the emp table.
SELECT --+ ORDERED
name, title, salary, dname
FROM dept, job, emp
Where title = 'clerk'
AND loc = 'Palo Alto'
AND emp.dno = dept.dno
AND emp.job= job.job
Because no predicates occur between the dept table and the job table, this
query forces a Cartesian product.
For examples that use the ORDERED join-order directive with views, refer to
your Performance Guide.
Segments 4-247
Optimizer Directives
Access-Method Directives
Use the access-method directive to specify the manner in which the optimizer
should search the tables.
.
INDEX ( table )
,
synonym
index
alias comments
"index"
FULL ( table )
AVOID_FULL synonym
alias
You can separate the elements that appear within the parentheses with either
one or more spaces or by commas.
The following table lists the purpose of each of the access-method directives
and how it affects the query plan of the optimizer.
AVOID_INDEX Do not use any of the indexes The optimizer considers the
listed. remaining indexes and a full
table scan.
If all indexes for a particular
table are specified, the
optimizer uses a full table scan
to access the table.
(1 of 2)
Segments 4-249
Optimizer Directives
In this example the access-method directive forces the optimizer to scan the
index on the dept_no column.
Segments 4-251
Optimizer Directives
Join-Method Directives
Use join-method directives to influence how the database server joins tables
in a query.
USE_NL ( table )
AVOID_NL synonym comments
alias
,
USE_HASH ( table )
AVOID_HASH synonym / BUILD
alias / PROBE
You can separate the elements that appear within the parentheses with either
one or more spaces or by commas.
The following table lists the purpose of each of the join-method directives
Keyword Purpose
AVOID_NL Does not use the listed table as the inner table in a
nested loop join.
A table listed with this directive can still participate in a
nested loop join as the outer table.
AVOID_HASH Does not access the listed table using a hash join.
Optionally, you can allow a hash join, but restrict the
table from being the one that is probed, or the table from
which the hash table is built.
A join-method directive takes precedence over the join method forced by the
OPTCOMPIND configuration parameter.
Segments 4-253
Optimizer Directives
■ BUILD
When used with USE_HASH, this keyword indicates that the
specified table be used to construct a hash table. When used with
AVOID_HASH, this keyword indicates that the specified table not be
used to construct a hash table.
■ PROBE
When used with USE_HASH, this keyword indicates that the
specified table be used to probe the hash table. When used with
AVOID_HASH, this keyword indicates that the specified table not be
used to probe the hash table. You can specify multiple probe tables
as long as there is at least one table for which you do not specify
PROBE.
If neither the BUILD nor PROBE keyword is specified, the optimizer uses cost
to determine the role of the table.
Optimization-Goal Directives
Use optimization-goal directives to specify the measure that is used to
determine the performance of a query result.
ALL_ROWS
FIRST_ROWS comments
■ In a view definition
■ In a subquery
Segments 4-255
Optimizer Directives
For information about how to set the optimization goal for an entire session,
see the SET OPTIMIZATION statement.
Directive-Mode Directive
Use the EXPLAIN directive-mode directive to turn SET EXPLAIN ON for a
particular query. You can use this directive to test and debug query plans.
Information about the query plan is printed to the sqexplain.out file. This
directive is redundant when SET EXPLAIN ON is already specified.
■ In a view definition
■ In a subquery
Related Information
For information about the sqexplain.out file, see SET EXPLAIN.
For information about how to set optimization settings for an entire session,
see SET OPTIMIZATION.
For a discussion about optimizer directives and performance, see your Perfor-
mance Guide.
Owner Name
The owner name segment specifies the name of the owner of a database
object in a database. Use this segment whenever you see a reference to Owner
Name in a syntax diagram.
Syntax
owner
Usage
In databases that are not ANSI compliant, the owner name is optional. You do
not need to specify owner when you create database objects or use data access
statements. If you do not specify owner when you create a database object, the
database server assigns your login name as the owner of the object in most
cases. For exceptions to this rule, see “Ownership of Created Database
Objects” on page 2-153 in CREATE FUNCTION and “Ownership of Created
Database Objects” on page 2-208 in CREATE PROCEDURE.
Segments 4-257
Owner Name
The following example shows four queries that can access data successfully
from the table kaths.tab1:
SELECT * FROM tab1
SELECT * FROM kaths.tab1
SELECT * FROM KATHS.tab1
SELECT * FROM Kaths.tab1
Suppose you have a table whose owner is Sam. You can use one of the
following two statements to access data in the table.
SELECT * FROM table1
SELECT * FROM ' Sam' .table1
The first query succeeds because the owner name is not required. The second
query succeeds because the specified owner name matches the owner name
as it is stored in the database.
Tip: The USER keyword returns the login name exactly as it is stored on the system.
If the owner name is stored differently from the login name (for example, a mixed-case
owner name and an all lowercase login name), the owner = USER syntax fails.
The following SELECT statement fails because it tries to match the name
NANCY.njcust to the actual owner and table name of nancy.njcust.
Tip: When you use the owner name as one of the selection criteria in a query, (for
example, WHERE owner = 'kaths'), make sure that the quoted string matches the
owner name as it is stored in the database. If the database server cannot find the
database object or database, you might need to modify the query so that the quoted
string uses uppercase letters (for example, WHERE owner = 'KATHS').
Segments 4-259
Quoted String
Quoted String
A quoted string is a string constant that is surrounded by quotation marks.
Use the Quoted String segment whenever you see a reference to a quoted
string in a syntax diagram.
Syntax
' '
+
character
''
" "
character
""
Usage
You use quoted strings to specify string constants in data manipulation state-
ments and other SQL statements. For example, you can use a quoted string in
an INSERT statement to insert a value into a column with a character data
type.
■ If you are using the ASCII code set, you can specify any printable
ASCII character, including a single quote or double quote. For restric-
tions that apply to using quotes in quoted strings, see “Using Quotes
in Strings” on page 4-262.
GLS ■ If you are using a nondefault locale, you can specify non-ASCII
characters, including multibyte characters, that the code set of your
locale supports. For further information, see the discussion of quoted
strings in the Informix Guide to GLS Functionality. ♦
■ If you enable newline characters for quoted strings, you can embed
newline characters in quoted strings. For further information on how
to enable newline characters for quoted strings, see “Newline
Characters in Quoted Strings” on page 4-262.
■ When you set the DELIMIDENT environment variable, you cannot
use double quotes to delimit a quoted string. When DELIMIDENT is
set, a string enclosed in double quotes is an identifier, not a quoted
string. When DELIMIDENT is not set, a string enclosed in double
quotes is a quoted string, not an identifier. For further information,
see “Using Quotes in Strings” on page 4-262.
■ You can enter DATETIME and INTERVAL data as quoted strings. For
the restrictions that apply to entering DATETIME and INTERVAL data
in quoted-string format, see “DATETIME and INTERVAL Values as
Strings” on page 4-263.
■ Quoted strings that are used with the LIKE or MATCHES keyword in
a search condition can include wildcard characters that have a
special meaning in the search condition. For further information, see
“LIKE and MATCHES in a Condition” on page 4-263.
■ When you insert a value that is a quoted string, you must observe a
number of restrictions. For further information, see “Inserting Values
as Quoted Strings” on page 4-264.
Segments 4-261
Quoted String
If newline characters in quoted strings are not enabled for a session, the
following statement is illegal and results in an error:
SELECT 'The quick brown fox
jumped over the old gray fence'
FROM customer
WHERE customer_num = 101
However, if you enable newline characters in quoted strings for the session,
the statement in the preceding example is legal and executes successfully.
If your string is delimited by double quotes, you can include a double quote
in the string by preceding the double quote with another double quote, as
shown in the following string:
"Enter ""y"" to select this row"
The format of the value in the quoted string must exactly match the format
specified by the qualifiers of the column. For the first case in the preceding
example, the call_dtime column must be defined with the qualifiers YEAR TO
SECOND for the INSERT statement to be valid.
Segments 4-263
Quoted String
Related Information
For a discussion of the DELIMIDENT environment variable, see the Informix
Guide to SQL: Reference.
For a discussion of the GLS aspects of quoted strings, see the Informix Guide to
GLS Functionality.
Relational Operator
A relational operator compares two expressions quantitatively. Use the
Relational Operator segment whenever you see a reference to a relational
operator in a syntax diagram.
Syntax
<
<=
>
=
>=
<>
+
!=
= Equal to
!= Not equal to
Segments 4-265
Relational Operator
Usage
For DATE and DATETIME expressions, greater than means later in time.
For CHAR, VARCHAR, and LVARCHAR expressions, greater than means after in
code-set order.
GLS Locale-based collation order is used for NCHAR and NVARCHAR expressions.
So for NCHAR and NVARCHAR expressions, greater than means after in the
locale-based collation order. For more information on locale-based collation
order and the NCHAR and NVARCHAR data types, see the Informix Guide to
GLS Functionality. ♦
< lessthan()
<= lessthanorequal()
>= greaterthanorequal()
= equal()
<> notequal()
!= notequal()
The database server provides the operator functions associated with the
relational operators for all built-in data types. When you develop a user-
defined data type, you must define the operator functions for that type for
users to be able to use the relational operator on the type.
UNIX On UNIX, the default code set is the ISO8859-1 code set, which consists of the
following sets of characters:
WIN NT In Windows NT, the default code set is Microsoft 1252. This code set includes
both the ASCII code set and a set of 8-bit characters. ♦
Segments 4-267
Relational Operator
The following table shows the ASCII code set. The Num column shows the
ASCII code numbers, and the Char column shows the ASCII character corre-
sponding to each ASCII code number. ASCII characters are sorted according
to their ASCII code number. Thus lowercase letters follow uppercase letters,
and both follow numerals. In this table, the caret symbol (^) stands for the
CTRL key. For example, ^X means CTRL-X.
Num Char Num Char Num Char Num Char Num Char Num Char Num Char
1 ^A 21 ^U 41 ) 61 = 81 Q 101 e 121 y
3 ^C 23 ^W 43 + 63 ? 83 S 103 g 123 {
4 ^D 24 ^X 44 , 64 @ 84 T 104 h 124 |
5 ^E 25 ^Y 45 - 65 A 85 U 105 i 125 }
6 ^F 26 ^Z 46 . 66 B 86 V 106 j 126 ~
8 ^H 28 ^\ 48 0 68 D 88 X 108 l
9 ^I 29 ^] 49 1 69 E 89 Y 109 m
10 ^J 30 ^^ 50 2 70 F 90 Z 110 n
11 ^K 31 ^_ 51 3 71 G 91 [ 111 o
12 ^L 32 52 4 72 H 92 \ 112 p
13 ^M 33 ! 53 5 73 I 93 ] 113 q
14 ^N 34 " 54 6 74 J 94 ^ 114 r
15 ^O 35 # 55 7 75 K 95 _ 115 s
16 ^P 36 $ 56 8 76 L 96 ` 116 t
17 ^Q 37 % 57 9 77 M 97 a 117 u
18 ^R 38 & 58 : 78 N 98 b 118 v
19 ^S 39 ' 59 ; 79 O 99 c 119 w
Related Information
For a discussion of relational operators in the SELECT statement, see the
Informix Guide to SQL: Tutorial.
For a discussion of the GLS aspects of relational operators, see the Informix
Guide to GLS Functionality.
Segments 4-269
Return Clause
Return Clause
The Return Clause specifies the data type of a value or values that a user-
defined function returns. Use this segment whenever you see reference to the
Return Clause in a syntax diagram.
Syntax
Usage
IDS For backward compatibility, you can continue to create SPL functions with
the CREATE PROCEDURE statement (that is include a Return Clause with the
CREATE PROCEDURE statement). However, Informix recommends that you
use the CREATE FUNCTION statement to create an SPL routine that returns
one or more values. ♦
Once you use the return clause to indicate the type of values that are to be
returned, you can use the RETURN SPL statement at any point in the
statement block to return SPL variables that correspond to the values in the
return clause.
Ext For an external function, you can specify only one data type in the return
clause. However, an external function can return more than one row of data
if it is an iterator function. For more information, see “ITERATOR” on
page 4-279. ♦
XPS A user-defined function can return values of any built-in data type except
SERIAL, TEXT, or BYTE. ♦
IDS A user-defined function can return values of any built-in data type except
those listed in the following table.
BLOB ✔ ✔
BYTE ✔ ✔ ✔
COLLECTION ✔
CLOB ✔ ✔
LIST ✔
MULTISET ✔
ROW ✔ ✔
SET ✔ ✔
SERIAL ✔ ✔ ✔
SERIAL8 ✔ ✔ ✔
TEXT ✔ ✔ ✔
Segments 4-271
Return Clause
If you use a complex type in the return clause, the calling user-defined
routine must define variables of the appropriate complex types to hold the
values that the C or SPL user-defined function returns.
The following example shows how to select a text column within an SPL
routine and then return the value:
CREATE FUNCTION sel_text()
RETURNING REFERENCES text;
END FUNCTION
XPS In Extended Parallel Server, to recreate this example use the CREATE
PROCEDURE statement instead of the CREATE FUNCTION statement. ♦
A function that returns only one set of values (such as one or more columns
from a single row of a table) is a noncursor function.
In the following example, the return clause can return zero (0) or two values
if it occurs in a noncursor function. However, if this clause is associated with
a cursor function, it returns more than one row from a table and each
returned row contains zero or two values.
RETURNING INT, INT;
Segments 4-273
Routine Modifier
IDS
Routine Modifier
A routine modifier specifies characteristics of how a user-defined routine
(UDR) behaves. Use the Routine Modifier segment whenever you see a
reference to a routine modifier in a syntax diagram.
Syntax
Adding or Modifying a
Routine Modifier
p. 4-275
Dropping a
Routine Modifier
p.4-277
Some modifiers are available only with user-defined functions. For infor-
mation on whether or not a specific routine modifier applies only to user-
defined functions (that is, if it does not apply to user-defined procedures), see
the textual description for the modifier.
NOT
NEGATOR = neg_func
Ext
CLASS = class_name
ITERATOR
PARALLELIZABLE
C
HANDLESNULLS
INTERNAL
PERCALL_COST = cost
0
COSTFUNC = cost_func
SELFUNC = sel_func
SELCONST = selectivity
STACK = stack_size
Segments 4-275
Routine Modifier
You can add these modifiers in any order. If you list the same modifier more
than once, the last setting overrides previous values.
When you drop an existing modifier, the database server sets the value of the
modifier to the default value, if a default exists.
CLASS
COSTFUNC
HANDLESNULLS
INTERNAL
ITERATOR
NEGATOR
PARALLELIZABLE
PERCALL_COST
SELCONST
SELFUNC
STACK
VARIANT
NOT
Segments 4-277
Routine Modifier
Modifier Descriptions
The following sections describe the modifiers that you can use to help the
database server optimally execute a UDR.
EXT CLASS
Use the CLASS modifier to specify the name of a virtual-processor (VP) class
in which to run an external routine.
If you do not use the CLASS modifier to specify a VP class, the UDR runs in
the CPU VP.
Warning: Execution of an ill-behaved C UDR in the CPU VP can cause serious inter-
ference with the operation of the database server. In addition, the UDR itself might
not produce correct results. For a more detailed discussion of ill-behaved UDRs, see
the DataBlade API Programmer’s Manual. ♦
Java By default, a UDR written in Java runs in a Java virtual processor class (JVP).
Therefore, the CLASS routine modifier is optional for a a UDR written in Java.
However, Informix recommends that you use the CLASS routine modifier
when you register a UDR written in Java to improve readability of your SQL
statements. ♦
C COSTFUNC
Use the COSTFUNC modifier to specify the cost of a C UDR. The cost of the
UDR is an estimate of the time required to execute it.
Occasionally, the cost of a UDR depends on the inputs to the UDR. In that case,
you can use a user-defined function that calculates a cost that depends on the
input value.
C HANDLESNULLS
Use the HANDLESNULLS modifier to specify that a C UDR can handle null
values that are passed to it as arguments. If you do not specify
HANDLESNULLS for a C UDR, and if you pass an argument with a null value
to it, the C UDR does not execute and returns a null value.
SPL The HANDLESNULLS modifier is not available for SPL routines because SPL
routines handle null values by default. ♦
Ext INTERNAL
Use the INTERNAL modifier with an external routine to specify that an SQL
or SPL statement cannot call the external routine.
By default, an external routine is not internal; that is, an SQL or SPL statement
can call the routine.
Ext ITERATOR
Use the ITERATOR modifier with external functions to specify that the
function is an iterator function. An iterator function is a function that returns
a single element per function call to return a set of data; that is, it is called
with an initial call and zero or more subsequent calls until the set is complete.
Segments 4-279
Routine Modifier
E/C An iterator function requires a cursor. The cursor allows the client appli-
cation to retrieve the values one at a time with the FETCH statement. ♦
For more information on how to write iterator functions, see the DataBlade
API Programmer’s Manual.
NEGATOR
Use the NEGATOR modifier with user-defined functions that return Boolean
values.
Both functions take the same arguments, in the same order, but return
complementary Boolean values.
When it is more efficient to do so, the optimizer can use the negator function
instead of the function you specify.
To invoke a user-defined function that has a negator function, you must have
the Execute privilege on both functions. In addition, the function must have
the same owner as its negator function.
Ext PARALLELIZABLE
Use the PARALLELIZABLE modifier to indicate that an external routine can be
executed in parallel in the context of a parallelizable data query (PDQ)
statement.
If your UDR has a complex type as either a parameter or a return value, you
cannot use the parallelizable modifier.
C A C UDR that calls only PDQ thread-safe DataBlade API functions is parallel-
izable. The following categories of DataBlade API functions are PDQ thread
safe:
■ Data handling
An exception in this category is that collection manipulation
functions (mi_collection_*) are not PDQ thread safe.
■ Session, thread, and transaction management
■ Function execution
■ Memory management
■ Exception handling
■ Callbacks
■ Miscellaneous
For details of the DataBlade API functions included in each category, see the
DataBlade API Programmer’s Manual.
If your UDR calls a function that is not included in one of these categories, it
is not PDQ thread safe and therefore not parallelizable. ♦
Java To parallelize UDR calls, the database server must have multiple instances of
JVPs. UDRs written in Java that open a JDBC connection are not
parallelizable. ♦
C PERCALL_COST
Use the PERCALL_COST modifier to specify the approximate CPU usage cost
that a C UDR incurs each time it executes. The optimizer uses the cost you
specify to determine the order in which to evaluate SQL predicates in the UDR
for best performance.
Segments 4-281
Routine Modifier
For example, the following query has two predicates joined by a logical AND:
SELECT * FROM tab1 WHERE func1() = 10 AND func2() = 'abc';
In this example, if one predicate returns FALSE, the optimizer need not
evaluate the other predicate. The optimizer uses the cost you specify to order
the predicates so that the least expensive predicate is evaluated first.
The CPU usage cost must be an integer between 1 and 231-1, with 1 the
lowest cost and 231-1 the most expensive. To calculate an approximate cost
per call, add the following two figures:
■ The number of lines of code that execute each time the C UDR is
called
■ The number of predicates that require an I/O access
The default cost per execution is 0. When you drop the PERCALL_COST
modifier, the cost per execution returns to 0.
C SELCONST
Use the SELCONST modifier to specify the selectivity of a C UDR. The selec-
tivity of the UDR is an estimate of the fraction of the rows that will be selected
by the query. That is, the number of times the UDR will need to be executed.
C SELFUNC
Use the SELFUNC modifier with a C UDR to name a companion user-defined
function, called a selectivity function, to the current UDR. The selectivity
function provides selectivity information about the current UDR to the
optimizer.
The selectivity of a UDR is an estimate of the fraction of the rows that will be
selected by the query. That is, it is an estimate of the number of times the UDR
will execute.
Concept of Selectivity
Selectivity refers to the number of rows that would qualify for a query that
does a search based on an equality predicate. The fewer the number of rows
that qualify, the more selective the query.
For example, the following query has a search condition based on the
customer_num column in the customer table:
SELECT * FROM customer
WHERE customer_num = 102;
Since each row in the table has a different customer number, this is a highly
selective query.
Since most of the rows in the customer table are for customers in California,
more than half of the rows in the table would be returned.
A user who invokes the C UDR must have the Execute privilege both on that
UDR and on the selectivity function that the SELFUNC modifier specifies.
Both the C UDR and the selectivity function must have the same owner.
For information on C language macros that you can use to extract infor-
mation about the arguments to the selectivity function, see the DataBlade API
Programmer’s Manual.
Segments 4-283
Routine Modifier
C STACK
Use the STACK modifier with a C UDR to override the default stack size that
the STACKSIZE configuration parameter specifies.
The STACK modifier specifies the size of the thread stack, which a user thread
uses to hold information such as routine arguments and function return
values.
A UDR needs to have enough stack space for all its local variables. For a
particular UDR, you might need to specify a stack size larger than the default
size to prevent stack overflow.
When a UDR that includes the STACK modifier executes, the database server
allocates a thread-stack size of the specified number of bytes. Once the UDR
completes execution, subsequent UDRs execute in threads with a stack size
that the STACKSIZE configuration parameter specifies (unless any of these
subsequent UDRs have also specified the STACK modifier).
For more information about the thread stack, see your Administrator’s Guide
and the DataBlade API Programmer’s Manual.
C You can specify VARIANT or NOT VARIANT in this clause or in the EXTERNAL
Routine Reference. For more information, see “External Routine Reference”
on page 4-202. However, if you specify the modifier in both places, you must
use the same modifier in both clauses. ♦
Related Information
For more information on user-defined routines, see Extending Informix
Dynamic Server 2000 and the DataBlade API Programmer’s Manual.
For more information about how these modifiers can affect performance, see
your Performance Guide.
Segments 4-285
Routine Parameter List
Syntax
Function
Parameter List
Parameter
p. 4-287
, OUT Parameter
p. 4-287
Procedure
Parameter List
,
Parameter
p. 4-287
IDS In Dynamic Server, although you can use the Function Parameter List with a
CREATE PROCEDURE statement to write and register an SPL routine that
returns one or more values (that is, an SPL function), Informix recommends
that you use the Function Parameter List only with the CREATE FUNCTION
statement.
XPS In Extended Parallel Server, you can use the Function Parameter List with the
CREATE PROCEDURE statement because the database server does not
support the CREATE FUNCTION statement. ♦
Parameter
A parameter is one item in a Function Parameter List or Procedure Parameter
List.
REFERENCES BYTE
Usage
To define a parameter when creating a UDR, specify its name and its data
type. You can specify the data type directly or use the LIKE or REFERENCES
clause to identify the data type.
IDS The name is optional for external routines. ♦
Segments 4-287
Routine Parameter List
A UDR can define a parameter of any data type defined in the database,
except SERIAL, SERIAL8, TEXT, BYTE, CLOB, or BLOB.
Java Complex types are not yet allowed as parameter data types for UDRs written
in Java. ♦
For more information on data types, see “Data Type” on page 4-53.
You cannot create another user-defined procedure named cost() in the same
database with two arguments. However, you can create a user-defined
procedure named cost() with a number of arguments other than two.
To circumvent this restriction with the LIKE clause, you might want to use
user-defined data types to achieve the same purpose.
If you use the DEFAULT NULL option in the REFERENCES clause, and you call
the UDR without a parameter, a null value is used.
XPS In Extended Parallel Server, to recreate this example use the CREATE
PROCEDURE statement instead of the CREATE FUNCTION statement.
Segments 4-289
Routine Parameter List
Warning: When you specify a date value as the default value for a parameter, make
sure to specify 4 digits instead of 2 digits for the year. When you specify a 4-digit year,
the DBCENTURY environment variable has no effect on how the database server
interprets the date value. When you specify a 2-digit year, the DBCENTURY
environment variable can affect how the database server interprets the date value, so
the UDR might not use the default value that you intended. For more information on
the DBCENTURY environment variable, see the “Informix Guide to SQL:
Reference.”
Once you register a user-defined function with an OUT parameter, you can
use the function with a statement-local variable (SLV) in an SQL statement.
You can only mark one parameter as OUT, and it must be the last parameter.
If you specify an OUT parameter, and you use Informix-style parameters, the
argument is passed to the OUT parameter by reference. The OUT parameter
is not significant in determining the routine signature.
Java For example, the following declaration of a Java method allows you to return
an extra value by passing an array:
Segments 4-291
Shared-Object Filename
Syntax
C C Shared-Object File
C C Shared-Object File
To specify the location of a C shared-object file, specify the path to the
executable file within a quoted pathname or a variable that holds the full
pathname of the executable file.
You can omit a pathname, and enter just a filename, if you want to refer to an
internal function.
A relative pathname need not begin with a period, and is relative to the
current directory at the time the CREATE or ALTER statement is run.
If you use a symbol, it refers to an optional entry point in the executable object
file. Use a symbol only if the entry point has a name other than the name of
the UDR that you are registering.
Segments 4-293
Shared-Object Filename
package_id .
( ) RETURNS java_type
,
java_type
Before you can create a UDR written in Java, you must assign a jar identifier
to the external jar file with the sqlj.install_jar procedure. For more infor-
mation, see “sqlj.install_jar” on page 2-447.
You can include the Java signature of the method that implements the UDR in
the shared-object filename.
■ If you do not specify the Java signature, the routine manager deter-
mines the implicit Java signature from the SQL signature in the
CREATE FUNCTION or CREATE PROCEDURE statement.
It maps SQL data types to the corresponding Java data types with the
JDBC and SQL-to-Java mappings. For information on mapping user-
defined data types to Java data types, see “sqlj.setUDTExtName” on
page 2-453.
■ If you do specify the Java signature, the routine manager uses this
explicit Java signature as the name of the Java method to use.
Segments 4-295
Specific Name
Syntax
specific_id
owner .
Usage
A specific name is a unique identifier that you define in a CREATE
PROCEDURE or CREATE FUNCTION statement to serve as an alternative name
for a UDR.
Because you can overload routines, a database can have more than one UDR
with the same name and different parameter lists. You can assign a UDR a
specific name that uniquely identifies the specific UDR.
If you give a UDR a specific name when you create it, you can later use the
specific name when you alter, drop, grant or revoke privileges, or update
statistics on that UDR. Otherwise, you need to include the parameter data
types with the UDR name if the name alone does not uniquely identify the
UDR.
When you do not specify an owner name, the database server uses the user
ID of the person creating the UDR. Therefore, if you specify the owner name
in one location and not the other, the owner name that you specify must
match your user ID.
ANSI In an ANSI-compliant database, you can use the same specific identifier for
two UDRs within the same database if the UDRs have different owners. The
combination owner.specific_id must be unique. In other words, the specific
name of the UDR must be unique for the owner.
Segments 4-297
Statement Block
Statement Block
Use a statement block to specify the operations to take place when the SPL
routine is called. Use the statement block segment whenever you see a
reference to statement block in a syntax diagram.
Syntax
EXECUTE FUNCTION
IDS Statement
p. 2-434
DEFINE ON EXCEPTION
Statement Statement
p. 3-11 p. 3-45 EXECUTE PROCEDURE
Statement
p. 2-444
Subset of
SPL Statements
p. 4-300
Subset of
SQL Statements ;
p. 4-299
Usage
If the statement block portion of the statement is empty, no operation takes
place when you call the SPL routine.
Warning: When you specify a date value in an expression in any statement in the
statement block, make sure to specify 4 digits instead of 2 digits for the year. When
you specify a 4-digit year, the DBCENTURY environment variable has no effect on
how the database server interprets the date value. When you specify a 2-digit year,
the DBCENTURY environment variable can affect how the database server interprets
the date value, so the routine might produce unpredictable results. For more infor-
mation on the DBCENTURY environment variable, see the “Informix Guide to SQL:
Reference.”
The following table lists the SQL statements that are not allowed in an SPL
routine.
ALLOCATE COLLECTION EXECUTE
ALLOCATE DESCRIPTOR EXECUTE IMMEDIATE
ALLOCATE ROW FETCH
CLOSE FLUSH
CLOSE DATABASE FREE
CONNECT GET DESCRIPTOR
CREATE DATABASE INFO
CREATE FUNCTION LOAD
CREATE FUNCTION FROM OPEN
CREATE PROCEDURE OUTPUT
CREATE PROCEDURE FROM PREPARE
DATABASE PUT
DEALLOCATE COLLECTION SET CONNECTION
DEALLOCATE DESCRIPTOR SET DESCRIPTOR
DEALLOCATE ROW UNLOAD
DECLARE UPDATE STATISTICS
DESCRIBE WHENEVER
DISCONNECT
For example, you cannot close the current database or select a new database
within an SPL routine. Likewise you cannot drop the current SPL routine
within the routine. You can, however, drop another SPL routine.
Segments 4-299
Statement Block
■ You can use the INTO TEMP clause to put the results of the SELECT
statement into a temporary table.
■ You can use the SELECT... INTO form of the SELECT statement to put
the resulting values into SPL variables.
You can use any of the following SPL statements in the statement block:
CALL LET
CONTINUE RAISE EXCEPTION
EXIT RETURN
FOR SYSTEM
FOREACH TRACE
IF WHILE
BEGIN
DEFINE var1 INT; -- same name as global parameter.
LET var1 = var2;
INSERT INTO tracker (who_submitted, value)
VALUES ('var1 var defined inside the "IF/BEGIN".', var1);
END
This example defines three independent variables, two of which are named
var1. (The example uses two different variables with the same name to illus-
trate how a statement block limits the scope of a variable. In general, using
the same name for different variables is not a good idea.)
Segments 4-301
Statement Block
Because of the statement block, only one var1 variable is in scope at a time.
The var1 variable that is defined inside the statement block is the only var1
variable that can be referenced from within the statement block.
The var1 variable that is defined outside the statement block can not be refer-
enced from within the statement block. Because this variable is out of scope,
it is unaffected by the change in value to the var1 variable that takes place
inside the BEGIN-END statement block. After all the statements run, the outer
var1 still has a value of 1.
The var2 variable shows that an inner statement block does not lose access to
outer variables that were not explicitly superseded. The outer variable var2
is still in scope from within the statement block because it was not super-
seded by a block-specific variable.
However, if the SPL routine is called within a statement that is not a data
manipulation statement (namely EXECUTE FUNCTION or EXECUTE
PROCEDURE), the routine can execute any statement that does not appear in
the list that appears in “SQL Statements Not Allowed in the Statement Block”
on page 4-299.
For further information about roles, see the CREATE ROLE, DROP ROLE,
GRANT, REVOKE, and SET ROLE statements.
Segments 4-303
Appendix
D
DIRTY
DISABLED
DATABASE
DISCONNECT
DATAFILES
DISTINCT
DATASKIP
DISTRIBUTIONS
DATE
DOCUMENT
DATETIME
DOMAIN
DAY
DORMANT
DBA
DOUBLE
dbDATE
DROP
DBMONEY
DTIME_T
DBPASSWORD
DEALLOCATE E
DEBUG EACH
DEC ELIF
DEC_T ELSE
DECIMAL ENABLED
DECLARE END
DECODE ENUM
DEFAULT ENVIRONMENT
J
LVARCHAR
JOIN M
K
MATCHES
MAX
KEEP
MAXERRORS
KEY
MAXLEN
L
MDY
LABELEQ
MEDIAN
LABELGE
MEDIUM
LABELGLB
MEMORY_RESIDENT
LABELGT
MIDDLE
LABELLE
MIN
LABELLT
MINUTE
N
ORDER
OUT
NAME
OUTER
NCHAR
NEGATOR P
NEW PAGE
NEXT PARALLELIZABLE
NO PARAMETER
NON_RESIDENT PASCAL
NONE PASSEDBYVALUE
NORMAL PDQPRIORITY
NOT PERCALL_COST
NOTEMPLATEARG PLI
NULL PLOAD
NUMERIC PRECISION
NVARCHAR PREPARE
NVL PREVIOUS
O
PRIMARY
PRIOR
OCTET_LENGTH
PRIVATE
OF
PRIVILEGES
OFF
PROCEDURE
OLD
PUBLIC
ON
PUT
R ROLLFORWARD
RAISE ROUND
RANGE ROUTINE
RAW ROW
READ ROWID
REAL ROWIDS
RECORDEND ROWS
REF
S
REFERENCES
SAMEAS
REFERENCING
SAMPLES
REGISTER
SCHEDULE
REJECTFILE
SCHEMA
RELATIVE
SCRATCH
RELEASE
SCROLL
REMAINDER
SECOND
RENAME
SECONDARY
REOPTIMIZATION
SECTION
REPEATABLE
SELCONST
REPLICATION
SELECT
RESERVE
SELFUNC
RESOLUTION
SERIAL
RESOURCE
SERIAL8T
RESTRICT
SERIALIZABLE
RESUME
SESSION
RETAIN
SET
RETURN
SHARE
RETURNING
SHORT
RETURNS
SIGNED
REVOKE
SIZE
ROBIN
SKALL
ROLE
SKINHIBIT
ROLLBACK
W
WAIT
WARNING
WHEN
WHENEVER
WHERE
WHILE
WITH
WITHOUT
WORK
WRITE
X
xLOAD
XUNLOAD
Y
YEAR
B CONTINUE
BEFORE COPY
BEGIN COUNT
BETWEEN CREATE
BITMAP CURRENT
BOTH CURSOR
BUFFERED D
BY DATABASE
BYTE DATAFILES
C DATASKIP
CACHE DATE
CALL DATETIME
CASCADE DAY
CASE DBA
CHAR dbDATE
CHAR_LENGTH DBMONEY
DEBUG
I LOW
IF M
IMMEDIATE MATCHES
IN MAX
INDEX MAXERRORS
INDICATOR MEDIUM
INIT MEMORY_RESIDENT
INSERT MIDDLE
INT MIN
INTEGER MINUTE
INTERVAL MODE
INTO MODIFY
IS MODULE
ISOLATION MONEY
K MONTH
KEY MOUNTING
N
L
LABELEQ NCHAR
LABELGE NEW
LABELGT NEXT
LABELLE NO
LABELLT NON_RESIDENT
LANGUAGE NORMAL
LEADING NOT
LET NULL
W
WAIT
WHEN
WHENEVER
WHERE
WHILE
WITH
WORK
WRITE
X
xLOAD
XUNLOAD
Y
YEAR
Index
Index
Index 3
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z @
FOR EACH with 3-33 associating cursor with 2-367 Column name
in SPL 3-33 cursor for 2-466 dot notation 4-93
inserting into 2-466, 2-599 deallocating memory for 2-343 using functions as names 4-211
opening 2-571 describing 2-386 using keywords as names 4-212
Collection data type 4-69 in SELECT statement 2-657 when qualified 2-318
deleting 2-380 manipulating values 4-16 Column value
element, searching for with opening a cursor 2-571 in triggered action 2-320
IN 4-35 selecting from 2-656 qualified vs. unqualified 2-320
IN operator 4-35 selecting, inserting when unqualified 2-320
loading 2-560 elements 2-367 COLUMNS keyword, in INFO
MULTISET 4-69 updating 4-16 statement 2-532
returning number of Collections COMBINE keyword, in CREATE
elements 4-129 accessing elements 4-11 AGGREGATE statement 2-115
selecting from 2-656 deleting elements from 2-380 Command file
unloading 2-806 generating values for 4-118 comment symbols in 1-7
updating 4-16 inserting values into 2-544 defined 1-7
Collection derived table 4-9 restrictions when accessing Comment icons Intro-12
collection cursor 2-466, 2-599 elements 4-11 Comment symbol
collection variables with 4-15 restrictions when defining 4-70 braces ({}) 1-7
INSERT statement with 2-370, restrictions with inserting null double dash (--) 1-7
2-551 values 2-545 examples of 1-8
row types in 4-13 selecting from 2-657 how to enter 1-6
row variables with 4-22 specifying literal values 4-228 in application programs 1-8
SELECT statement with 2-656, updating 2-828 in command file 1-7
4-15 Column in prepared statements 2-582
SELECT with, fields from row adding 2-59 in SPL routine 1-7
variable 2-658 adding a NOT NULL in SQL APIs 1-8
TABLE keyword 4-11, 4-15, 4-22 constraint 2-75 COMMIT keyword, in TRUNCATE
UPDATE row variable with 2-832 as an expression 2-640, 4-91 statement 2-802
UPDATE statement with 4-15, changing the data type 2-75 COMMIT WORK statement
4-22 defining as primary key 2-240 in ANSI-compliant
where allowed 4-22 dropping 2-69, 2-70 databases 2-101
COLLECTION keyword, in inserting into 2-537 in non-ANSI databases 2-101
DEFINE statement 3-11 modifying with ALTER syntax 2-100
Collection Subquery TABLE 2-72 COMMITTED READ keywords, in
creating a multiset collection 4-24 number, effect on triggers 2-301 SET ISOLATION
example 4-26 primary or foreign key 2-240 statement 2-736
restrictions 4-25 privileges 2-507 Compare support function 2-191
resulting row structure 4-25 projection 4-93 Complex data type
where used 4-25 referenced and referencing 2-242 loading element values 2-560
Collection types removing a NOT NULL unloading 2-811
defining a column 4-69 constraint 2-75 Compliance
LIST 4-70 renaming 2-604 icons Intro-14
MULTISET 4-69 specifying a subscript 2-676, 4-97 with industry standards Intro-22
SET 4-69 specifying check constraint Compound assignment 3-42
Collection variable for 2-136, 2-245 Concatenation operator (||) 4-73,
accessing 4-15 virtual 2-337 4-87
accessing values 4-15 Column definition clause 2-233
allocating memory for 2-6
Index 5
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z @
Index 7
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z @
in DEFINE statement 3-16 Cursor function 3-31, 4-272 default isolation levels 2-738,
in expression 4-108 CURSOR keyword, in DECLARE 2-772
in INSERT statement 2-541, 2-547 statement 2-349 dropping 2-397
in WHERE condition 4-113 CURSOR STABILITY keywords, in lock 2-342
CURRENT keyword SET ISOLATION naming conventions 4-48
in DELETE statement 2-373 statement 2-736 naming with variable 4-49
in DISCONNECT opening in exclusive mode 2-342
statement 2-389 optimizing queries 2-836
in FETCH statement 2-455 D remote 4-49
in SET CONNECTION renaming 2-606
Data
statement 2-694 Database administrator
access statements 1-11
in UPDATE statement 2-815, (DBA) 2-504
definition statements 1-10
2-831 privileges
inserting with the LOAD 2-553
Cursor granting 2-501
integrity statements 1-11
activating with OPEN 2-566 revoking 2-611
manipulation statements 1-10
affected by transaction end 2-96 Database Name segment
Data distributions
characteristics 2-360 for remote database 4-49
confidence 2-841
closing 2-94 naming conventions 4-47
on temporary tables 2-836
closing with ROLLBACK naming with variable 4-49
RESOLUTION 2-841
WORK 2-632 syntax 4-47
DATA field
declaring 2-349 Database object
in GET DESCRIPTOR
for update naming 4-50
statement 2-476
restricted statements 2-363 naming owner 4-257
in SET DESCRIPTOR
using in ANSI-mode Database object mode
statement 2-722
databases 2-364, 2-365 for triggers 2-332
with DESCRIBE statement 2-385
using in non-ANSI in SET Database Object Mode
DATA keyword. See DATA field.
databases 2-364, 2-365 statement 2-703
Data replication 2-58
freeing automatically with SET privileges required 2-700
Data type 4-53
AUTOFREE 2-691 Database Object Name
casting 2-119, 4-89
manipulation statements 1-10 segment 4-50
changing with ALTER
opening 2-568 DATABASE statement
TABLE 2-75
optimization statements 1-11 determining database type 2-342
collection 4-69
prepared statement with 2-366 exclusive mode 2-342
complex 4-67
read-only specifying current database 2-341
considerations for INSERT 2-543,
restricted statements 2-363 SQLWARN after 2-342
4-264
using in ANSI-mode syntax 2-341
distinct 4-67
databases 2-364, 2-365 Database-level privilege
opaque 2-186
using in non-ANSI passing grant ability 2-520
simple large object 4-63
databases 2-364, 2-365 See also Privilege.
specifying with CREATE
retrieving values with DATAFILES keyword
VIEW 2-335
FETCH 2-455 in CREATE EXTERNAL TABLE
See also each data type listed
select hold examples 2-362 statement 2-137
under its own name.
sequence of program Dataskip, skipping unavailable
Data Type segment 4-53
operations 2-354 dbspaces 2-709
Database
statement identifier with 2-366 DATE data type
closing with CLOSE
statement, as trigger event 2-299 defined 4-65
DATABASE 2-98
with INTO keyword in functions in 4-152
creating with CREATE
SELECT 2-647 DATE function 4-152, 4-154
DATABASE 2-124
with transactions 2-371
Index 9
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z @
Index 11
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z @
deallocating row variable INTO SQL DESCRIPTOR in ALTER TABLE statement 2-78
memory 2-347 clause 2-428 in CREATE TABLE
inserting collection variables parameterizing a statement 2-430 statement 2-273, 2-276
with 2-544 syntax 2-422 Extent, revising the size 2-84
inserting row variables 2-547 USING DESCRIPTOR External function
EXCEPTION keyword clause 2-432 as operator-class strategy
in GET DIAGNOSTICS with USING keyword 2-430 function 2-196
statement 2-491 EXISTS keyword as operator-class support
EXCLUSIVE keyword beginning a subquery 2-665 function 2-197
in DATABASE statement 2-341 in Condition segment 4-42 CREATE FUNCTION 2-152
in LOCK TABLE statement 2-563 in Condition subquery 4-42 dropping 2-399
Executable file location 4-292 EXIT statement 3-24 executing 2-434, 2-583
EXECUTE FUNCTION keywords EXP function 4-141 limits on return values 4-271
in CREATE TRIGGER EXPLICIT keyword, in CREATE non-variant 4-203
statement 2-315 CAST statement 2-119 OUT parameter 4-183
in DECLARE statement 2-349 Exponential function 4-141 registering 2-152
in INSERT statement 2-550 Export support function 2-191, variant 4-203
in Statement Block segment 4-298 2-808 EXTERNAL keyword
EXECUTE FUNCTION keywords Exportbinary support in CREATE EXTERNAL TABLE
in FOREACH statement 3-30 function 2-191, 2-808 statement 2-132
EXECUTE FUNCTION statement EXPRESS keyword, in CREATE in External Routine Reference
and triggers 2-316 EXTERNAL TABLE segment 4-202
how it works 2-435 statement 2-139 in SELECT statement 2-683
INTO clause 2-436 Expression EXTERNAL NAME keywords
preparing 2-439 boolean 4-28, 4-30 in ALTER FUNCTION
syntax 2-434 casting 4-89 statement 2-41
EXECUTE IMMEDIATE statement list of 4-76 in ALTER PROCEDURE
restricted statement types 2-442 ordering by 2-678 statement 2-48
syntax 2-441 smart large objects in 4-98 in ALTER ROUTINE
EXECUTE ON keywords EXPRESSION keyword statement 2-51
in GRANT statement 2-513 in ALTER FRAGMENT External procedure
in REVOKE statement 2-620 statement 2-30, 2-33 creating body of 2-206
EXECUTE PROCEDURE keywords in CREATE INDEX executing 2-583
in CREATE TRIGGER statement 2-175 External routine
statement 2-315 in CREATE TABLE as triggered action 2-316
in DECLARE statement 2-349 statement 2-259 CREATE PROCEDURE FROM
in FOREACH statement 3-30 Expression segment statement in 2-210
in INSERT statement 2-550 aggregate expressions 4-185 creating a function in 2-155
in Statement Block segment 4-298 cast expressions 4-88 definition 2-202
EXECUTE PROCEDURE statement column expressions 4-91 pathname syntax 4-292
in FOREACH 3-30 combined expressions 4-85 preparing 2-583
in triggered action 2-316 list of expressions 4-76 referencing 4-202
syntax 2-444 syntax 4-73 External Routine Reference
EXECUTE statement EXTEND function 4-152, 4-156 segment 4-202
and sqlca record 2-424 Extension to SQL, symbol External routine reference,
error conditions with 2-424 for Intro-14 example 4-203
INTO clause 2-425 EXTENT keyword External table
INTO DESCRIPTOR clause 2-428 in ALTER TABLE statement 2-78 creating 2-131
EXTENT SIZE keywords integer data types 2-133
Index 13
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z @
Functional index, in composite SIN 4-161 GLS. See Global Language Support.
index 2-164 SITENAME 4-111 GL_DATE environment
Function, SQL SQRT 4-128 variable 2-555, 2-806
ABS 4-125 STDEV 4-196 GL_DATETIME environment
ACOS 4-161 SUBSTR 4-168 variable 2-556, 2-807
ASIN 4-161 SUM 4-195 GO TO keywords, in WHENEVER
ATAN 4-161 TAN 4-161 statement 2-848
ATAN2 4-162 Time 4-152 GRANT FRAGMENT statement
AVG 4-194 TODAY 4-112 AS grantor clause 2-530
CARDINALTY 4-129 TO_CHAR 4-157 syntax 2-523
CASE expression 4-100 TRIM function 4-121 WITH GRANT OPTION
CHARACTER_LENGTH 4-145 TRUNC 4-128 clause 2-529
CHAR_LENGTH 4-145 UPPER 4-174 GRANT keyword
COS 4-160 USER 4-110 in GRANT FRAGMENT
COUNT 4-189 VARIANCE 4-196 statement 2-523
CURRENT 4-112 WEEKDAY 4-155 in GRANT statement 2-500
DAY 4-155 Function, user-defined GRANT statement
DBSERVERNAME 4-111 definition 2-201 ALL keyword 2-508
DECODE 4-105 changing grantor 2-521
EXP 4-141 column-specific privileges 2-507
Exponential 4-141 G database-level privileges 2-502
EXTEND 4-156 EXECUTE ON (user-defined
Generalized-key index
FILETOBLOB 4-147 routine) 2-513
affected by dropping a
FILETOCLOB 4-147 passing grant ability 2-520
column 2-72
HEX 4-142 role name and privileges 2-518
affected by modifying a
IFX_REPLACE_MODULE 4-145 table-level privileges 2-505
column 2-77
INITCAP 4-174 UNDER keyword 2-507, 2-512
description of 2-182
LENGTH 4-144 USAGE ON LANGUAGE
SELECT clause 2-183
LOCOPY 4-150 clause 2-516
WHERE clause 2-185
LOG10 4-142 USAGE ON (user-defined data
GET DESCRIPTOR statement
Logarithmic 4-141 type) 2-511
syntax 2-475
LOGN 4-142 view name and privileges 2-510
use with FETCH statement 2-463
LOTOFILE 4-149 WITH GRANT OPTION
GET DIAGNOSTICS statement
LOWER 4-174 keywords 2-520
exception clause 2-491
LPAD 4-172 greaterthanorequal() operator
SQLSTATE codes 2-485
MAX 4-194 function 4-266
syntax 2-483
MDY 4-157 greaterthan() operator
GK INDEX keywords
MIN 4-194 function 4-266
in CREATE INDEX
MOD 4-126 GROUP BY keywords, in SELECT
statement 2-157
MONTH 4-155 statement 2-669
GK index. See Generalized-key
NVL 4-104
index.
OCTET_LENGTH 4-144
Global environment variable,
POW 4-126
definition 3-14
H
RANGE 4-195
GLOBAL keyword, in DEFINE HANDLESNULLS keyword
ROOT 4-126
statement 3-11 in CREATE AGGREGATE
ROUND 4-127
Global Language Support statement 2-115
RPAD 4-173
(GLS) Intro-4 in Routine Modifier
segment 4-275, 4-277
Index 15
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z @
Index 17
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z @
INTEGER data type 4-59 ISAM error code 3-45, 3-50 sqlj.unsetUDTExtName
Integers, in external tables 2-133 ISO 8859-1 code set Intro-4 procedure 2-454
Integrity. See Data integrity. Isolation level unmapping a user-defined
INTERNAL keyword, in Routine definitions 2-737, 2-770 type 2-454
Modifier segment 4-275, 4-277 use with FETCH statement 2-465 Java Virtual Processor Class
INTERNALLENGTH keyword, in ISOLATION LEVEL keywords, in getting memory
CREATE OPAQUE TYPE SET TRANSACTION information 2-440
statement 2-186 statement 2-768 getting thread information 2-440
INTERVAL data type Item descriptor, defined 2-9 JDBC Driver built-in function 2-439
as quoted string 4-263 ITEM keyword, in Collection Join
field qualifier, syntax 4-223 Subquery segment 4-24 in Condition segment 2-666
in expression 4-114 ITER keyword, in CREATE in DELETE statement 2-378
in INSERT 4-264 AGGREGATE 2-115 in UPDATE statement 2-829
loading 2-556 iterator function 4-279 multiple-table join 2-668
syntax 4-65, 4-234 ITERATOR keyword, in Routine outer 2-652, 2-669
INTERVAL keyword Modifier segment 4-275, 4-277 self-join 2-668
in Literal INTERVAL ITYPE field two-table join 2-668
segment 4-234 in GET DESCRIPTOR Join column. See Foreign key.
INTO DESCRIPTOR keywords statement 2-476 Join on key query 2-184
in EXECUTE 2-428 in SET DESCRIPTOR Joins
INTO EXTERNAL keywords, in statement 2-722 in UPDATE statement 2-830
SELECT statement 2-686 with X/Open programs 2-479 jvpcontrol function 2-439
INTO keyword ITYPE keyword. See ITYPE field. JVP. See Java Virtual Processor
in DESCRIBE statement 2-382 Class.
in EXECUTE FUNCTION
statement 2-436 J
in EXECUTE PROCEDURE
JAVA keyword
K
statement 2-444
in External Routine Reference KEEP ACCESS TIME keywords
in EXECUTE statement 2-425
segment 4-202 in ALTER TABLE statement 2-78
in FETCH statement 2-455
in GRANT statement 2-516 in CREATE TABLE
in FOREACH statement 3-30
in REVOKE statement 2-622 statement 2-273
in INSERT statement 2-535
Java UDRs 2-447, 2-450, 2-451 KEEP keyword, in ALTER TABLE
in LOAD statement 2-553
CLASS routine modifier 4-278 statement 2-78
INTO keyword, in SELECT
creating functions 2-152 Keyword
statement 2-645
creating procedures 2-206 formatting conventions Intro-11
INTO SCRATCH keywords, in
Getting JVP memory Keyword. See also Reserved words.
SELECT statement 2-686
information 2-440
INTO SQL DESCRIPTOR keywords
Getting JVP thread
in EXECUTE statement 2-428
INTO TEMP clause
information 2-440 L
installing a Jar file 2-447
in SELECT statement 2-684 LANGUAGE keyword
jvpcontrol function 2-439
with UNION operator 2-689 in External Routine Reference
removing a Jar file 2-450
IS keyword segment 4-202
replacing a Jar file 2-449
in Condition segment 4-28 in GRANT statement 2-516
sqlj.alter_java_path
in WHERE clause 2-663 in REVOKE statement 2-622
procedure 2-451
IS NOT NULL keywords, in Language, privileges on 2-516,
sqlj.replace_jar procedure 2-449
Condition segment 4-36 2-622
sqlj.setUDTExtName
IS NULL keywords, in Condition
procedure 2-453
segment 4-36
Index 19
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z @
Index 21
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z @
Index 23
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z @
Index 25
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z @
enabling with SET ROLE 2-758 NEGATOR 4-280 selecting from 2-658
establishing with CREATE, NOT VARIANT 4-284 updating 2-832
GRANT, SET 2-519 PARALLELIZABLE 4-280 Rowid
granting name with PERCALL_COST 4-281 adding column with INIT
GRANT 2-519 SELCONST 4-282 clause 2-29
granting privileges with SELFUNC 4-282 adding with ALTER TABLE 2-58
GRANT 2-520 STACK 4-284 dropping from fragmented
revoking privileges with VARIANT 4-284 tables 2-58
REVOKE 2-624 Row use in a column expression 4-98
scope of 2-759 deleting 2-373 use in fragmented tables 2-29
setting with SET ROLE 2-758 engine response to locked used as column name 4-214
ROLLBACK WORK statement row 2-743 ROWID keyword, in Expression
syntax 2-632 finding location of 4-98 segment 4-91
with WHENEVER 2-91, 2-99, inserting ROWIDS keyword
2-633 through a view 2-538 in ALTER FRAGMENT
ROOT function 4-123, 4-126 with a cursor 2-539 statement 2-27
ROUND function 4-123, 4-127 order, guaranteeing in CREATE TABLE
ROUND ROBIN keywords independence of 2-309 statement 2-259
in ALTER FRAGMENT retrieving with FETCH 2-460 ROWS keyword, in START
statement 2-30 rowid definition 2-460 VIOLATIONS TABLE
in CREATE TABLE updating through a view 2-817 statement 2-778
statement 2-259 writing buffered rows with Row-type columns, generating
Routine FLUSH 2-469 values for 4-116
as triggered action 2-326 ROW constructor, in Expression ROW_COUNT keyword, in GET
checking references 2-326 segment 4-116 DIAGNOSTICS
creating with CREATE ROUTINE ROW keyword statement 2-489
FROM 2-214 in ALTER TABLE statement 2-85 RPAD function 4-173
dropping with DROP in CREATE TABLE R-tree index
ROUTINE 2-408 statement 2-278 creating 2-170
modifying in CREATE TRIGGER default operator class 2-198
path to executable file 2-53 statement 2-307, 2-314 rtree_ops operator class 2-198
routine modifiers 2-52 in Expression segment 4-116 uses 2-170
privileges 2-202 in Literal Row segment 4-239 rtree secondary access
rules with triggers 2-326 Row type method 2-170
specific name 4-296 constructor syntax 4-116
ROUTINE keyword dot notation with 4-93
in DROP ROUTINE in collection-derived tables 4-13 S
statement 2-408 loading field values 2-556, 2-560
sales_demo database Intro-5
in GRANT statement 2-513 nested 4-243
SAMEAS keyword, in CREATE
in REVOKE statement 2-620 selecting fields 2-643, 2-658
EXTERNAL TABLE
in UPDATE STATISTICS selecting from 2-658
statement 2-132
statement 2-844 unloading 2-807, 2-811
Sample-code conventions Intro-19
Routine modifier updating 2-826, 2-832
SAMPLES OF keywords, in
CLASS 4-278 Row variable
SELECT statement 2-655
COSTFUNC 4-279 accessing 4-22
Sampling data 2-655
HANDLESNULLS 4-279 allocating memory for 2-10
sbspace
INTERNAL 4-279 deallocating memory for 2-347
specifying in ALTER TABLE 2-78
ITERATOR 4-279 inserting 2-546
specifying in CREATE
inserting into 2-551
TABLE 2-273
Index 27
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z @
Serial column table-mode format 2-701 SET PLOAD FILE statement 2-755
nonsequential numbers in 2-264 with CREATE TRIGGER SET Residency statement 2-756
resetting values 2-74 statement 2-329 SET ROLE statement 2-758
use with hash data manipulation SET SCHEDULE LEVEL
fragmentation 2-264 statements 2-704 statement 2-760
SERIAL data type SET DATASKIP statement 2-709 SET SESSION AUTHORIZATION
inserting values 2-543 SET DEBUG FILE TO statement statement 2-761
length 4-60 syntax 2-712 SET TABLE. See SET Residency
resetting values 2-74, 2-544 with TRACE statement 3-58 statement.
value range 4-60 SET DEFERRED_PREPARE SET Transaction Mode
SERIAL8 data type statement 2-715 statement 2-774
inserting values 2-543 SET DESCRIPTOR statement SET TRANSACTION statement
value range 4-60 the VALUE clause 2-721 default database levels 2-772
SERIALIZABLE keyword, in SET X/Open mode 2-725 effects of isolation 2-773
TRANSACTION SET EXPLAIN statement 2-733 similarities to SET ISOLATION
statement 2-768 SET INDEXES. See SET Database statement 2-769
SERVER_NAME keyword, in GET Object Mode statement. syntax 2-768
DIAGNOSTICS SET INDEX. See SET Residency SET TRIGGERS. See SET Database
statement 2-491 statement. Object Mode statement.
Session control block SET ISOLATION statement setnet32 2-109
accessed by DBINFO default 2-738 SHARE keyword, in LOCK TABLE
function 4-135 definition of isolation statement 2-563
defined 4-135 levels 2-737, 2-770 Shared library functions 4-145
Session ID, returned by DBINFO effects of isolation 2-740 Side-effect index 2-197
function 4-135 similarities to SET Simple assignment, in SPL 3-42
SET data type TRANSACTION Simple large object
See also Collections. statement 2-769 assigning to a column 4-62
SET AUTOFREE statement 2-691 syntax 2-736 loading 2-556, 2-558
SET columns, generating values SET keyword Simple large-object
for 4-118 in DEFINE statement 3-18 unloading 2-807, 2-809
SET CONNECTION in Expression segment 4-118 SIN function 4-159, 4-161
statement 2-694 in Literal Collection Single-threaded application 2-696
SET CONSTRAINTS. See SET segment 4-227 Singleton SELECT statement 2-646
Database Object Mode in ON EXCEPTION SITENAME function
statement and SET Transaction statement 3-45 in ALTER TABLE statement 2-60
Mode statement. in UPDATE statement 2-819 in Condition segment 4-34
SET data type SET LOCK MODE statement in CREATE TABLE
definition of 4-118 setting wait period 2-743 statement 2-234
deleting elements from 2-380 syntax 2-742 in DEFINE statement 3-16
unloading 2-806 SET LOG statement 2-745 in Expression segment 4-111
updating elements in 2-832 SET OPTIMIZATION statement See DBSERVERNAME function.
SET Database Object Mode ALL_ROWS option 2-748 SIZE keyword
statement FIRST_ROWS option 2-748 in ALTER TABLE statement 2-84
error options 2-706 HIGH option 2-748 in CREATE EXTERNAL TABLE
list-mode format 2-702 LOW option 2-748 statement 2-139
relationship to START syntax 2-747 in CREATE TABLE
VIOLATIONS TABLE 2-780 SET PDQPRIORITY statement 2-273, 2-276
syntax 2-700 statement 2-751 in TRUNCATE statement 2-802
Index 29
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z @
Index 31
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z @
Subquery Synonym
beginning with ALL, ANY, SOME ANSI-compliant naming 2-227 T
keywords 2-665 chaining 2-228 Table
beginning with EXISTS creating 2-226 adding a constraint 2-80, 2-81
keyword 2-665 difference from alias 2-226 adding a constraint to a column
beginning with IN dropping 2-412 with data 2-76
keyword 2-664 Syntax 2-48 alias in SELECT 2-650
correlated 4-41 Syntax conventions consumed 2-16
definition of 2-661 description of Intro-14 creating 2-230
in Condition segment 4-40 example diagram Intro-18 creating a synonym for 2-226
restrictions with UNION icons used in Intro-15 defining fragmentation
operator 2-689 Syntax diagrams, elements strategy 2-259
with DISTINCT keyword 2-640 in Intro-15 diagnostic 2-793
Subscripting, on character System catalog dropping 2-413
columns 2-676, 4-97 database entries 2-124 dropping a synonym 2-412
SUBSTR function 4-168 dropping tables 2-415 dropping a system table 2-415
Substring sysdepend 2-420 engine response to locked
in column expression 4-97 systabauth 2-522 table 2-743
in ORDER BY clause of sysxtdtypes 2-186 external 2-131, 2-686
SELECT 2-676 user-defined function isolating 2-257
SUBSTRING function 4-170, 4-172, information 2-151 joins in Condition segment 2-666
4-173 user-defined procedure loading data with the LOAD
Subtable, inherited information 2-205 statement 2-553
properties 2-282 System descriptor area locking
SUM function 4-185, 4-195 assigning values to 2-719 with ALTER INDEX 2-45
superstores_demo database Intro-5 item descriptors in 2-9 with LOCK TABLE 2-563
Support function OPEN using 2-431, 2-573, 2-598 logging 2-287
assigning 2-191, 2-544, 2-560, resizing 2-721 memory-resident 2-756
2-829 use with EXECUTE name, specifying 4-50
comparing 2-191 statement 2-432 privileges
defining 2-190 with DESCRIBE 2-385 column-specific 2-617
definition of 2-197 with EXECUTE...INTO 2-427 granting 2-505
destroy 2-191, 2-380, 2-415 System name, in database revoking 2-614
export 2-191 name 4-49 privileges on 2-283
exportbinary 2-191 System requirements resident in memory 2-756
import 2-191 database Intro-4 scratch 2-287, 2-686
importbinary 2-191 software Intro-4 surviving 2-16
input 2-190 SYSTEM statement target 2-786
lohandles 2-191 setting environment variables temporary 2-287, 2-684
output 2-190 with 3-56 unlocking 2-813
receive 2-190 syntax 3-55 violations 2-785
send 2-191 sysxtdtypes TABLE keyword
specifying in CREATE DESCRIBE and GET in ALTER FRAGMENT
OPCLASS 2-197 DESCRIPTOR with 2-481, statement 2-12
SUPPORT keyword, in CREATE 2-482 in ALTER TABLE statement 2-85
OPCLASS statement 2-193 sysxtdtypes system catalog in Collection Derived Table
Surviving table 2-16 table 2-186, 2-418, 2-727, 2-728 segment 4-9
in CREATE TABLE
statement 2-278
Index 33
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z @
unloading TEXT or BYTE updating through a view 2-817 User informix, privileges associated
columns 2-809 use of expressions 2-819 with 2-504
VARCHAR, TEXT, or BYTE with USER keyword
columns 2-808 FETCH 2-465 in CONNECT statement 2-112
UNLOAD TO file 2-806 SELECT...FOR UDATE 2-680 User-defined aggregate
UNLOCK TABLE statement 2-813 WHERE keyword 2-829 creating 2-115
Unnamed row data type UPDATE STATISTICS statement defined 4-187
updating fields 2-832 distribution bins 2-843 dropping 2-393
Unnamed row type 4-68 dropping data distributions 2-840 invoking 4-199
field definition 4-68 examining index pages 2-839 User-defined data type 4-66
unloading 2-807, 2-811 only one table in hierarchy 2-837 privileges 2-511, 2-512
Updatable view 2-339 specifying distributions revoking 2-618
Update cursor only 2-844 User-defined function
locking considerations 2-358 using when upgrading database cursor 2-438
opening 2-568 server 2-846 inserting data with 2-550
restricted statements 2-363 Update trigger, defining iterator 4-279
use in DELETE 2-377 multiple 2-301 negator 4-280
UPDATE keyword Updating a specific table in a table noncursor 2-437
in CREATE TRIGGER hierarchy 2-817 OUT parameter 4-183
statement 2-300, 2-315 Upgrading the database selectivity 4-282
in GRANT FRAGMENT server 2-837, 2-846 variant 4-203, 4-284
statement 2-525 Upgrading to a newer database User-defined functions 4-179
in GRANT statement 2-505 server 2-846 User-defined routine
in REVOKE FRAGMENT UPPER function 4-174 arguments 2-189
statement 2-629, 2-630 Upper-case characters, converting definition 2-201
in REVOKE statement 2-614 to 4-174 dropping with DROP
Update privilege, with a USAGE keyword ROUTINE 2-408
view 2-817 in GRANT statement 2-511, 2-516 in SELECT statements 2-642
UPDATE statement in REVOKE statement 2-618, inserting data with 2-550
and transactions 2-818 2-622 ownership of created
and triggers 2-298, 2-300, 2-316 USAGE ON LANGUAGE objects 2-153
collection derived table with 4-15 keywords privileges
collection variables with 4-15, in GRANT statement 2-516 revoking 2-620
4-16 in REVOKE statement 2-622 REFERENCES keyword with
cursor with 2-355 USAGE ON TYPE keywords BYTE or TEXT data type 3-22
locking considerations 2-819 in GRANT statement 2-511 return values 4-270
opaque-type columns 2-828 in REVOKE statement 2-618 Users, types of Intro-3
OUT parameters and 4-184 USER function 4-110 USE_HASH keyword
rolling back updates 2-819 as affected by ANSI in Optimizer Directives
row types 2-826 compliance 4-111 Segment 4-252
SET clause 2-820 in ALTER TABLE statement 2-60 USE_NL keyword
single-column SET clause 2-820, in Condition segment 4-34 in Optimizer Directives
2-823 in CREATE TABLE Segment 4-252
smart large objects with 4-98 statement 2-234 USING BITMAP keywords
syntax 2-816 in DEFINE statement 3-16 in CREATE INDEX
updating a column to null 2-822 in expression 4-108 statement 2-157
updating a column twice 2-822 in INSERT statement 2-541, 2-547 Using correlation names 2-319
updating fields of a row in Literal Row segment 4-240
type 2-826, 2-832
Index 35
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z @
WHILE statement WITH GRANT OPTION keywords WITH LOG MODE ANSI
syntax 3-62 in GRANT FRAGMENT keywords, in CREATE
with NULL expressions 3-62 statement 2-523 DATABASE 2-125
Wildcard character in GRANT statement 2-500 WITH MAX keywords, in
asterisk (*) 4-38 WITH HOLD keywords ALLOCATE DESCRIPTOR
backslash (\) 4-37, 4-38 in DECLARE statement 2-349 statement 2-8
caret (^) 4-38 in FOREACH statement 3-30 WITH NO LOG keywords
percent sign (%) 4-37 WITH keyword in CREATE Temporary TABLE
question mark (?) 4-38 in ALTER FUNCTION statement 2-286
square brackets ([...]) 4-38 statement 2-41 in SELECT statement 2-683, 2-685
underscore (_) 4-37 in ALTER PROCEDURE WITH REOPTIMIZATION
with LIKE 2-663, 4-37 statement 2-48 keywords, in OPEN
with LIKE or MATCHES 4-263 in ALTER ROUTINE statement 2-566
with MATCHES 2-663, 4-38 statement 2-51 WITH RESUME keywords
Windows NT in CONNECT statement 2-103 in ON EXCEPTION
default locale for Intro-4 in CREATE AGGREGATE statement 3-45
wing 4-166 statement 2-115 in RETURN statement 3-52
WITH APPEND keywords in CREATE CAST WITH ROWIDS keywords
in SET DEBUG FILE TO statement 2-119 in ALTER FRAGMENT
statement 2-712 in CREATE DATABASE statement 2-27
in SET EXPLAIN statement 2-730 statement 2-124 in CREATE TABLE
in SET PLOAD FILE in CREATE FUNCTION statement 2-259
statement 2-755 statement 2-146 WITHOUT ERROR keywords
WITH BUFFERED LOG keywords, in CREATE INDEX in ALTER TABLE statement 2-64
in CREATE DATABASE 2-125 statement 2-178 in CREATE INDEX
WITH CHECK OPTION keywords, in CREATE PROCEDURE statement 2-178
in CREATE VIEW statement 2-200 in CREATE TABLE
statement 2-334 in CREATE VIEW statement 2-247
WITH COMMIT keywords, in statement 2-334 in SET Database Object Mode
TRUNCATE statement 2-802 in DECLARE statement 2-349 statement 2-703
WITH CONCURRENT in GRANT FRAGMENT WITHOUT HEADINGS keywords,
TRANSACTION keywords, in statement 2-523 in OUTPUT statement 2-577
CONNECT statement 2-103 in GRANT statement 2-500 WITHOUT keyword
WITH CRCOLS keywords in OPEN statement 2-566 in BEGIN WORK statement 2-91
in CREATE TABLE in SET Database Object Mode in CREATE INDEX
statement 2-255 statement 2-703 statement 2-178
in CREATE Temporary TABLE in SET DEBUG FILE TO in OUTPUT statement 2-577
statement 2-291 statement 2-712 in SET Database Object Mode
WITH ERROR keywords in SET EXPLAIN statement 2-730 statement 2-703
in ALTER TABLE statement 2-64 in SET PLOAD FILE WORK keyword
in CREATE INDEX statement 2-755 in BEGIN WORK statement 2-91
statement 2-178 in TRUNCATE statement 2-802 in COMMIT WORK
in CREATE TABLE WITH LISTING IN keywords statement 2-100
statement 2-247 in CREATE FUNCTION in ROLLBACK WORK
in SET Database Object Mode statement 2-146 statement 2-632
statement 2-703 in CREATE PROCEDURE WORK WITHOUT REPLICATION
statement 2-200 keywords, in BEGIN WORK
WITH LOG keywords, in CREATE statement 2-91
DATABASE statement 2-124
Index 37
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z @
*, asterisk
X as wildcard character 4-38
X/Open compliance level Intro-22 arithmetic operator 4-73
X/Open mode use in SELECT 2-636
FETCH statement 2-458 +, plus sign, arithmetic
SET DESCRIPTOR operator 4-73
statement 2-725 --, double dash, comment
symbol 1-7
-, minus sign, arithmetic
Y operator 4-73
., period
YEAR function dot notation 4-93
defined 4-152 /, division symbol, arithmetic
SQL 4-156 operator 4-73
YEAR keyword ?, question mark
in DATETIME data type 4-71 generating unique large-object
in DATETIME Field Qualifier filename with 4-150
segment 4-231 placeholder in prepared
in INTERVAL data type 4-234 statement
in INTERVAL Field Qualifier requires OPEN...USING 2-572
segment 4-223 replacement options in USING
clause 2-572
?, question mark
Z as placeholder in PREPARE 2-580
Zoned decimal, in external as wildcard 4-38
tables 2-133 naming variables in PUT 2-597
ZONED keyword, in CREATE [...], square brackets
EXTERNAL TABLE as wildcard characters 4-38
statement 2-132 \, backslash
escape character with
UNLOAD 2-811
Symbols \, backslash, as wildcard
character 4-37
(escape character), allowing ^, caret, as wildcard character 4-38
newlines in quoted _, underscore, as wildcard 4-37
strings 4-262 {}, braces, comment symbol 1-7
!, exclamation point ||, concatenation operator 4-73,
generating smart-large-object 4-87
filename 4-150 ’, single quotes
", double quotes around quoted string 4-260
around quoted string 4-260 in quoted string 4-262
in quoted string 4-262
with delimited identifiers 4-208,
4-211
$INFORMIXDIR/etc/sqlhosts. See
sqlhosts file.
%, percent sign, as wildcard 4-37
(|), pipe character 2-140, 2-687