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; [Link]; [Link]; 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 [Link]; The world is being digitized. We’re indexing [Link];
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:
[Link]/answers
Printed Manuals
To order printed manuals, call 1-800-331-1763 or send email to
moreinfo@[Link]. 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
doc@[Link]
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, [Link], 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
[Link] 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 [Link] 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 [Link]
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/[Link]/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/[Link]/mytbl.%r(1..3)",
"DISK:2:/work2/[Link]/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 [Link] = [Link]
--join between the two catalog tables
AND [Link] = 'update_by_pct'
-- look for procedure named update_by_pct
AND [Link] = '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 [Link] = [Link]
--join between the two catalog tables
AND [Link] = 'raise_prices'
-- look for procedure named raise_prices
AND [Link] = '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:[Link]
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:[Link]
The identifier mysum now refers to the table [Link], 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 [Link] (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