100% found this document useful (2 votes)
2K views1,232 pages

SQL Syntax Informix

This document contains proprietary information of IBM. It is provided under a license agreement and is protected by copyright law. When you send information to IBM, you grant IBM a nonexclusive right to use or distribute the information without incurring any obligation to you.

Uploaded by

reelea
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
2K views1,232 pages

SQL Syntax Informix

This document contains proprietary information of IBM. It is provided under a license agreement and is protected by copyright law. When you send information to IBM, you grant IBM a nonexclusive right to use or distribute the information without incurring any obligation to you.

Uploaded by

reelea
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1232

IBM Informix

Guide to SQL

Syntax

IBM Informix Extended Parallel Server, Version 8.4


IBM Informix Dynamic Server, Version 9.4

March 2003
Part Nos. CT1SQNA (Volume 1) and CT1SRNA (Volume 2)
Note:
Before using this information and the product it supports, read the information in the appendix
entitled “Notices.”

This document contains proprietary information of IBM. It is provided under a license agreement and is
protected by copyright law. The information contained in this publication does not include any product
warranties, and any statements provided in this manual should not be interpreted as such.

When you send information to IBM, you grant IBM a nonexclusive right to use or distribute the information
in any way it believes appropriate without incurring any obligation to you.

© Copyright International Business Machines Corporation 1996, 2003. All rights reserved.

US Government User Restricted Rights—Use, duplication or disclosure restricted by GSA ADP Schedule
Contract with IBM Corp.

ii IBM Informix Guide to SQL: Syntax


Table of
Contents

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 in Dynamic Server, Version 9.4 . . . . . . . . . 5
New Features in Extended Parallel Server Version 8.4 . . . . 7
Documentation Conventions . . . . . . . . . . . . . . 9
Typographical Conventions . . . . . . . . . . . . . 9
Icon Conventions . . . . . . . . . . . . . . . . . 10
Syntax Conventions . . . . . . . . . . . . . . . . 12
Example-Code Conventions . . . . . . . . . . . . . 16
Additional Documentation . . . . . . . . . . . . . . . 17
Related Reading . . . . . . . . . . . . . . . . . . . 19
Compliance with Industry Standards . . . . . . . . . . . 20
IBM Welcomes Your Comments . . . . . . . . . . . . . 20

Chapter 1 Overview of SQL Syntax


In This Chapter . . . . . . . . . . . . . . . . . . . 1-3
How to Enter SQL Statements . . . . . . . . . . . . . . 1-3
How to Enter SQL Comments . . . . . . . . . . . . . . 1-6
Categories of SQL Statements . . . . . . . . . . . . . . 1-9
ANSI Compliance and Extensions . . . . . . . . . . . . 1-13
Chapter 2 SQL Statements
In This Chapter . . . . . . . . . . . . . . . . . . . 2-7
ALLOCATE COLLECTION. . . . . . . . . . . . . . . 2-8
ALLOCATE DESCRIPTOR . . . . . . . . . . . . . . . 2-10
ALLOCATE ROW . . . . . . . . . . . . . . . . . . 2-12
ALTER ACCESS_METHOD . . . . . . . . . . . . . . 2-14
ALTER FRAGMENT . . . . . . . . . . . . . . . . . 2-16
ALTER FUNCTION . . . . . . . . . . . . . . . . . 2-39
ALTER INDEX . . . . . . . . . . . . . . . . . . . 2-41
ALTER PROCEDURE . . . . . . . . . . . . . . . . . 2-44
ALTER ROUTINE . . . . . . . . . . . . . . . . . . 2-46
ALTER SEQUENCE . . . . . . . . . . . . . . . . . 2-49
ALTER TABLE . . . . . . . . . . . . . . . . . . . 2-52
BEGIN WORK . . . . . . . . . . . . . . . . . . . 2-82
CLOSE . . . . . . . . . . . . . . . . . . . . . . 2-85
CLOSE DATABASE . . . . . . . . . . . . . . . . . 2-88
COMMIT WORK . . . . . . . . . . . . . . . . . . 2-90
CONNECT . . . . . . . . . . . . . . . . . . . . 2-92
CREATE ACCESS_METHOD . . . . . . . . . . . . . . 2-102
CREATE AGGREGATE . . . . . . . . . . . . . . . . 2-104
CREATE CAST . . . . . . . . . . . . . . . . . . . 2-108
CREATE DATABASE . . . . . . . . . . . . . . . . . 2-112
CREATE DISTINCT TYPE . . . . . . . . . . . . . . . 2-115
CREATE DUPLICATE . . . . . . . . . . . . . . . . 2-118
CREATE EXTERNAL TABLE . . . . . . . . . . . . . . 2-121
CREATE FUNCTION . . . . . . . . . . . . . . . . . 2-133
CREATE FUNCTION FROM . . . . . . . . . . . . . . 2-141
CREATE INDEX . . . . . . . . . . . . . . . . . . 2-144
CREATE OPAQUE TYPE . . . . . . . . . . . . . . . 2-169
CREATE OPCLASS . . . . . . . . . . . . . . . . . 2-176
CREATE PROCEDURE . . . . . . . . . . . . . . . . 2-182
CREATE PROCEDURE FROM. . . . . . . . . . . . . . 2-192
CREATE ROLE . . . . . . . . . . . . . . . . . . . 2-194
CREATE ROUTINE FROM . . . . . . . . . . . . . . . 2-196
CREATE ROW TYPE . . . . . . . . . . . . . . . . . 2-198
CREATE SCHEMA. . . . . . . . . . . . . . . . . . 2-203
CREATE SCRATCH TABLE. . . . . . . . . . . . . . . 2-205
CREATE SEQUENCE . . . . . . . . . . . . . . . . . 2-206
CREATE SYNONYM . . . . . . . . . . . . . . . . . 2-210
CREATE TABLE. . . . . . . . . . . . . . . . . . . 2-214
CREATE TEMP TABLE . . . . . . . . . . . . . . . . 2-260
CREATE Temporary TABLE . . . . . . . . . . . . . . 2-261

iv IBM Informix Guide to SQL: Syntax


CREATE TRIGGER . . . . . . . . . . . . . . . . . 2-269
CREATE VIEW . . . . . . . . . . . . . . . . . . 2-310
DATABASE. . . . . . . . . . . . . . . . . . . . 2-316
DEALLOCATE COLLECTION . . . . . . . . . . . . . 2-318
DEALLOCATE DESCRIPTOR . . . . . . . . . . . . . 2-320
DEALLOCATE ROW . . . . . . . . . . . . . . . . 2-322
DECLARE . . . . . . . . . . . . . . . . . . . . 2-323
DELETE . . . . . . . . . . . . . . . . . . . . . 2-344
DESCRIBE . . . . . . . . . . . . . . . . . . . . 2-351
DESCRIBE INPUT . . . . . . . . . . . . . . . . . 2-359
DISCONNECT . . . . . . . . . . . . . . . . . . 2-366
DROP ACCESS_METHOD . . . . . . . . . . . . . . 2-369
DROP AGGREGATE . . . . . . . . . . . . . . . . 2-370
DROP CAST . . . . . . . . . . . . . . . . . . . 2-371
DROP DATABASE . . . . . . . . . . . . . . . . . 2-372
DROP DUPLICATE . . . . . . . . . . . . . . . . . 2-374
DROP FUNCTION . . . . . . . . . . . . . . . . . 2-375
DROP INDEX . . . . . . . . . . . . . . . . . . . 2-377
DROP OPCLASS . . . . . . . . . . . . . . . . . . 2-378
DROP PROCEDURE . . . . . . . . . . . . . . . . 2-379
DROP ROLE . . . . . . . . . . . . . . . . . . . 2-381
DROP ROUTINE . . . . . . . . . . . . . . . . . . 2-382
DROP ROW TYPE . . . . . . . . . . . . . . . . . 2-384
DROP SEQUENCE . . . . . . . . . . . . . . . . . 2-386
DROP SYNONYM . . . . . . . . . . . . . . . . . 2-387
DROP TABLE . . . . . . . . . . . . . . . . . . . 2-388
DROP TRIGGER . . . . . . . . . . . . . . . . . . 2-391
DROP TYPE . . . . . . . . . . . . . . . . . . . 2-392
DROP VIEW . . . . . . . . . . . . . . . . . . . 2-393
EXECUTE . . . . . . . . . . . . . . . . . . . . 2-394
EXECUTE FUNCTION . . . . . . . . . . . . . . . . 2-404
EXECUTE IMMEDIATE . . . . . . . . . . . . . . . 2-411
EXECUTE PROCEDURE . . . . . . . . . . . . . . . 2-414
FETCH . . . . . . . . . . . . . . . . . . . . . 2-424
FLUSH . . . . . . . . . . . . . . . . . . . . . 2-435
FREE . . . . . . . . . . . . . . . . . . . . . . 2-437
GET DESCRIPTOR . . . . . . . . . . . . . . . . . 2-439
GET DIAGNOSTICS . . . . . . . . . . . . . . . . 2-446
GRANT . . . . . . . . . . . . . . . . . . . . . 2-459
GRANT FRAGMENT . . . . . . . . . . . . . . . . 2-480
INFO . . . . . . . . . . . . . . . . . . . . . . 2-487
INSERT . . . . . . . . . . . . . . . . . . . . . 2-489

Table of Contents v
LOAD . . . . . . . . . . . . . . . . . . . . . . 2-504
LOCK TABLE . . . . . . . . . . . . . . . . . . . 2-513
OPEN . . . . . . . . . . . . . . . . . . . . . . 2-516
OUTPUT . . . . . . . . . . . . . . . . . . . . . 2-525
PREPARE . . . . . . . . . . . . . . . . . . . . . 2-527
PUT . . . . . . . . . . . . . . . . . . . . . . . 2-539
RENAME COLUMN . . . . . . . . . . . . . . . . . 2-549
RENAME DATABASE . . . . . . . . . . . . . . . . 2-551
RENAME INDEX . . . . . . . . . . . . . . . . . . 2-552
RENAME SEQUENCE . . . . . . . . . . . . . . . . 2-553
RENAME TABLE . . . . . . . . . . . . . . . . . . 2-554
REVOKE . . . . . . . . . . . . . . . . . . . . . 2-557
REVOKE FRAGMENT . . . . . . . . . . . . . . . . 2-575
ROLLBACK WORK . . . . . . . . . . . . . . . . . 2-579
SELECT . . . . . . . . . . . . . . . . . . . . . 2-581
SET AUTOFREE . . . . . . . . . . . . . . . . . . 2-640
SET COLLATION . . . . . . . . . . . . . . . . . . 2-643
SET CONNECTION . . . . . . . . . . . . . . . . . 2-646
SET CONSTRAINTS . . . . . . . . . . . . . . . . . 2-651
SET Database Object Mode . . . . . . . . . . . . . . . 2-652
SET DATASKIP . . . . . . . . . . . . . . . . . . . 2-659
SET DEBUG FILE TO . . . . . . . . . . . . . . . . . 2-661
SET Default Table Type . . . . . . . . . . . . . . . . 2-663
SET Default Table Space . . . . . . . . . . . . . . . . 2-665
SET DEFERRED_PREPARE . . . . . . . . . . . . . . . 2-666
SET DESCRIPTOR . . . . . . . . . . . . . . . . . . 2-670
SET ENVIRONMENT. . . . . . . . . . . . . . . . . 2-678
SET EXPLAIN . . . . . . . . . . . . . . . . . . . 2-683
SET INDEX . . . . . . . . . . . . . . . . . . . . 2-689
SET INDEXES . . . . . . . . . . . . . . . . . . . 2-690
SET ISOLATION . . . . . . . . . . . . . . . . . . 2-691
SET LOCK MODE . . . . . . . . . . . . . . . . . . 2-696
SET LOG . . . . . . . . . . . . . . . . . . . . . 2-698
SET OPTIMIZATION . . . . . . . . . . . . . . . . . 2-700
SET PDQPRIORITY . . . . . . . . . . . . . . . . . 2-704
SET PLOAD FILE . . . . . . . . . . . . . . . . . . 2-707
SET Residency . . . . . . . . . . . . . . . . . . . 2-708
SET ROLE . . . . . . . . . . . . . . . . . . . . . 2-710
SET SCHEDULE LEVEL . . . . . . . . . . . . . . . . 2-712
SET SESSION AUTHORIZATION . . . . . . . . . . . . 2-713
SET STATEMENT CACHE . . . . . . . . . . . . . . . 2-715
SET TABLE . . . . . . . . . . . . . . . . . . . . 2-719

vi IBM Informix Guide to SQL: Syntax


SET TRANSACTION . . . . . . . . . . . . . . . . 2-720
SET Transaction Mode . . . . . . . . . . . . . . . . 2-725
SET TRIGGERS . . . . . . . . . . . . . . . . . . 2-728
START VIOLATIONS TABLE . . . . . . . . . . . . . 2-729
STOP VIOLATIONS TABLE . . . . . . . . . . . . . . 2-748
TRUNCATE . . . . . . . . . . . . . . . . . . . 2-750
UNLOAD . . . . . . . . . . . . . . . . . . . . 2-753
UNLOCK TABLE . . . . . . . . . . . . . . . . . 2-760
UPDATE . . . . . . . . . . . . . . . . . . . . 2-762
UPDATE STATISTICS . . . . . . . . . . . . . . . . 2-778
WHENEVER . . . . . . . . . . . . . . . . . . . 2-789

Chapter 3 SPL Statements


In This Chapter . . . . . . . . . . . . . . . . . . 3-3
CALL . . . . . . . . . . . . . . . . . . . . . . 3-4
CASE . . . . . . . . . . . . . . . . . . . . . . 3-6
CONTINUE . . . . . . . . . . . . . . . . . . . 3-9
DEFINE . . . . . . . . . . . . . . . . . . . . . 3-10
EXIT . . . . . . . . . . . . . . . . . . . . . . 3-22
FOR . . . . . . . . . . . . . . . . . . . . . . 3-23
FOREACH . . . . . . . . . . . . . . . . . . . . 3-27
IF . . . . . . . . . . . . . . . . . . . . . . . 3-33
LET . . . . . . . . . . . . . . . . . . . . . . 3-36
ON EXCEPTION . . . . . . . . . . . . . . . . . . 3-39
RAISE EXCEPTION . . . . . . . . . . . . . . . . . 3-43
RETURN . . . . . . . . . . . . . . . . . . . . 3-45
SYSTEM . . . . . . . . . . . . . . . . . . . . . 3-47
TRACE . . . . . . . . . . . . . . . . . . . . . 3-50
WHILE . . . . . . . . . . . . . . . . . . . . . 3-54

Chapter 4 Segments
In This Chapter . . . . . . . . . . . . . . . . . . 4-3
Arguments . . . . . . . . . . . . . . . . . . . . 4-5
Collection-Derived Table . . . . . . . . . . . . . . . 4-7
Collection Subquery . . . . . . . . . . . . . . . . . 4-22
Condition . . . . . . . . . . . . . . . . . . . . 4-24
Database Name . . . . . . . . . . . . . . . . . . 4-44
Database Object Name . . . . . . . . . . . . . . . . 4-46
Data Type . . . . . . . . . . . . . . . . . . . . 4-49
DATETIME Field Qualifier . . . . . . . . . . . . . . 4-65
Expression . . . . . . . . . . . . . . . . . . . . 4-67
External Routine Reference . . . . . . . . . . . . . . 4-187

Table of Contents vii


Identifier . . . . . . . . . . . . . . . . . . . . . 4-189
INTERVAL Field Qualifier . . . . . . . . . . . . . . . 4-205
Jar Name . . . . . . . . . . . . . . . . . . . . . 4-207
Literal Collection . . . . . . . . . . . . . . . . . . 4-208
Literal DATETIME . . . . . . . . . . . . . . . . . . 4-212
Literal INTERVAL . . . . . . . . . . . . . . . . . . 4-214
Literal Number . . . . . . . . . . . . . . . . . . . 4-216
Literal Row . . . . . . . . . . . . . . . . . . . . 4-218
Optimizer Directives . . . . . . . . . . . . . . . . . 4-222
Owner Name. . . . . . . . . . . . . . . . . . . . 4-234
Purpose Options . . . . . . . . . . . . . . . . . . 4-237
Quoted String . . . . . . . . . . . . . . . . . . . 4-243
Relational Operator . . . . . . . . . . . . . . . . . 4-248
Return Clause . . . . . . . . . . . . . . . . . . . 4-253
Routine Modifier . . . . . . . . . . . . . . . . . . 4-257
Routine Parameter List . . . . . . . . . . . . . . . . 4-266
Shared-Object Filename . . . . . . . . . . . . . . . . 4-270
Specific Name . . . . . . . . . . . . . . . . . . . 4-274
Statement Block . . . . . . . . . . . . . . . . . . . 4-276

Appendix A Reserved Words for IBM Informix Dynamic Server

Appendix B Reserved Words for IBM Informix Extended Parallel Server

Appendix C Notices

Index

viii IBM Informix Guide to SQL: Syntax


Introduction

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 in Dynamic Server, Version 9.4 . . . . . . . . . . 5


New Features in Extended Parallel Server Version 8.4 . . . . . 7
Performance Enhancements . . . . . . . . . . . . . 7
New SQL Functionality . . . . . . . . . . . . . . 7
Version 8.4 Features from Version 7.3 . . . . . . . . . . 8
Documentation Conventions . . . . . . . . . . . . . . . 9
Typographical Conventions . . . . . . . . . . . . . . 9
Icon Conventions . . . . . . . . . . . . . . . . . . 10
Comment Icons . . . . . . . . . . . . . . . . . 10
Feature, Product, and Platform Icons . . . . . . . . . . 10
Compliance Icons . . . . . . . . . . . . . . . . 12
Syntax Conventions . . . . . . . . . . . . . . . . . 12
Elements That Can Appear on the Path . . . . . . . . . 13
How to Read a Syntax Diagram . . . . . . . . . . . . 15
Example-Code Conventions . . . . . . . . . . . . . . 16

Additional Documentation . . . . . . . . . . . . . . . . 17
Related Reading . . . . . . . . . . . . . . . . . . . . 19
Compliance with Industry Standards . . . . . . . . . . . . 20
IBM Welcomes Your Comments . . . . . . . . . . . . . . 20
2 IBM Informix Guide to SQL: Syntax
In This Introduction
This introduction provides an overview of the information in this manual
and describes the documentation conventions that it uses.

About This Manual


This manual describes the syntax of the structured query language (SQL) and
Stored Procedure Language (SPL) statements for Version 9.4 of IBM Informix
Dynamic Server and Version 8.4 of IBM Informix Extended Parallel Server.

This manual is a companion volume to the IBM Informix Guide to SQL:


Reference, the IBM Informix Guide to SQL: Tutorial, and the IBM Informix Database
Design and Implementation Guide. The IBM Informix Guide to SQL: Reference
provides reference information about the system catalog, the built-in SQL
data types, and environment variables that can affect SQL statements. The
IBM Informix Guide to SQL: Tutorial shows how to use basic and advanced SQL
and SPL routines to access and manipulate the data in your databases. The
IBM Informix Database Design and Implementation Guide shows how to use SQL
to implement and manage relational databases.

Types of Users
This manual is written for the following users:

■ Database users
■ Database administrators
■ Database-application programmers

Introduction 3
Software Dependencies

This manual assumes that you have the following background:

■ A working knowledge of your computer, your operating system,


and the utilities that your operating system provides
■ Some experience working with relational databases or exposure to
database concepts
■ Some experience with computer programming

If you have limited experience with relational databases, SQL, or your


operating system, refer to the Getting Started Guide for your database server
for a list of supplementary titles.

Software Dependencies
This manual assumes that you are using one of the following database
servers:

■ IBM Informix Extended Parallel Server, Version 8.4


■ IBM Informix Dynamic Server, Version 9.4

Assumptions About Your Locale


IBM Informix products can support many languages, cultures, and code sets.
All culture-specific information is brought together in a single environment,
called a Global Language Support (GLS) locale.

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 environments. These locales
support U.S. English format conventions for dates, times, and currency, and
also support 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 non-ASCII characters in your data or in SQL identifiers, or


if you want to conform to localized collation rules of character data, you need
to specify an appropriate nondefault locale.

For instructions on how to specify a nondefault locale, additional syntax, and


other considerations related to GLS locales, see the IBM Informix GLS
Programmer’s Manual.

4 IBM Informix Guide to SQL: Syntax


Demonstration Databases

Demonstration Databases
The DB-Access utility, which is provided with your IBM Informix database
server products, includes one or more of the following demonstration
databases:

■ The stores_demo database illustrates a relational schema with infor-


mation about a fictitious wholesale sporting-goods distributor.
Many examples in IBM Informix manuals are based on the
stores_demo database.
XPS ■ The sales_demo database illustrates a dimensional schema for data-
warehousing applications. For conceptual information about dimen-
sional data modeling, see the IBM Informix Database Design and
Implementation Guide. ♦

IDS ■ The superstores_demo database illustrates an object-relational


schema. The superstores_demo database contains examples of
extended data types, type and table inheritance, and user-defined
routines. ♦

For information about how to create and populate the demonstration


databases, see the IBM Informix DB-Access User’s Guide. For descriptions of the
databases and their contents, see the IBM Informix Guide to SQL: Reference.

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.

New Features in Dynamic Server, Version 9.4


For a comprehensive list of new database server features, see the Getting
Started Guide. This section lists new features relevant to this manual. In
addition to documenting the new features that are listed in this section, this
manual corrects errata that have been identified since the previous edition.

The following list provides information about the new features for
IBM Informix Dynamic Server, Version 9.4, that this manual describes.

Introduction 5
New Features in Dynamic Server, Version 9.4

■ The following new SQL statements are documented in Chapter 2:


ALTER SEQUENCE RENAME SEQUENCE
CREATE SEQUENCE DESCRIBE INPUT
DROP SEQUENCE SET COLLATION

■ The following SQL statements support new syntax in Version 9.4:


ALTER FUNCTION DESCRIBE
ALTER PROCEDURE GRANT
CREATE FUNCTION REVOKE
CREATE PROCEDURE SELECT
CREATE SYNONYM SET EXPLAIN
CREATE TRIGGER SET Residency

■ The SET COLLATION statement can specify a localized collating order


for sorting NCHAR and NVARCHAR values that is different from
what DB_LOCALE specifies. Database objects such as indexes and
UDRs that perform sorting operations always use the collating order
that was in effect when they were created.
■ This release provides data definition language (DDL) statements to
support sequence objects, from which one or more users can generate
unique integers in the INT8 range. The GRANT and REVOKE state-
ments can control privileges on a sequence, and CREATE SYNONYM
can declare synonyms for sequence objects. New CURRVAL and
NEXTVAL operators can read and increment sequence objects.
■ The new DESCRIBE INPUT and DESCRIBE OUTPUT statements can
return information about multiple input and output parameters
prior to execution of a prepared statement.
■ The CREATE TRIGGER statement can create INSTEAD OF Triggers on
Views. You can use these to update views that in previous releases
did not support UPDATE operations.
■ The ORDER BY Clause of the SELECT statement can include column
names and expressions that did not appear in the Projection clause.
■ The FROM clause of the SELECT statement can include iterator
functions that create a virtual table.
■ The PDQ feature supports cursors that were declared WITH HOLD.
■ The new DESCRIBE INPUT statement supports dynamic queries.

6 IBM Informix Guide to SQL: Syntax


New Features in Extended Parallel Server Version 8.4

■ The LOAD and UNLOAD statements for flat-file I/O can support file
sizes larger than the 2 Gigabyte limit of earlier release versions.
■ User-defined functions can include multiple OUT parameters.
■ SPL functions can declare named return parameters.
■ Functional indexes can be based on more than 16 columns. The new
limit on index parts is language-dependent, but is greater than 90.
■ The LVARCHAR data type can be declared with a new size parameter
that can be larger than the former upper limit of 2048 bytes.
■ The functionality of the SET Residency statement is provided
automatically by the database server.

New Features in Extended Parallel Server Version 8.4


This manual describes new features in Version 8.4 of IBM Informix Extended
Parallel Server. The features fall into the following areas:

■ Performance enhancements
■ New SQL functionality
■ Version 8.3 features from Dynamic Server, Version 7.30

Performance Enhancements
This manual describes the following performance enhancements to
Version 8.4 of IBM Informix Extended Parallel Server:

■ Insert cursors with simple large objects


■ Coarse-grain index locks
■ Updates with subquery in SET clause
■ Index on aggregates

New SQL Functionality


This manual describes the following new SQL functionality in Version 8.4 of
IBM Informix Extended Parallel Server:

■ CASE statement in SPL


■ Creating a table with RANGE fragmentation

Introduction 7
New Features in Extended Parallel Server Version 8.4

■ DELETE…USING statement to delete rows based on a table join


■ Globally detached indexes
■ Load and unload simple large objects to external tables
■ MIDDLE function
■ Referential integrity for globally detached indexes
■ TRUNCATE statement

Version 8.4 Features from Version 7.3


This manual describes the following features from Version 7.3 of Dynamic
Server in Version 8.4 of IBM Informix Extended Parallel Server:

■ Ability to retain update locks


■ ALTER FRAGMENT attach with remainders
■ ALTER TABLE to add or drop a foreign key constraint
■ ALTER TABLE to add, drop, or modify a column
■ Constraints on columns other than the fragmentation column
■ COUNT function
■ DBINFO provides all Version 7.3 information and adds the coserver
ID and dbspace name
■ Deferred constraints for all constraint types
■ Deferred referential-integrity constraints
■ Insert from SPL functions
■ NVL and DECODE functions
■ REPLACE, SUBSTR, LPAD, and RPAD string manipulation functions
■ RENAME COLUMN statement
■ TO_CHAR and TO_DATE functions for date conversion
■ Triggers
■ UPDATE SET clause subqueries
■ UPPER, LOWER, and INITCAP functions for case-insensitive search
■ Memory-resident tables
■ Violations table

8 IBM Informix Guide to SQL: Syntax


Documentation Conventions

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
This manual uses the following conventions to introduce new terms,
illustrate screen displays, describe command syntax, and so forth.

Convention Meaning

KEYWORD All primary elements in a programming language statement


(keywords) appear in uppercase letters in a serif font.

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.

boldface Names of program entities (such as classes, events, and tables),


boldface environment variables, file and pathnames, and interface
elements (such as icons, menu items, and buttons) appear in
boldface.

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.

♦ This symbol indicates the end of product- or platform-specific


information.

➞ This symbol indicates a menu item. For example, “Choose


Tools➞Options” means choose the Options item from the
Tools menu.

Tip: When you are instructed to “enter” characters or to “execute” a command,


immediately press RETURN after the entry. When you are instructed to “type” the
text or to “press” other keys, no RETURN is required.

Introduction 9
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 Label Description

Warning: Identifies paragraphs that contain vital instructions,


cautions, or critical information

Important: Identifies paragraphs that contain significant


information about the feature or operation that is
being described

Tip: Identifies paragraphs that offer additional details or


shortcuts for the functionality that is being described

Feature, Product, and Platform Icons


Feature, product, and platform icons identify paragraphs that contain
feature-specific, product-specific, or platform-specific information.

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 IBM Informix
ESQL/C
(1 of 2)

10 IBM Informix Guide to SQL: Syntax


Icon Conventions

Icon Description

Ext
Identifies information that is specific to external routines,
that is, UDRs written in either C or Java language

GLS
Identifies information that relates to the IBM Informix
Global Language Support (GLS) feature

IDS
Identifies information or syntax that is specific to
IBM Informix Dynamic Server

Java
Identifies information that is specific to UDRs written in
Java

UNIX
Identifies information that is specific to the UNIX
operating system

Windows
Identifies information that applies to all Windows
environments

Identifies information or syntax that is specific to


XPS
IBM 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 11
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 an Informix extension to ANSI SQL-92 entry-
level standard SQL

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 within one or more
paragraphs within a section.

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 EXPLAIN ON

OFF

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.

12 IBM Informix Guide to SQL: Syntax


Syntax Conventions

Syntax elements in a path represent terms, keywords, symbols, and segments


that can appear in your statement. The path always approaches elements
from the left and continues to the right, except in the case of separators in
loops. For separators in loops, the path approaches counterclockwise. Unless
otherwise noted, at least one blank character separates syntax elements.

Elements That Can Appear on the Path


You might encounter one or more of the following elements on a path.

Element Description
KEYWORD A word in UPPERCASE letters is a keyword. You must
spell the word exactly as shown; however, you can use
either uppercase or lowercase letters.
(.,;@+*-/) Punctuation and other nonalphanumeric characters
are literal symbols that you must enter exactly as
shown.
' ' [Single quotes are literal symbols that you must enter
as shown.]
variable A word in italics represents a value that you must
supply. A table immediately following the diagram
explains the value.
A reference in a box represents a subdiagram. Imagine
ADD that the subdiagram is spliced into the main diagram
Clause
p. 3-288 at this point. When a page number is not specified, the
subdiagram appears on the same page. The aspect
ADD Clause ratio of a box is not significant.

A reference in a box in the upper-right corner of a


Back to ADD Clause subdiagram refers to the next higher-level diagram of
p. 1-14 which this subdiagram is a member.

(1 of 3)

Introduction 13
Syntax Conventions

Element Description
An icon is a warning that this path is valid only for
E/C some products, or only under certain conditions.
Characters on the icons indicate what products or
conditions support the path.
These icons might appear in path of a syntax diagram:

IDS Valid only for Dynamic Server.

Valid only for Extended Parallel Server.


XPS

Ext Valid only for external routines, that is,


UDRs written in C and Java.

Valid only if you are using IBM Informix


SPL
Stored Procedure Language (SPL)

Valid only for INFORMIX-ESQL/C.


E/C

ALL
A shaded option is the default specification. This
option is in effect, unless you specify another path.

... Syntax between a pair of arrows is a subdiagram.

The vertical line at the upper right terminates the


syntax diagram.

IS NULL A branch below the main path indicates an optional


path. (Any term on the main path is required, unless
NOT a branch can circumvent it.)
(2 of 3)

14 IBM Informix Guide to SQL: Syntax


Syntax Conventions

Element Description
NOT FOUND A set of multiple branches indicates that a choice
among more than two different paths is available.
ERROR

WARNING

, A loop indicates a path that you can repeat.


Punctuation along the top of the loop indicates the
variable separator symbol for list items. If no symbol appears,
a blank space is the separator (except in the diagrams
for “Identifier” on page 4-189, “Literal Number” on
statement
page 4-216, and “Quoted String” on page 4-243, which
allow no separators between characters within loops.
, A gate ( 3 ) on a path indicates that you can use that
path only the indicated number of times, even if it is
3 size part of a larger loop. You can specify size no more than
three times within this statement segment.
(3 of 3)

How to Read a Syntax Diagram


Figure 2 shows a syntax diagram that uses most of the path elements that the
previous table lists.
Figure 2
Example of a Syntax Diagram

DELETE FROM table

view WHERE Condition


p. 4-5
synonym E/C
CURRENT OF cursor

Tip: For purposes of illustrating how to read syntax diagrams, this diagram has been
simplified, and does not reflect all of the options of the DELETE statement. See the
section “DELETE” on page 2-344” for the complete syntax of DELETE.

To use this diagram to construct a statement, start at the top left with the
keyword DELETE FROM. Then follow the diagram to the right, proceeding
through the options that you want.

Introduction 15
Example-Code Conventions

Figure 2 illustrates the following steps:

1. Type DELETE FROM.


2. You can delete a table, view, or synonym:
■ Type the table name, view name, or synonym, as you desire.
■ You can type WHERE to limit the rows to delete.
■ If you type WHERE and you are using DB-Access or the SQL Editor,
you must include the Condition clause to specify a condition to
delete. To find the syntax for specifying a condition, go to the
“Condition” segment on the specified page.
■ If you are using ESQL/C, you can include either the Condition
clause to delete a specific condition or the CURRENT OF cursor
clause to delete a row from the table.
3. Follow the diagram to the terminator.
Your DELETE statement is complete.

Example-Code Conventions
Examples of SQL code occur throughout this manual. Except where noted,
the code is not specific to any single IBM 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
...

DELETE FROM customer


WHERE customer_num = 121
...

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.

16 IBM Informix Guide to SQL: Syntax


Additional Documentation

Tip: Ellipses points in program fragments indicate that additional code (that a full
application would include) has been omitted to simplify presentation of the concept
under discussion. In addition, ellipses symbols never begin or end an example. In
most contexts, including literal ellipses symbols in SQL code will produce an error.

For detailed directions on using SQL statements for a particular application


development tool or SQL API, see the manual for your product.

Additional Documentation
IBM Informix Dynamic Server documentation is provided in a variety of
formats:

■ Online manuals. The IBM Informix Online Documentation site at


http://www.ibm.com/software/data/informix/pubs/library/
contains manuals provided for your use. This Web site enables you
to print chapters or entire books.
■ Online help. This facility provides context-sensitive help, an error
message reference, language syntax, and more.
■ Documentation notes and release notes. Documentation notes,
which contain additions and corrections to the manuals, and release
notes are located in the directory where the product is installed.
Please examine these files because they contain vital information
about application and performance issues.

Introduction 17
Additional Documentation

UNIX On UNIX platforms in the default locale, the following online files
appear in the $INFORMIXDIR/release/en_us/0333 directory.

Online File Purpose

ids_sqls_docnotes_9.40.html The documentation notes file for


(for Dynamic Server) or your version of this manual describes
xps_sqls_docnotes_8.40.html topics that are not covered in the
(for Extended Parallel Server) manual or that were modified since
publication.

ids_unix_release_notes_9.40.html The release notes file describes


and (in plain text format) feature differences from earlier
ids_unix_release_notes_9.40.txt versions of IBM Informix products
(for Dynamic Server) or and how these differences might
xps_release_notes_9.40.html affect current products. This file also
and (in plain text format) contains information about any
xps_release_notes_9.40.txt known problems and their
(for Extended Parallel Server) workarounds.

ids_machine_notes_9.40.txt The machine notes file describes any


(for Dynamic Server) or special actions that you must take to
xps_machine_notes_8.40.txt configure and use IBM Informix
(for Extended Parallel Server) products on your computer. Machine
notes are named for the product
described.

18 IBM Informix Guide to SQL: Syntax


Related Reading

Windows The following items appear in the Informix folder. To display this
folder, choose Start➞Programs➞Informix➞ Documentation Notes
or Release Notes from the task bar.

Program Group Item Description

Documentation Notes This item includes additions or corrections to


manuals with information about features that
might not be covered in the manuals or that have
been modified since publication.

Release Notes This item describes feature differences from


earlier versions of IBM Informix products and
how these differences might affect current
products. This file also contains information
about any known problems and their
workarounds.

Machine notes do not apply to Windows platforms. ♦


■ Error message files. IBM Informix software products provide ASCII
files that contain error messages and their corrective actions.
UNIX To read the error messages on UNIX, you can use the finderr com-
mand to display the error messages online. ♦
Windows To read error messages and corrective actions on Windows, use the
Informix Error Messages utility. To display this utility, 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 Guide.

Introduction 19
Compliance with Industry Standards

Compliance with Industry Standards


The American National Standards Institute (ANSI) has established a set of
industry standards for SQL. IBM Informix SQL-based products are fully
compliant with SQL-92 Entry Level (published as ANSI X3.135-1992), which
is identical to ISO 9075:1992. In addition, many features of Informix database
servers comply with the SQL-92 Intermediate and Full Level and X/Open
SQL CAE (common applications environment) standards.

IBM Welcomes Your Comments


To help us with future versions of our manuals, let us know about any correc-
tions or clarifications that you would find useful. Include the following
information:

■ The name and version of your manual


■ Any comments that you have about the manual
■ Your name, address, and phone number

Send electronic mail to us at the following address:

[email protected]

This address is reserved for reporting errors and omissions in our documen-
tation. For immediate help with a technical problem, contact Customer
Services.

20 IBM Informix Guide to SQL: Syntax


Chapter

Overview of SQL Syntax


1
In This Chapter . . . . . . . . . . . . . . . . . . . . 1-3
How to Enter SQL Statements . . . . . . . . . . . . . . . 1-3
How to Enter SQL Comments . . . . . . . . . . . . . . . 1-6
Categories of SQL Statements . . . . . . . . . . . . . . . 1-9
ANSI Compliance and Extensions . . . . . . . . . . . . . 1-13
1-2 IBM Informix Guide to SQL: Syntax
In This Chapter
This chapter provides information about how to use the SQL statements, SPL
statements, and segments that are discussed in the later chapters of this book.
It is organized into the following sections.

Section Page Scope

“How to Enter SQL 1-3 How to use the statement diagrams and descrip-
Statements” tions to enter SQL statements correctly

“How to Enter SQL 1-6 How to enter comments for SQL statements
Comments”

“Categories of SQL 1-9 The SQL statements, listed by functional category


Statements”

“ANSI Compliance 1-13 The SQL statements, listed by degree of ANSI


and Extensions” compliance

How to Enter SQL Statements


Statement descriptions are provided in this manual to help you to enter SQL
statements successfully. A statement description includes this information:

■ A brief introduction that explains what the statement does


■ A syntax diagram that shows how to enter the statement correctly
■ A table that explains each input parameter in the syntax diagram
■ Rules of usage, typically with examples that illustrate these rules

If a statement can include multiple clauses, this information is provided for


each clause.

Overview of SQL Syntax 1-3


How to Enter SQL Statements

Most statement descriptions conclude with references to related information


in this manual and in other manuals.

The major aids for entering SQL statements include:

■ The combination of the syntax diagram and syntax table


■ The examples of syntax that appear in the rules of usage
■ The references to related information

Using Syntax Diagrams and Syntax Tables


Before you try to use the syntax diagrams in this chapter, it is helpful to read
the “Syntax Conventions” on page 12 of the Introduction. This section is the
key to understanding the syntax diagrams in the statement descriptions, and
explains the elements that can appear in a syntax diagram and the paths that
connect the elements to each other. This section also includes an example that
illustrates the elements of typical syntax diagrams. The narrative that follows
the example diagram shows how to read the diagram in order to enter the
statement successfully.

When a syntax diagram includes input specifications, such as identifiers,


expressions, filenames. host variables, or other terms, the syntax diagram is
followed by a table that describes how to enter the term without generating
errors. Each syntax table includes four columns:

■ The Elements column lists the name of each variable term that
appears in the syntax diagram.
■ The Purpose column briefly describes the term, and identifies the
default value, if the term has one.
■ The Restrictions column summarizes the restrictions on the term,
such as acceptable ranges of values. (For some diagrams, restrictions
that cannot be tersely summarized appear in the Usage notes, rather
than in this column.)
■ The Syntax column points to the SQL segment that gives the detailed
syntax for the term. For a few terms, such as the names of host
variables or literal characters, no page reference is provided.

The diagrams generally provide an intuitive notation for what is valid in a


given SQL statement, but for some statements, dependencies or restrictions
among syntax elements are identified only in the text of the Usage section.

1-4 IBM Informix Guide to SQL: Syntax


How to Enter SQL Statements

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:

■ To show how to accomplish specific tasks with the statement or its


clauses
■ To show how to use the syntax of the statement or its clauses in a
concrete way
Tip: An efficient way to understand a syntax diagram is to find an example of the
syntax and compare it with the keywords and parameters in the syntax diagram. By
mapping the concrete elements of the example to the abstract elements of the syntax
diagram, you can understand the syntax diagram and use it more effectively.

For an explanation of the conventions used in the examples in this manual,


see “Example-Code Conventions” on page 16 of the Introduction.

These code examples are program fragments to illustrate valid syntax, rather
than complete SQL programs. In some code examples, ellipsis ( . . . ) symbols
indicate that additional code has been omitted. To save space, however,
ellipses are not shown at the beginning or end of the program fragments.

Using Related Information


For help in understanding the concepts and terminology in the SQL
statement description, check the “Related Information” section at the end of
each statement.

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
“IBM Informix Guide to SQL: Tutorial” gives you the basic SQL knowledge that you
need to understand and use the statement descriptions in this manual.

Overview of SQL Syntax 1-5


How to Enter SQL Comments

How to Enter SQL Comments


You can add comments to clarify the purpose or effect of particular SQL state-
ments. You can also use comment symbols during program development to
disable individual statements without deleting them from your source code.

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, but your own SQL programs will be easier
to read and to maintain if you document them with frequent comments.

The following table shows the SQL comment indicators that you can enter in
your code. Here a Y in a column signifies that you can use the symbol with
the product or with the database type identified in the column heading. An
N in a column signifies that you cannot use the symbol with the indicated
product or database type. (For additional information about a special use of
comments, see the section “Optimizer Directives” on page 4-222.)

ANSI- Databases
Comment SPL Compliant Not ANSI
Symbol ESQL/C Routine DB-Access Databases Compliant Description

double Y Y Y Y Y The double hyphen precedes a


hyphen comment within a single line. To
(--) comment more than one line, you must
put the double hyphen symbols at the
beginning of each comment line.

braces N Y Y Y Y Braces enclose the comment. The {


({}) precedes the comment, and the }
follows it. Braces can delimit single-
line or multiple-line comments, but
comments cannot be nested.

Characters within the comment are ignored by the database server.

IDS The section “Optimizer Directives” on page 4-222 describes a context where
information that you specify within comments can influence query plans of
the database server, and where (besides comments in these two formats),
comments in the style of the C language are also valid. ♦

1-6 IBM Informix Guide to SQL: Syntax


How to Enter SQL Comments

ANSI If the product that you are using supports both comment symbols, your
choice of a comment symbol depends on requirements for ANSI compliance:

■ Double hyphen ( -- ) complies with the ANSI/ISO standard for SQL.


■ Braces ( { } ) are an Informix extension to the ANSI/ISO standard.

If ANSI compliance is not an issue, your choice of comment symbols is a


matter of personal preference. ♦

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 IBM 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 IBM Informix DB-Access User’s Guide. ♦

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
IBM Informix Guide to SQL: Tutorial. ♦

E/C In ESQL/C, the double hyphen ( -- ) can begin a comment that extends to the
end of the same line. For information on language-specific comment symbols
in ESQL/C programs, see the IBM Informix ESQL/C Programmer’s Manual. ♦

Examples of SQL Comment Symbols


These examples illustrate different ways to use the SQL comment indicators.

Examples of the Double-Hyphen Symbol


The next example uses the double hyphen ( -- ) to include a comment after
an SQL statement. The comment appears on the same line as the statement.
SELECT * FROM customer -- Selects all columns and rows

The following example uses 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

Overview of SQL Syntax 1-7


How to Enter SQL Comments

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

DB Examples of the Braces Symbols


SPL This example uses braces ( { } ) to delimit a comment after an SQL statement.
In this example, the comment appears on the same line as the statement.
SELECT * FROM customer {Selects all columns and rows}

The next example uses the same SQL statement and the same comment as in
the preceding example, but the comment appears on a line by itself:
SELECT * FROM customer
{Selects all columns and rows}

In the following example, the same SQL statement as in the preceding


example is followed by a multiple-line comment:
SELECT * FROM customer
{Selects all columns and rows
from the customer table}

GLS Non-ASCII Characters in SQL Comments


You can enter non-ASCII characters (including multibyte characters) in SQL
comments if the database locale supports the non-ASCII characters. For
further information on the GLS aspects of SQL comments, see the IBM Informix
GLS User’s Guide.

1-8 IBM Informix Guide to SQL: Syntax


Categories of SQL Statements

Categories of SQL Statements


SQL statements are traditionally divided into these twelve logical categories:

■ Data definition statements. These data definition language (DDL)


statements can declare, rename, modify, or destroy database objects.
■ Data manipulation statements. These data manipulation language
(DML) statements can retrieve, insert, delete, or modify data values.
■ Cursor manipulation statements. These statements can declare,
open, and close cursors, which are data structures for operations on
multiple rows of data.
■ Cursor optimization statements. These statements can be used to
improve the performance of cursors.
■ Dynamic management statements. These statements support
memory management and allow users to specify at runtime the
details of DML operations.
■ Data access statements. These statements specify access privileges
and support concurrent access to the database by multiple users.
■ Data integrity statements. These implement transaction logging and
support the referential integrity of the database.
■ Optimization statements. These can be used to improve the perfor-
mance of operations on the database.
■ Routine definition statements. These can declare, define, modify,
execute, or destroy user-defined routines that the database stores.
■ Client/server connection statements. These can open or close a
connection between a database and a client application.
■ Auxiliary statements. These can provide information about the
database. (This is also a residual category for statements that are not
closely related to the other statement categories.)
■ Optical subsystem statements. These support storage and retrieval
of database objects in the optical subsystem, whose statements are
separately documented in IBM Informix Optical Subsystem Guide.)

The SQL statements of each category are listed in the pages that follow.
As their descriptions in Chapter 3 indicate, some statements (and options of
some statements, as designated with special icons in the syntax diagrams) are
specific to Dynamic Server or to Extended Parallel Server.

Overview of SQL Syntax 1-9


Categories of SQL Statements

Data Definition Statements


ALTER ACCESS_METHOD CREATE SYNONYM
ALTER FRAGMENT CREATE TABLE
ALTER FUNCTION CREATE Temporary TABLE
ALTER INDEX CREATE TRIGGER
ALTER PROCEDURE CREATE VIEW
ALTER ROUTINE DROP ACCESS_METHOD
ALTER SEQUENCE DROP AGGREGATE
ALTER TABLE DROP CAST
CLOSE DATABASE DROP DATABASE
CREATE ACCESS_METHOD DROP DUPLICATE
CREATE AGGREGATE DROP FUNCTION
CREATE CAST DROP INDEX
CREATE DATABASE DROP OPCLASS
CREATE DISTINCT TYPE DROP PROCEDURE
CREATE DUPLICATE DROP ROLE
CREATE EXTERNAL TABLE DROP ROUTINE
CREATE FUNCTION DROP ROW TYPE
CREATE FUNCTION FROM DROP SEQUENCE
CREATE INDEX DROP SYNONYM
CREATE OPAQUE TYPE DROP TABLE
CREATE OPCLASS DROP TRIGGER
CREATE PROCEDURE DROP TYPE
CREATE PROCEDURE FROM DROP VIEW
CREATE ROLE RENAME COLUMN
CREATE ROUTINE FROM RENAME DATABASE
CREATE ROW TYPE RENAME INDEX
CREATE SCHEMA RENAME SEQUENCE
CREATE SEQUENCE RENAME TABLE

Data Manipulation Statements


DELETE LOAD
INSERT TRUNCATE
SELECT UNLOAD
UPDATE

1-10 IBM Informix Guide to SQL: Syntax


Categories of SQL Statements

Cursor Manipulation Statements


CLOSE FREE
DECLARE OPEN
FETCH PUT
FLUSH SET AUTOFREE

Cursor Optimization Statements


SET AUTOFREE SET DEFERRED_PREPARE

Dynamic Management Statements


ALLOCATE COLLECTION EXECUTE
ALLOCATE DESCRIPTOR EXECUTE IMMEDIATE
ALLOCATE ROW FREE
DEALLOCATE COLLECTION GET DESCRIPTOR
DEALLOCATE DESCRIPTOR INFO
DEALLOCATE ROW PREPARE
DESCRIBE SET DEFERRED_PREPARE
DESCRIBE INPUT SET DESCRIPTOR

Data Access Statements


GRANT SET LOCK MODE
GRANT FRAGMENT SET ROLE
LOCK TABLE SET SESSION AUTHORIZATION
REVOKE SET TRANSACTION
REVOKE FRAGMENT SET Transaction Mode
SET ISOLATION UNLOCK TABLE

Data Integrity Statements


BEGIN WORK SET PLOAD FILE
COMMIT WORK SET Transaction Mode
ROLLBACK WORK START VIOLATIONS TABLE
SET Database Object Mode STOP VIOLATIONS TABLE
SET LOG

Overview of SQL Syntax 1-11


Categories of SQL Statements

Optimization Statements
SET Default Table Space SET PDQPRIORITY
SET Default Table Type SET Residency
SET ENVIRONMENT SET SCHEDULE LEVEL
SET EXPLAIN SET STATEMENT CACHE
SET OPTIMIZATION UPDATE STATISTICS

Routine Definition Statements


ALTER FUNCTION CREATE ROUTINE FROM
ALTER PROCEDURE DROP FUNCTION
ALTER ROUTINE DROP PROCEDURE
CREATE FUNCTION DROP ROUTINE
CREATE FUNCTION FROM EXECUTE FUNCTION
CREATE PROCEDURE EXECUTE PROCEDURE
CREATE PROCEDURE FROM SET DEBUG FILE TO

Auxiliary Statements
INFO SET COLLATION
OUTPUT SET DATASKIP
GET DIAGNOSTICS WHENEVER

Client/Server Connection Statements


CONNECT DISCONNECT
DATABASE SET CONNECTION

IDS Optical Subsystem Statements


ALTER OPTICAL CLUSTER RELEASE
CREATE OPTICAL CLUSTER RESERVE
DROP OPTICAL CLUSTER SET MOUNTING TIMEOUT

Important: Optical Subsystem statements are described in the ”IBM Informix


Optical Subsystem Guide.”

1-12 IBM Informix Guide to SQL: Syntax


ANSI Compliance and Extensions

ANSI
ANSI Compliance and Extensions
The following lists show statements that are compliant with the ANSI SQL-92
standard at the entry level, statements that are ANSI compliant but include
Informix extensions, and statements that are Informix extensions to the ANSI
standard.

ANSI-Compliant Statements
CLOSE ROLLBACK WORK
COMMIT WORK SET SESSION AUTHORIZATION
EXECUTE IMMEDIATE SET TRANSACTION

ANSI-Compliant Statements with Informix Extensions


CONNECT FETCH
CREATE SCHEMA AUTHORIZATION GRANT
CREATE TABLE INSERT
CREATE Temporary TABLE OPEN
CREATE VIEW SELECT
DECLARE SET CONNECTION
DELETE SET Transaction Mode
DISCONNECT UPDATE
EXECUTE WHENEVER

Statements That Are Extensions to the ANSI Standard


ALLOCATE COLLECTION ALTER INDEX
ALLOCATE DESCRIPTOR ALTER OPTICAL CLUSTER
ALLOCATE ROW ALTER PROCEDURE
ALTER ACCESS_METHOD ALTER ROUTINE
ALTER FRAGMENT ALTER SEQUENCE
ALTER FUNCTION ALTER TABLE

BEGIN WORK

Overview of SQL Syntax 1-13


ANSI Compliance and Extensions

CLOSE DATABASE CREATE OPAQUE TYPE


CREATE ACCESS_METHOD CREATE OPCLASS
CREATE AGGREGATE CREATE OPTICAL CLUSTER
CREATE CAST CREATE PROCEDURE
CREATE DATABASE CREATE PROCEDURE FROM
CREATE DISTINCT TYPE CREATE ROLE
CREATE DUPLICATE CREATE ROUTINE FROM
CREATE EXTERNAL TABLE CREATE ROW TYPE
CREATE FUNCTION CREATE SEQUENCE
CREATE FUNCTION FROM CREATE SYNONYM
CREATE INDEX CREATE TRIGGER

DATABASE DROP INDEX


DEALLOCATE COLLECTION DROP OPCLASS
DEALLOCATE DESCRIPTOR DROP OPTICAL CLUSTER
DEALLOCATE ROW DROP PROCEDURE
DESCRIBE DROP ROLE
DESCRIBE INPUT DROP ROUTINE
DROP ACCESS_METHOD DROP ROW TYPE
DROP AGGREGATE DROP SEQUENCE
DROP CAST DROP SYNONYM
DROP DATABASE DROP TABLE
DROP DUPLICATE DROP TRIGGER
DROP FUNCTION DROP TYPE
DROP VIEW

EXECUTE FUNCTION FLUSH


EXECUTE PROCEDURE FREE

GET DESCRIPTOR GRANT FRAGMENT


GET DIAGNOSTICS INFO

LOAD LOCK TABLE

OUTPUT

PREPARE PUT

1-14 IBM Informix Guide to SQL: Syntax


ANSI Compliance and Extensions

RELEASE RENAME TABLE


RENAME COLUMN RESERVE
RENAME DATABASE REVOKE
RENAME INDEX REVOKE FRAGMENT
RENAME SEQUENCE

SET AUTOFREE SET LOCK MODE


SET COLLATION SET LOG
SET Database Object Mode SET MOUNTING TIMEOUT
SET DATASKIP SET OPTIMIZATION
SET DEBUG FILE TO SET PDQPRIORITY
SET Default Table Type SET PLOAD FILE
SET Default Table Space SET RESIDENCY
SET DEFERRED_PREPARE SET ROLE
SET DESCRIPTOR SET SCHEDULE LEVEL
SET ENVIRONMENT SET STATEMENT CACHE
SET EXPLAIN START VIOLATIONS TABLE
SET ISOLATION STOP VIOLATIONS TABLE

TRUNCATE

UNLOAD UNLOCK TABLE


UPDATE STATISTICS

Overview of SQL Syntax 1-15


Chapter

SQL Statements
2
In This Chapter . . . . . . . . . . . . . . . . . . . . 2-7
ALLOCATE COLLECTION . . . . . . . . . . . . . . . . 2-8
ALLOCATE DESCRIPTOR . . . . . . . . . . . . . . . . 2-10
ALLOCATE ROW . . . . . . . . . . . . . . . . . . . 2-12
ALTER ACCESS_METHOD . . . . . . . . . . . . . . . . 2-14
ALTER FRAGMENT . . . . . . . . . . . . . . . . . . 2-16
ALTER FUNCTION . . . . . . . . . . . . . . . . . . 2-39
ALTER INDEX . . . . . . . . . . . . . . . . . . . . 2-41
ALTER PROCEDURE . . . . . . . . . . . . . . . . . . 2-44
ALTER ROUTINE . . . . . . . . . . . . . . . . . . . 2-46
ALTER SEQUENCE . . . . . . . . . . . . . . . . . . 2-49
ALTER TABLE . . . . . . . . . . . . . . . . . . . . 2-52
BEGIN WORK . . . . . . . . . . . . . . . . . . . . 2-82
CLOSE . . . . . . . . . . . . . . . . . . . . . . . 2-85
CLOSE DATABASE . . . . . . . . . . . . . . . . . . 2-88
COMMIT WORK . . . . . . . . . . . . . . . . . . . 2-90
CONNECT . . . . . . . . . . . . . . . . . . . . . 2-92
CREATE ACCESS_METHOD . . . . . . . . . . . . . . . 2-102
CREATE AGGREGATE . . . . . . . . . . . . . . . . . 2-104
CREATE CAST . . . . . . . . . . . . . . . . . . . . 2-108
CREATE DATABASE . . . . . . . . . . . . . . . . . . 2-112
CREATE DISTINCT TYPE . . . . . . . . . . . . . . . . 2-115
CREATE DUPLICATE. . . . . . . . . . . . . . . . . . 2-118
CREATE EXTERNAL TABLE . . . . . . . . . . . . . . . 2-121
CREATE FUNCTION . . . . . . . . . . . . . . . . . . 2-133
CREATE FUNCTION FROM . . . . . . . . . . . . . . . 2-141
CREATE INDEX . . . . . . . . . . . . . . . . . . . . 2-144
CREATE OPAQUE TYPE . . . . . . . . . . . . . . . . . 2-169
CREATE OPCLASS . . . . . . . . . . . . . . . . . . . 2-176
CREATE PROCEDURE . . . . . . . . . . . . . . . . . 2-182
CREATE PROCEDURE FROM . . . . . . . . . . . . . . . 2-192
CREATE ROLE . . . . . . . . . . . . . . . . . . . . 2-194
CREATE ROUTINE FROM . . . . . . . . . . . . . . . . 2-196
CREATE ROW TYPE . . . . . . . . . . . . . . . . . . 2-198
CREATE SCHEMA . . . . . . . . . . . . . . . . . . . 2-203
CREATE SCRATCH TABLE . . . . . . . . . . . . . . . . 2-205
CREATE SEQUENCE . . . . . . . . . . . . . . . . . . 2-206
CREATE SYNONYM . . . . . . . . . . . . . . . . . . 2-210
CREATE TABLE . . . . . . . . . . . . . . . . . . . . 2-214
CREATE TEMP TABLE . . . . . . . . . . . . . . . . . 2-260
CREATE Temporary TABLE . . . . . . . . . . . . . . . . 2-261
CREATE TRIGGER . . . . . . . . . . . . . . . . . . . 2-269
CREATE VIEW . . . . . . . . . . . . . . . . . . . . 2-310
DATABASE . . . . . . . . . . . . . . . . . . . . . 2-316
DEALLOCATE COLLECTION . . . . . . . . . . . . . . . 2-318
DEALLOCATE DESCRIPTOR . . . . . . . . . . . . . . . 2-320
DEALLOCATE ROW . . . . . . . . . . . . . . . . . . 2-322
DECLARE . . . . . . . . . . . . . . . . . . . . . . 2-323
DELETE. . . . . . . . . . . . . . . . . . . . . . . 2-344
DESCRIBE . . . . . . . . . . . . . . . . . . . . . . 2-351
DESCRIBE INPUT . . . . . . . . . . . . . . . . . . . 2-359
DISCONNECT . . . . . . . . . . . . . . . . . . . . 2-366
DROP ACCESS_METHOD . . . . . . . . . . . . . . . . 2-369
DROP AGGREGATE . . . . . . . . . . . . . . . . . . 2-370
DROP CAST . . . . . . . . . . . . . . . . . . . . . 2-371
DROP DATABASE . . . . . . . . . . . . . . . . . . . 2-372
DROP DUPLICATE. . . . . . . . . . . . . . . . . . . 2-374
DROP FUNCTION . . . . . . . . . . . . . . . . . . . 2-375
DROP INDEX. . . . . . . . . . . . . . . . . . . . . 2-377
DROP OPCLASS. . . . . . . . . . . . . . . . . . . . 2-378
DROP PROCEDURE . . . . . . . . . . . . . . . . . . 2-379
DROP ROLE . . . . . . . . . . . . . . . . . . . . . 2-381
DROP ROUTINE . . . . . . . . . . . . . . . . . . . 2-382

2-2 IBM Informix Guide to SQL: Syntax


DROP ROW TYPE. . . . . . . . . . . . . . . . . . . . 2-384
DROP SEQUENCE . . . . . . . . . . . . . . . . . . . 2-386
DROP SYNONYM . . . . . . . . . . . . . . . . . . . 2-387
DROP TABLE . . . . . . . . . . . . . . . . . . . . . 2-388
DROP TRIGGER . . . . . . . . . . . . . . . . . . . . 2-391
DROP TYPE . . . . . . . . . . . . . . . . . . . . . . 2-392
DROP VIEW. . . . . . . . . . . . . . . . . . . . . . 2-393
EXECUTE . . . . . . . . . . . . . . . . . . . . . . 2-394
EXECUTE FUNCTION . . . . . . . . . . . . . . . . . . 2-404
EXECUTE IMMEDIATE. . . . . . . . . . . . . . . . . . 2-411
EXECUTE PROCEDURE . . . . . . . . . . . . . . . . . 2-414
FETCH . . . . . . . . . . . . . . . . . . . . . . . 2-424
FLUSH . . . . . . . . . . . . . . . . . . . . . . . 2-435
FREE . . . . . . . . . . . . . . . . . . . . . . . . 2-437
GET DESCRIPTOR . . . . . . . . . . . . . . . . . . . 2-439
GET DIAGNOSTICS . . . . . . . . . . . . . . . . . . . 2-446
GRANT . . . . . . . . . . . . . . . . . . . . . . . 2-459
GRANT FRAGMENT . . . . . . . . . . . . . . . . . . 2-480
INFO . . . . . . . . . . . . . . . . . . . . . . . . 2-487
INSERT . . . . . . . . . . . . . . . . . . . . . . . 2-489
LOAD . . . . . . . . . . . . . . . . . . . . . . . . 2-504
LOCK TABLE . . . . . . . . . . . . . . . . . . . . . 2-513
OPEN . . . . . . . . . . . . . . . . . . . . . . . . 2-516
OUTPUT . . . . . . . . . . . . . . . . . . . . . . . 2-525
PREPARE. . . . . . . . . . . . . . . . . . . . . . . 2-527
PUT. . . . . . . . . . . . . . . . . . . . . . . . . 2-539
RENAME COLUMN . . . . . . . . . . . . . . . . . . . 2-549
RENAME DATABASE . . . . . . . . . . . . . . . . . . 2-551
RENAME INDEX . . . . . . . . . . . . . . . . . . . . 2-552
RENAME SEQUENCE . . . . . . . . . . . . . . . . . . 2-553
RENAME TABLE . . . . . . . . . . . . . . . . . . . . 2-554
REVOKE . . . . . . . . . . . . . . . . . . . . . . . 2-557
REVOKE FRAGMENT . . . . . . . . . . . . . . . . . . 2-575
ROLLBACK WORK . . . . . . . . . . . . . . . . . . . 2-579
SELECT . . . . . . . . . . . . . . . . . . . . . . . 2-581
SET AUTOFREE . . . . . . . . . . . . . . . . . . . . 2-640

SQL Statements 2-3


SET COLLATION . . . . . . . . . . . . . . . . . . . 2-643
SET CONNECTION . . . . . . . . . . . . . . . . . . 2-646
SET CONSTRAINTS . . . . . . . . . . . . . . . . . . 2-651
SET Database Object Mode . . . . . . . . . . . . . . . . 2-652
SET DATASKIP . . . . . . . . . . . . . . . . . . . . 2-659
SET DEBUG FILE TO . . . . . . . . . . . . . . . . . . 2-661
SET Default Table Type . . . . . . . . . . . . . . . . . 2-663
SET Default Table Space . . . . . . . . . . . . . . . . . 2-665
SET DEFERRED_PREPARE . . . . . . . . . . . . . . . . 2-666
SET DESCRIPTOR . . . . . . . . . . . . . . . . . . . 2-670
SET ENVIRONMENT . . . . . . . . . . . . . . . . . . 2-678
SET EXPLAIN . . . . . . . . . . . . . . . . . . . . 2-683
SET INDEX . . . . . . . . . . . . . . . . . . . . . 2-689
SET INDEXES. . . . . . . . . . . . . . . . . . . . . 2-690
SET ISOLATION . . . . . . . . . . . . . . . . . . . . 2-691
SET LOCK MODE . . . . . . . . . . . . . . . . . . . 2-696
SET LOG . . . . . . . . . . . . . . . . . . . . . . 2-698
SET OPTIMIZATION . . . . . . . . . . . . . . . . . . 2-700
SET PDQPRIORITY. . . . . . . . . . . . . . . . . . . 2-704
SET PLOAD FILE . . . . . . . . . . . . . . . . . . . 2-707
SET Residency . . . . . . . . . . . . . . . . . . . . 2-708
SET ROLE . . . . . . . . . . . . . . . . . . . . . . 2-710
SET SCHEDULE LEVEL . . . . . . . . . . . . . . . . . 2-712
SET SESSION AUTHORIZATION. . . . . . . . . . . . . . 2-713
SET STATEMENT CACHE . . . . . . . . . . . . . . . . 2-715
SET TABLE. . . . . . . . . . . . . . . . . . . . . . 2-719
SET TRANSACTION . . . . . . . . . . . . . . . . . . 2-720
SET Transaction Mode . . . . . . . . . . . . . . . . . . 2-725
SET TRIGGERS . . . . . . . . . . . . . . . . . . . . 2-728
START VIOLATIONS TABLE . . . . . . . . . . . . . . . 2-729
STOP VIOLATIONS TABLE . . . . . . . . . . . . . . . . 2-748
TRUNCATE . . . . . . . . . . . . . . . . . . . . . 2-750
UNLOAD . . . . . . . . . . . . . . . . . . . . . . 2-753
UNLOCK TABLE . . . . . . . . . . . . . . . . . . . 2-760
UPDATE . . . . . . . . . . . . . . . . . . . . . . 2-762

2-4 IBM Informix Guide to SQL: Syntax


UPDATE STATISTICS . . . . . . . . . . . . . . . . . . 2-778
WHENEVER . . . . . . . . . . . . . . . . . . . . . 2-789

SQL Statements 2-5


2-6 IBM Informix Guide to SQL: Syntax
In This Chapter
This chapter describes the syntax and semantics of SQL statements that are
recognized by Dynamic Server or Extended Parallel Server. Statements (and
statement segments, and notes describing usage) that are not marked by the
icon for one of these database servers are valid for both.

The statement descriptions appear in alphabetical order. For some state-


ments, important details of the semantics appear in other volumes of this
documentation set, as indicated by cross-references.

For many statements, the syntax diagram, or the table of terms immediately
following the diagram, or both, can includes references to syntax segments in
Chapter 4, “Segments.”

When the name of an SQL statement includes lowercase characters, such as


”CREATE Temporary TABLE,” it means that two or more different keywords
can follow the preceding uppercase keyword.

For an explanation of the structure of statement descriptions, see Chapter 1,


“Overview of SQL Syntax.”

SQL Statements 2-7


ALLOCATE COLLECTION

+ ALLOCATE COLLECTION
IDS
Use the ALLOCATE COLLECTION statement to allocate memory for a variable
E/C of a collection data type (such as LIST, MULTISET, or SET) or an untyped
collection variable. Use this statement with ESQL/C.

Syntax

ALLOCATE COLLECTION variable

Element Purpose Restrictions Syntax


variable Name of typed or untyped Must be an unallocated ESQL/C Must conform to language-
collection variable to allocate collection-type host variable specific rules for names

Usage
The ALLOCATE COLLECTION statement allocates memory for an ESQL/C
variable that can store the value of a collection data type.

To create a collection variable for an ESQL/C program

1. Declare the collection variable as a client collection variable in an


ESQL/C program.
The collection variable can be a typed or untyped collection variable.
2. Allocate memory for the collection variable with the ALLOCATE
COLLECTION statement.

The ALLOCATE COLLECTION statement sets SQLCODE (sqlca.sqlcode) to


zero (0) if the memory allocation was successful and to a negative error code
if the allocation failed.

You must explicitly release memory with the DEALLOCATE COLLECTION


statement. After you free the collection variable with the DEALLOCATE
COLLECTION statement, you can reuse the collection variable.

2-8 IBM Informix Guide to SQL: Syntax


ALLOCATE COLLECTION

Tip: The ALLOCATE COLLECTION statement allocates memory for an ESQL/C


collection variable only. To allocate memory for an ESQL/C row variable, use the
ALLOCATE ROW statement.

Examples
The following example shows how to allocate resources with the ALLOCATE
COLLECTION statement for the untyped collection variable, a_set:

EXEC SQL BEGIN DECLARE SECTION;


client collection a_set;
EXEC SQL END DECLARE SECTION;
. . .
EXEC SQL allocate collection :a_set;
. . .

The following example uses ALLOCATE COLLECTION to allocate resources


for a typed collection variable, a_typed_set:
EXEC SQL BEGIN DECLARE SECTION;
client collection set(integer not null) a_typed_set;
EXEC SQL END DECLARE SECTION;
. . .
EXEC SQL allocate collection :a_typed_set;
. . .

Related Information
Related examples: Refer to the collection-variable example in PUT.

Related statements: ALLOCATE ROW and DEALLOCATE COLLECTION

For a discussion of collection data types in ESQL/C programs, see the


IBM Informix ESQL/C Programmer’s Manual.

SQL Statements 2-9


ALLOCATE DESCRIPTOR

+ ALLOCATE DESCRIPTOR
E/C
Use the ALLOCATE DESCRIPTOR statement to allocate memory for a system-
descriptor area. Use this statement with ESQL/C.

Syntax

ALLOCATE DESCRIPTOR 'descriptor '


descriptor_var WITH MAX items

items_var

Element Purpose Restrictions Syntax


descriptor Quoted string that identifies a Use single ( ' ) quotes. Must be the Quoted String,
system-descriptor area unique name of an unallocated p. 4-243
system-descriptor area
descriptor_var Host variable that contains the name Must contain name of an unallo- Language
of a system-descriptor area cated system-descriptor area specific
items Number of item descriptors in Must be an unsigned INTEGER Literal Number,
descriptor. Default value is 100. greater than zero p. 4-216
items_var Host variable that contains the Data type must be INTEGER or Language
number of items SMALLINT specific

Usage
The ALLOCATE DESCRIPTOR statement creates a system-descriptor area, which
is a location in memory to hold information that a DESCRIBE statement
obtains, or to hold information about the WHERE clause of a statement.
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 data type, length, scale, precision, and nullability.

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.

2-10 IBM Informix Guide to SQL: Syntax


ALLOCATE DESCRIPTOR

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.

WITH MAX Clause


You can use the WITH MAX clause to indicate the maximum number of item
descriptors you need. When you use this clause, the COUNT field is set to the
number of items that you specify. If you do not specify the WITH MAX clause,
the default value of the COUNT field is 100. You can change the value of the
COUNT field with the SET DESCRIPTOR statement.

The following examples show valid ALLOCATE DESCRIPTOR statements.


Each example includes the WITH MAX clause. The first line uses embedded
variable names to identify the system-descriptor area and to specify the
desired number of item descriptors. The second line uses a quoted string to
identify the system-descriptor area and an unsigned integer to specify the
desired number of item descriptors.
EXEC SQL allocate descriptor :descname with max :occ;

EXEC SQL allocate descriptor 'desc1' with max 3;

Related Information
Related statements: DEALLOCATE DESCRIPTOR, DECLARE, DESCRIBE,
EXECUTE, FETCH, GET DESCRIPTOR, OPEN, PREPARE, PUT, and SET
DESCRIPTOR

For more information on system-descriptor areas, refer to the IBM Informix


ESQL/C Programmer’s Manual.

SQL Statements 2-11


ALLOCATE ROW

+ ALLOCATE ROW
IDS
Use the ALLOCATE ROW statement to allocate memory for a ROW variable.
E/C Use this statement with ESQL/C.

Syntax

ALLOCATE ROW variable

Element Purpose Restrictions Syntax


variable Name of a typed or untyped Must be an unallocated ESQL/C Must conform to language-
ROW variable to allocate ROW-type host variable. specific rules for names.

Usage
The ALLOCATE ROW statement allocates memory for a variable that stores
ROW-type data.

To create a row variable using your ESQL/C program

1. Declare the ROW variable.


The ROW variable can be a typed or untyped ROW variable.
2. Allocate memory for the ROW variable with the ALLOCATE ROW
statement.

The ALLOCATE ROW statement sets SQLCODE (sqlca.sqlcode) to zero (0) if


the memory allocation was successful and to a negative error code if the
allocation failed.

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.

2-12 IBM Informix Guide to SQL: Syntax


ALLOCATE ROW

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:

EXEC SQL BEGIN DECLARE SECTION;


row (a int, b int) a_row;
EXEC SQL END DECLARE SECTION;
. . .
EXEC SQL allocate row :a_row;

Related Information
Related statements: ALLOCATE COLLECTION and DEALLOCATE ROW

For a discussion of complex data types in ESQL/C programs, see the


IBM Informix ESQL/C Programmer’s Manual.

SQL Statements 2-13


ALTER ACCESS_METHOD

+ ALTER ACCESS_METHOD
IDS
The ALTER ACCESS_METHOD statement changes the attributes of a user-
defined access method in the sysams system catalog table.

Syntax
,
ALTER ACCESS_METHOD access_method Purpose
MODIFY Option
p. 4-237
ADD

DROP purpose_keyword

Element Purpose Restrictions Syntax


access_method Name of the access The access method must be registered in the Database Object
method to alter sysams system catalog table with a previous Name, p. 4-46
CREATE ACCESS_METHOD statement
purpose_keyword A keyword that The keyword must be associated with the Purpose Functions,
indicates which access method by a previous statement Methods, Flags, and
feature to change Values, p. 4-239

Usage
Use ALTER ACCESS_METHOD to modify the definition of a user-defined
access method. You must be the owner of the access method or have DBA
privileges to alter an access method.

When you alter an access method, you change the purpose-option specifica-
tions (purpose functions, purpose methods, purpose flags, or purpose
values) that define the access method. For example, you might alter an access
method to assign a new user-defined function or method name or to provide
a multiplier for the scan cost on a table.

If a transaction is in progress, the database server waits to alter the access


method until the transaction is committed or rolled back. No other users can
execute the access method until the transaction has completed.

2-14 IBM Informix Guide to SQL: Syntax


ALTER ACCESS_METHOD

Example
The following statement alters the remote user-defined access method:
ALTER ACCESS_METHOD remote
ADD am_scancost = FS_scancost,
ADD am_rowids,
DROP am_getbyid,
MODIFY am_costfactor = 0.9;

The preceding example makes the following changes to the access method:
■ Adds a user-defined function or method named FS_scancost(),
which is associated in the sysams table with the am_scancost
keyword
■ Sets (adds) the am_rowids flag
■ Drops the user-defined function or method associated with the
am_getbyid keyword
■ Modifies the am_costfactor value

Related Information
Related statements: CREATE ACCESS_METHOD and DROP ACCESS_METHOD

For detailed information about how to set purpose-option specifications, see


“Purpose Options” on page 4-237.

For more information on primary-access methods, see the IBM Informix


Virtual-Table Interface Programmer’s Guide.

For more information on secondary-access methods, see the IBM Informix


Virtual-Index Interface Programmer’s Guide.

For a discussion of privileges, see the GRANT statement or the IBM Informix
Database Design and Implementation Guide.

SQL Statements 2-15


ALTER FRAGMENT

+
ALTER FRAGMENT
Use the ALTER FRAGMENT statement to alter the distribution strategy or
storage location of an existing table or index.

Syntax

ALTER FRAGMENT ON TABLE surviving_table ATTACH Clause


p. 2-19
IDS DETACH Clause
INDEX surviving_index p. 2-27
INIT Clause
p. 2-29
IDS
ADD Clause
p. 2-34
DROP Clause
p. 2-36
MODIFY Clause
p. 2-37

Element Purpose Restrictions Syntax


surviving_index Index on which to modify the Must exist when the statement Database Object
distribution or storage executes Name, p. 4-46
surviving_table Table on which to modify the Must exist. See “Restrictions on the Database Object
distribution or storage ALTER FRAGMENT Statement” on Name, p. 4-46
page 2-17

Usage
The ALTER FRAGMENT statement applies only to table fragments or index
fragments that are located at the current site (or cluster, for Extended Parallel
Server). No remote information is accessed or updated.

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.

2-16 IBM Informix Guide to SQL: Syntax


ALTER FRAGMENT

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.

Clauses of the ALTER FRAGMENT statement support the following tasks.

Clause Purpose

ATTACH Combines tables that contain identical table structures into a single
fragmented table

DETACH Detaches a table fragment or slice from a fragmentation strategy and


places it in a new table

INIT Provides the following options:


■ Defines and initializes a fragmentation strategy on a table
■ Creates a fragmentation strategy for tables
■ Changes the order of evaluation of fragment expressions
■ Alters the fragmentation strategy of an existing table or index
■ Changes the storage location of an existing table

ADD Adds an additional fragment to an existing fragmentation list

DROP Drops an existing fragment from a fragmentation list

MODIFY Changes an existing fragmentation expression

Use the CREATE TABLE statement or the INIT clause of the ALTER FRAGMENT
statement to create fragmented tables.

Restrictions on the ALTER FRAGMENT Statement


You cannot use the ALTER FRAGMENT statement on a temporary table, an
external table, or on a view. If your table or index is not already fragmented,
the only clauses available to you are INIT and ATTACH.

XPS You cannot use ALTER FRAGMENT on a generalized-key (GK) index. If the
surviving_table has hash fragmentation, the only clauses available are
ATTACH and INIT. 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. ♦

SQL Statements 2-17


ALTER FRAGMENT

IDS You cannot use ALTER FRAGMENT on a typed table that is part of a table
hierarchy. ♦

ALTER FRAGMENT and Transaction Logging


If your database uses logging, ALTER FRAGMENT is executed within a single
transaction. When the fragmentation strategy uses large numbers of records,
you might run out of log space or disk space. (The database server requires
extra disk space for the operation; it later frees the disk space).

When you run out of log space or disk space, try one of the following
procedures to make more space available:
■ Turn off logging and turn it back on again at the end of the operation.
This procedure indirectly requires a backup of the root dbspace.
■ Split the operations into multiple ALTER FRAGMENT statements,
moving a smaller portion of records each time.

For information about log-space requirements and disk-space requirements,


see your Administrator’s Guide. That guide also contains detailed instructions
about how to turn off logging. For information about backups, refer to your
IBM Informix Backup and Restore Guide.

Determining the Number of Rows in the Fragment


You can place as many rows into a fragment as the available space in the
dbspace allows.

To find out how many rows are in a fragment

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.

2-18 IBM Informix Guide to SQL: Syntax


ALTER FRAGMENT

ATTACH Clause
Use the ATTACH clause to combine tables that contain identical table
structures into a fragmentation strategy.

ATTACH Back to ALTER FRAGMENT


Clause p. 2-16

,
ATTACH 1 surviving_table

consumed_table AS expression BEFORE dbspace

AFTER
IDS
1 AS REMAINDER

Element Purpose Restrictions Syntax


consumed_ Table that loses its identity Must exist. Cannot include serial columns Database Object
table to be merged with nor unique, referential, or primary key Name, p. 4-46
surviving_table constraints. See also “General Restrictions
for the ATTACH Clause” on page 2-20.
dbspace Dbspace(s) that specifies Must exist. See also “Altering Hybrid- Identifier,
where the consumed table Fragmented Tables” on page 2-22. p. 4-189
expression exists in the
fragmentation list
expression Expression that defines Can include only columns from the Condition,
which rows are stored in a current table, and only data values from a p. 4-24;
fragment single row. See also “General Restrictions Expression,
for the ATTACH Clause” on page 2-20. p. 4-67
surviving_table Table on which to modify Must exist. Cannot have any constraints. Database Object
the distribution or storage See also “Restrictions on the ALTER Name, p. 4-46
FRAGMENT Statement” on page 2-17.

SQL Statements 2-19


ALTER FRAGMENT

To use this clause, you must have the DBA privilege, or else be the owner of
the specified tables. The ATTACH clause supports the following tasks:

■ Creates a single fragmented table by combining two or more identi-


cally-structured, nonfragmented tables
(See “Combining Nonfragmented Tables to Create a Fragmented
Table” on page 2-21.)
■ Attaches one or more tables to a fragmented table
(See “Attaching a Table to a Fragmented Table” on page 2-21.)

General Restrictions for the ATTACH Clause


Any tables that you attach must have been created previously in separate
dbspaces. You cannot attach the same table more than once.

All consumed tables listed in the ATTACH clause must have the same
structure as the surviving table. The number, names, data types, and relative
position of the columns must be identical.

The expression cannot include aggregates, subqueries, nor variant functions.

IDS User-defined routines and references to fields of a row-type column are not
valid. You cannot attach a fragmented table to another fragmented table. ♦

XPS Additional Restrictions on the ATTACH Clause Specific to XPS


In addition to the general restrictions, every consumed table must be of the
same usage type as the surviving table. For information about how to specify
the usage type of a table, refer to “Logging Options” on page 2-215.

The ATTACH clause is not valid under either of the following conditions:
■ If the consumed tables contain data that belongs in some existing
fragment of the surviving table
■ If existing data in the surviving table would belong in a new
fragment

Thus, you cannot use the ATTACH clause for data movement among
fragments. To perform this task, see the “INIT Clause” on page 2-29.

2-20 IBM Informix Guide to SQL: Syntax


ALTER FRAGMENT

Using the BEFORE, AFTER, and REMAINDER Options


The BEFORE and AFTER options allow you to place a new fragment either
before or after an existing dbspace. You cannot use the BEFORE and AFTER
options when the distribution scheme is round-robin.

When you attach a new fragment without an explicit BEFORE or AFTER


option, the database server places the added fragment at the end of the
fragmentation list, unless a remainder fragment exists. If a remainder
fragment exists, the new fragment is placed just before the remainder
fragment. You cannot attach a new fragment after the remainder fragment.

XPS When you create or append to a hybrid-fragmented table, the positioning


specification (BEFORE, AFTER, or REMAINDER) applies to an entire dbslice.
You can use any dbspace in a dbslice to identify the dbslice for the BEFORE or
AFTER position. ♦

Combining Nonfragmented Tables to Create a Fragmented Table


When you transform tables with identical table structures into fragments in
a single table, you allow the database server to manage the fragmentation
instead of allowing the application to manage the fragmentation. The distri-
bution scheme can be round-robin or expression-based.

To make a single, fragmented table from two or more identically-structured,


nonfragmented tables, the ATTACH clause must contain the surviving table
in the attach list. The attach list is the list of tables in the ATTACH clause.

IDS To include a rowid column in the newly-created single, fragmented table,


attach all tables first and then add the rowid with the ALTER TABLE
statement. ♦

Attaching a Table to a Fragmented Table


To attach a nonfragmented table to an already fragmented table, the
nonfragmented table must have been created in a separate dbspace and must
have the same table structure as the fragmented table. In the following
example, a round-robin distribution scheme fragments the table cur_acct,
and the table old_acct is a nonfragmented table that resides in a separate
dbspace. The example shows how to attach old_acct to cur_acct:
ALTER FRAGMENT ON TABLE cur_acct ATTACH old_acct

SQL Statements 2-21


ALTER FRAGMENT

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. ♦

XPS Altering Hybrid-Fragmented Tables


When you alter a hybrid-fragmented table with either an ATTACH or
DETACH clause, you need specify only one dbspace to identify the entire set
of dbspaces that are associated with a given expression in the base fragmen-
tation strategy of the table. The set of dbspaces associated with an expression
in the base fragmentation strategy of the table might have been defined as
one or more dbslices or a dbspaces. For more information, see “Fragmenting
by HYBRID” on page 2-243.

If you know the name of the dbslice but not the names any of the dbspaces
that it is made up of, 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.

Effect of the ATTACH Clause


After an ATTACH operation, 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.

What Happens to Indexes?


In a logging database, an ATTACH operation extends any attached index on
the surviving table according to the new fragmentation strategy of the
surviving table. All rows in the consumed table are subject to these automat-
ically adjusted indexes. For information on whether the database server
completely rebuilds the index on the surviving table or reuses an index that
was on the consumed table, see your Performance Guide.

2-22 IBM Informix Guide to SQL: Syntax


ALTER FRAGMENT

IDS In a nonlogging database, an ATTACH operation does not extend indexes on


the surviving table according to the new fragmentation strategy of the
surviving table. To extend the fragmentation strategy of an attached index
according to the new fragmentation strategy of the surviving table, you must
drop the index and re-create it on the surviving table. ♦

A detached index on the surviving table retains its same fragmentation


strategy. That is, a detached index does not automatically adjust to accom-
modate the new fragmentation of the surviving table. For more information
on what happens to indexes, see the discussion about altering table
fragments in your Performance Guide.

What Happens to BYTE and TEXT Columns?

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 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. ♦

What Happens to Triggers and Views?


When you attach tables, triggers on the surviving table survive the ATTACH,
but triggers on the consumed table are automatically dropped. No triggers
are activated by the ATTACH clause, but subsequent data-manipulation
operations on the new rows can activate triggers.

Views on the surviving table survive the ATTACH operation, but views on the
consumed table are automatically dropped.

SQL Statements 2-23


ALTER FRAGMENT

What Happens with the Distribution Scheme?


You can attach a nonfragmented table to a table with any type of supported
distribution scheme. In general, the resulting table has the same fragmen-
tation strategy as the prior fragmentation strategy of the surviving_table.

When you attach two or more nonfragmented tables, however, the distri-
bution scheme can either be based on expression or round-robin.

IDS The following table shows the distribution schemes that can result from
different distribution schemes of the tables mentioned in the ATTACH clause.

Prior Distribution Scheme Prior Distribution Scheme


of Surviving Table of Consumed Table Resulting Distribution Scheme
None None Round-robin or expression
Round-robin None Round-robin
Expression None Expression

XPS The following table shows the distribution schemes that can result from
different distribution schemes of the tables mentioned in the ATTACH clause.

Prior Distribution Scheme Prior Distribution Scheme


of Surviving Table of Consumed Table Resulting Distribution Scheme
None None Round-robin or expression
None Hash Hybrid
Round-robin None Round-robin
Expression None Expression
Hash None Hybrid
Hash Hash Hybrid
Hybrid None Hybrid
Hybrid Hash Hybrid

When you attach a nonfragmented table to a table that has hash fragmen-
tation, the resulting table has hybrid fragmentation.

2-24 IBM Informix Guide to SQL: Syntax


ALTER FRAGMENT

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. ♦

The following examples illustrate the use of the ATTACH clause to create
fragmented tables with different distribution schemes.

Round-Robin Distribution Scheme


The following example combines nonfragmented tables pen_types and
pen_makers into a single, fragmented table, pen_types. Table pen_types
resides in dbspace dbsp1, and table pen_makers resides in dbspace dbsp2.
Table structures are identical in each table.
ALTER FRAGMENT ON TABLE pen_types ATTACH pen_types, pen_makers

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.

Expression Distribution Scheme


Consider the following example that combines tables cur_acct and new_acct
and uses an expression-based distribution scheme. Table cur_acct was origi-
nally created as a fragmented table and has fragments in dbspaces dbsp1 and
dbsp2. The first statement of the example shows that table cur_acct was
created with an expression-based distribution scheme. The second statement
of the example creates table new_acct in dbsp3 without a fragmentation
strategy. The third statement combines the tables cur_acct and new_acct.
Table structures (columns) are identical in each table.
CREATE TABLE cur_acct (a int) FRAGMENT BY EXPRESSION
a < 5 in dbsp1,
a >= 5 and a < 10 in dbsp2;

CREATE TABLE new_acct (a int) IN dbsp3;

ALTER FRAGMENT ON TABLE cur_acct ATTACH new_acct AS a>=10;

SQL Statements 2-25


ALTER FRAGMENT

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 IBM 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-31.

Warning: When you specify a date value as the default value for a parameter, make
sure to specify 4 digits instead of 2 digits for the year. When you specify a 4-digit year,
the DBCENTURY environment variable has no effect on how the database server
interprets the date value. When you specify a 2-digit year, DBCENTURY can affect
how the database server interprets the date value, so the UDR might not use the
default value that you intended. For more information, see the “IBM Informix Guide
to SQL: Reference.”

XPS Hybrid Fragmentation Distribution Scheme


Consider a case where monthly sales data is added to the sales_info table
defined below. Due to the large amount of data, the table is distributed
evenly across multiple coservers with a system-defined hash function. To
manage monthly additions of data to the table, it is also fragmented by a date
expression. The combined hybrid fragmentation is declared in the following
CREATE TABLE statement:

CREATE TABLE sales_info (order_num INT, sale_date DATE, ...)


FRAGMENT BY HYBRID (order_num) EXPRESSION
sale_date >= '01/01/1996' AND sale_date < '02/01/1996'
IN sales_slice_9601,
sale_date >= '02/01/1996' AND sale_date < '03/01/1996'
IN sales_slice_9602,
. . .
sale_date >= '12/01/1996' AND sale_date < '01/01/1997'
IN sales_slice_9612

The data values for a new month are originally loaded from an external
source. The data values are 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 ...

2-26 IBM Informix Guide to SQL: Syntax


ALTER FRAGMENT

After data values are 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. ♦

For an explanation of distribution schemes, see “FRAGMENT BY Clause for


Tables” on page 2-31.

DETACH Back to ALTER FRAGMENT


Clause p. 2-16

DETACH dbspace new_table

Element Purpose Restrictions Syntax


dbspace Dbspace that contains the fragment to be detached. With Must exist at the Identifier,
a hybrid-fragmented table, dbspace identifies a set of time of execution. p. 4-189
dbspaces (XPS only). See “Altering Hybrid-Fragmented
Tables” on page 2-22.
new_table Nonfragmented table that results after you execute the Must not exist Database Object
ALTER FRAGMENT statement. (In XPS, this can also be before the time of Name, p. 4-46
a hash-fragmented table.) execution.

The new table that results from executing the DETACH clause does not inherit
any indexes or constraints from the original table. Only the data remains.

Similarly, the new table does not inherit any privileges from the original
table. Instead, the new 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-463.

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.

SQL Statements 2-27


ALTER FRAGMENT

XPS In Extended Parallel Server, you cannot use the DETACH clause if the table
has a dependent GK index defined on it. ♦

Detach That Results in a Nonfragmented Table


The following example shows the table cur_acct fragmented into two
dbspaces, dbsp1 and dbsp2:
ALTER FRAGMENT ON TABLE cur_acct DETACH dbsp2 accounts

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. The following
example shows a table that contains three fragments:
ALTER FRAGMENT ON TABLE bus_acct DETACH dbsp3 cli_acct

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.

XPS Detach That Results in a Table with Hash Fragmentation


The new table is a hash-fragmented table if the surviving_table had hybrid
fragmentation and the detached dbslice has more than one fragment. In a
hybrid-fragmented table, the dbslice is detached if you specify any dbspace
in that slice. For example, see the sales_info table discussed in the “Hybrid
Fragmentation Distribution Scheme” on page 2-26. Once the January 1997
data is available in sales_info, you might archive year-old sales_info data.
ALTER FRAGMENT ON TABLE sales_info
DETACH sales_slice_9601.1 jan_96

In this example, data from January 1996 is detached from the sales_info table
and placed in a new table called jan_96.

2-28 IBM Informix Guide to SQL: Syntax


ALTER FRAGMENT

INIT Clause
The INIT clause of ALTER FRAGMENT has the following syntax.

INIT Back to ALTER FRAGMENT


Clause p. 2-16

FRAGMENT BY Clause for Tables


INIT p. 2-31
IDS
IN dbspace
WITH ROWIDS
IDS FRAGMENT BY Clause for Indexes
p. 2-33
XPS
IN dbslice

Element Purpose Restrictions Syntax


dbslice Dbslice storing fragmented information Must exist at time of execution. Identifier, p. 4-189
dbspace Dbspace storing fragmented information Must exist at time of execution. Identifier, p. 4-189

The INIT clause can accomplish tasks like the following:


■ Move a nonfragmented table from one dbspace to another dbspace.
■ Convert a fragmented table to a nonfragmented table.
■ Fragment an existing not fragmented table without redefining it.
■ Convert a fragmentation strategy to another fragmentation strategy.
IDS ■ Fragment an existing index that is not fragmented without
redefining the index.
■ Convert a fragmented index to a nonfragmented index. ♦

XPS You cannot use the INIT clause to change the fragmentation strategy of a table
that has a GK index. ♦

When you use the INIT clause to modify a table, the tabid value in the system
catalog tables changes for the affected table. The constrid of all unique and
referential constraints on the table also change.

For more information about the storage spaces in which you can store a table,
see “Using the IN Clause” on page 2-237.

SQL Statements 2-29


ALTER FRAGMENT

Warning: When you execute the ALTER FRAGMENT statement with this clause, it
results in data movement if the table contains any data. If data moves, the potential
exists for significant logging, for the transaction being aborted as a long transaction,
and for a relatively long exclusive lock being held on the affected tables. Use this
statement when it does not interfere with day-to-day operations.

IDS WITH ROWIDS Option


Nonfragmented tables contain a hidden column called rowid. By default,
fragmented tables do not contain this column unless it is explicitly created.
You can use the WITH ROWIDS option to add a new rowid column. The
database server assigns a unique rowid number to each row and automati-
cally creates an index that it can use to find the physical location of the row.
The rowid value of a row cannot be updated, but remains stable during the
existence of the row. Each row requires an additional 4 bytes to store the
rowid column after you specify the WITH ROWIDS option.

Important: The rowid column is a deprecated feature. You should use primary keys,
rather than the rowid column, as an access method.

Converting a Fragmented Table to a Nonfragmented Table


You might decide that you no longer want a table to be fragmented. You can
use the INIT clause to convert a fragmented table to a nonfragmented table.
The following example shows the original fragmentation definition as well as
how to use the ALTER FRAGMENT statement to convert the table:
CREATE TABLE checks (col1 INT, col2 INT)
FRAGMENT BY ROUND ROBIN IN dbsp1, dbsp2, dbsp3;

ALTER FRAGMENT ON TABLE checks INIT IN dbsp1;

You must use the IN dbspace clause to place the table in a dbspace explicitly.

When you use the INIT clause to change a fragmented table to a


nonfragmented table, all attached indexes become nonfragmented indexes.
In addition, constraints that do not use existing user indexes (detached
indexes) become nonfragmented indexes. All newly nonfragmented indexes
exist in the same dbspace as the new nonfragmented table.

Using the INIT clause to change a fragmented table to a nonfragmented table


has no effect on the fragmentation strategy of detached indexes, nor of
constraints that use detached indexes.

2-30 IBM Informix Guide to SQL: Syntax


ALTER FRAGMENT

FRAGMENT BY Clause for Tables


Use the FRAGMENT BY portion of the INIT clause to fragment an existing non-
fragmented table, or to convert one fragmentation strategy to another.

FRAGMENT BY Back to INIT Clause


Clause for Tables p. 2-29
,
FRAGMENT BY ROUND ROBIN IN dbspace

, XPS IN dbslice

EXPRESSION expr IN dbspace , REMAINDER IN dbspace

XPS ,, expr ,
HASH ( column ) IN ( dbspace , dbspace )
, dbslice

EXPRESSION expr IN dbslice , REMAINDER IN dbslice


,
expr dbspace
, ( dbspace ) ,
HYBRID ( column ) dbspace ( dbspace )

Element Purpose Restrictions Syntax


column Column to which fragmentation Must exist in the specified Identifier, p. 4-189
strategy applies table.
dbslice Dbslice that contains the table fragment Must be defined. Identifier, p. 4-189
dbspace Dbspace that contains the table Must specify at least two but Identifier, p. 4-189
fragment no more than 2,048 dbspaces.
expr Expression that defines a table fragment Must evaluate to a Boolean Expression, p. 4-67
by a range, hash, or arbitrary rule value (true or false).

In the HYBRID clause, column identifies the column or columns on which you
want to apply the hash portion of the hybrid table fragmentation strategy.
The expression can contain only columns from the current table and only data
values from a single row. No subqueries or aggregates are allowed. In
addition, the built-in CURRENT, DATE, and TIME functions are not valid.

SQL Statements 2-31


ALTER FRAGMENT

For more information on the available fragmentation strategies, see the


“FRAGMENT BY Clause” on page 2-238.

Changing an Existing Fragmentation Strategy on a Table


You can redefine a fragmentation strategy on a table if you decide that your
initial strategy does not fulfill your needs. When you alter a fragmentation
strategy, the database server discards the existing fragmentation strategy and
moves records to fragments as defined in the new fragmentation strategy.

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:

CREATE TABLE account (col1 INT, col2 INT)


FRAGMENT BY ROUND ROBIN IN dbsp1, dbsp2;
ALTER FRAGMENT ON TABLE account
INIT FRAGMENT BY EXPRESSION
col1 < 0 IN dbsp1,
col2 >= 0 IN dbsp2;

If an existing dbspace is full when you redefine a fragmentation strategy, you


must not use it in the new fragmentation strategy.

Defining a Fragmentation Strategy on a Nonfragmented Table


The INIT clause can define a fragmentation strategy on a nonfragmented
table, regardless of whether the table was created with a storage option:
CREATE TABLE balances (col1 INT, col2 INT) IN dbsp1;
ALTER FRAGMENT ON TABLE balances INIT
FRAGMENT BY EXPRESSION
col1 <= 500 IN dbsp1,
col1 > 500 AND col1 <=1000 IN dbsp2,
REMAINDER IN dbsp3;

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. ♦

2-32 IBM Informix Guide to SQL: Syntax


ALTER FRAGMENT

IDS FRAGMENT BY Clause for Indexes


The INIT FRAGMENT BY clause for indexes allows you to fragment an existing
index that is not fragmented without redefining the index. Use this clause to
define an expression-based distribution scheme for indexes.

FRAGMENT BY Back to INIT Clause


Clause for Indexes p. 2-29
,
FRAGMENT BY EXPRESSION expr IN dbspace

, REMAINDER IN dbspace

Element Purpose Restrictions Syntax


dbspace Dbspace that contains the fragmented You must specify at least two but Identifier, p. 4-189
information no more than 2,048 dbspaces.
expr Expression defining an index fragment Must return a Boolean value. Condition, p. 4-24;
by a range, hash, or arbitrary rule Expression, p. 4-67

You can convert an existing fragmentation strategy to another fragmentation


strategy. Any existing fragmentation strategy is discarded and records are
moved to fragments as defined in the new fragmentation strategy. You can
also convert a fragmented index to a nonfragmented index.

The expression can contain only columns from the current table and data
values from only a single row. No subqueries nor aggregates are allowed. The
built-in CURRENT, DATE, and TIME functions are not valid here.

Fragmenting Unique and System Indexes


You can fragment unique indexes only if the table uses an expression-based
distribution scheme. Any columns referenced in the fragment expression
must be indexed columns. If your ALTER FRAGMENT INIT statement fails to
meet either of these restrictions, the INIT fails, and work is rolled back.

You might have an attached unique index on a table fragmented by


Column A. If you use INIT to change the table fragmentation to Column B,
the INIT fails because the unique index is defined on Column A. To resolve
this issue, use the INIT clause on the index to detach it from the table fragmen-
tation strategy and fragment it separately.

SQL Statements 2-33


ALTER FRAGMENT

System indexes (such as those used in referential constraints and unique


constraints) use user indexes if the indexes exist. If no user indexes can be
used, system indexes remain nonfragmented and are moved to the dbspace
where the database was created. To fragment a system index, create the
fragmented index on the constraint columns and then use the ALTER TABLE
statement to add the constraint.

Detaching an Index from a Table-Fragmentation Strategy


You can detach an index from a table-fragmentation strategy with the INIT
clause, which causes an attached index to become a detached index. This
breaks any dependency of the index on the table fragmentation strategy.

IDS ADD Clause


Use the ADD clause to add another fragment to an existing fragmentation list.

ADD Back to ALTER FRAGMENT


Clause p. 2-16

ADD new_dbspace

REMAINDER IN BEFORE existing_dbspace

expression IN new_dbspace AFTER

Element Purpose Restrictions Syntax


existing_dbspace Name of a dbspace in an Must exist at the time when Identifier, p. 4-189
existing fragmentation list you execute the statement
expression Expression that defines the new Must return a Boolean value Condition, p. 4-24;
fragment that is to be added (true or false) Expression, p. 4-67
new_dbspace Name of dbspace to be added to Must exist at the time when Identifier, p. 4-189
the fragmentation scheme you execute the statement

The expression can contain column names only from the current table and data
values only from a single row. No subqueries or aggregates are allowed. In
addition, the built-in CURRENT, DATE, and TIME functions are not valid here.

2-34 IBM Informix Guide to SQL: Syntax


ALTER FRAGMENT

Adding a New Dbspace to a Round-Robin Distribution Scheme


You can add more dbspaces to a round-robin distribution scheme. The
following example shows the original round-robin definition:
CREATE TABLE book (col1 INT, col2 INT)
FRAGMENT BY ROUND ROBIN IN dbsp1, dbsp4;

To add another dbspace, use the ADD clause, as in this example:


ALTER FRAGMENT ON TABLE book ADD dbsp3;

Adding Fragment Expressions


Adding a fragment expression to the fragmentation list in an expression-
based distribution scheme can relocate records from existing fragments into
the new fragment. When you add a new fragment into the middle of the
fragmentation list, all the data existing in fragments after the new one must
be re-evaluated. The next example shows the original expression definition:
FRAGMENT BY EXPRESSION
c1 < 100 IN dbsp1,
c1 >= 100 AND c1 < 200 IN dbsp2,
REMAINDER IN dbsp3;

To add another fragment to hold rows between 200 and 300, use the
following ALTER FRAGMENT statement:
ALTER FRAGMENT ON TABLE news ADD
c1 >= 200 AND c1 < 300 IN dbsp4;

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.

Using the BEFORE and AFTER Options


The BEFORE and AFTER options allow you to place a new fragment either
before or after an existing dbspace. You cannot use the BEFORE and AFTER
options when the distribution scheme is round-robin.

When you attach a new fragment without an explicit BEFORE or AFTER


option, the database server places the added fragment at the end of the
fragmentation list, unless a remainder fragment exists. If a remainder
fragment exists, the new fragment is placed just before the remainder
fragment. You cannot attach a new fragment after the remainder fragment.

SQL Statements 2-35


ALTER FRAGMENT

Using the REMAINDER Option


You cannot add a remainder fragment when one already exists. When you
add a new fragment to the fragmentation list, and a remainder fragment
exists, the records in the remainder fragment are retrieved and re-evaluated.
Some of these records might move to the new fragment. The remainder
fragment always remains the last item in the fragment list.

IDS DROP Clause


Use the DROP clause to drop an existing fragment from a fragmentation list.

DROP Back to ALTER FRAGMENT


Clause p. 2-16

DROP dbspace

Element Purpose Restrictions Syntax


dbspace Name of dbspace that contains Must exist at the time when you Identifier, p. 4-189
the dropped fragment execute the statement.

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 values within that dbspace are affected.

When you drop a fragment, the database server attempts to move all the
records in the dropped fragment to another fragment. In this case, the desti-
nation fragment might not have enough space for the additional records.
When this happens, follow one of the procedures that are listed in “ALTER
FRAGMENT and Transaction Logging” on page 2-18 to increase your space,
and retry the procedure.

2-36 IBM Informix Guide to SQL: Syntax


ALTER FRAGMENT

The following examples show how to drop a fragment from a fragmentation


list. The first line shows how to drop an index fragment, and the second line
shows how to drop a table fragment.
ALTER FRAGMENT ON INDEX cust_indx DROP dbsp2;

ALTER FRAGMENT ON TABLE customer DROP dbsp1;

IDS MODIFY Clause


Use the MODIFY clause to change an existing fragment expression on an
existing dbspace. You can also use the MODIFY clause to move a fragment
expression from one dbspace to a different dbspace.

MODIFY Back to ALTER FRAGMENT


Clause p. 2-16

,
MODIFY mod_dbspace TO expression IN new_dbspace

1 REMAINDER

Element Purpose Restrictions Syntax


expression Modified range, hash, or Can specify columns in current table Condition, p. 4-24;
arbitrary expression only and data from only a single row. Expression, p. 4-67
mod_ dbspace Modified dbspace Must exist when you execute the Identifier, p. 4-189
statement.
new_dbspace Dbspace that contains the Must exist when you execute the Identifier, p. 4-189
modified information statement.

The expression must evaluate to a Boolean value (true or false).

No subqueries nor aggregates are allowed in the expression. In addition, the


built-in CURRENT, DATE, and TIME functions are not allowed.
When you use the MODIFY clause, the underlying dbspaces are not affected.
Only the fragment data values within the dbspaces are affected.

You cannot change a REMAINDER fragment into a nonremainder fragment if


records within the REMAINDER fragment do not satisfy the new expression.

SQL Statements 2-37


ALTER FRAGMENT

When you use the MODIFY clause to change an expression without changing
the dbspace storage for the expression, you must use the same name for the
mod_dbspace and the new_dbspace, as in the following example:
ALTER FRAGMENT ON TABLE cust_acct
MODIFY dbsp1 TO acct_num < 65 IN dbsp1

When you use the MODIFY clause to move an expression from one dbspace
to another, mod_dbspace is the name of the dbspace where the expression was
previously located, and new_dbspace is the new location for the expression:
ALTER FRAGMENT ON TABLE cust_acct
MODIFY dbsp1 TO acct_num < 35 IN dbsp2

Here the distribution scheme for the cust_acct table is modified so that all
row items in column acct_num that are less than 35 are now contained in the
dbspace dbsp2. These items were formerly contained in the dbspace dbsp1.

When you use the MODIFY clause to change the expression and to move it to
a new dbspace, you must change both the expression and the dbspace name.

If your indexes are attached indexes, and you modify the table, the index
fragmentation strategy is also modified.

Related Information
Related statements: CREATE TABLE, CREATE INDEX, and ALTER TABLE

For a discussion of fragmentation strategy, refer to the IBM Informix Database


Design and Implementation Guide.

For information on how to maximize performance when you make fragment


modifications, see your Performance Guide.

2-38 IBM Informix Guide to SQL: Syntax


ALTER FUNCTION

+ ALTER FUNCTION
IDS
Use the ALTER FUNCTION statement to change the routine modifiers or
pathname of a user-defined function.

Syntax
,
ALTER FUNCTION function ( ) WITH ( ADD Routine )
Modifier
, p. 4-257
MODIFY

parameter_type Ext DROP


Shared-
Specific Object
SPECIFIC FUNCTION Name MODIFY EXTERNAL NAME = Filename
p. 4-274 p. 4-270

Element Purpose Restrictions Syntax


function User-defined Must be registered in the database. If the name does Database Object
function to be not uniquely identify a function, you must enter one Name, p. 4-46
modified or more appropriate values for parameter_type.
parameter_type Data type of a Must be the same data types (and specified in the Identifier,
parameter same order) as in the definition of function. p. 4-189

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 used-defined routines (UDRs) that provide alternatives for the
optimizer, which can improve performance.

All modifications take effect on the next invocation of the function.

To use the ALTER FUNCTION statement, you must be the owner of the UDR or
have the DBA privilege.

SQL Statements 2-39


ALTER FUNCTION

Keywords That Introduce Modifications


Use the following keywords to introduce what you modify in the UDR.

Keyword Purpose

ADD Introduces a routine modifier that you want to


add to the user-defined function

MODIFY Introduces a routine modifier for which you want


to modify a value

DROP Introduces a routine modifier that you want to


remove from the user-defined function

MODIFY EXTERNAL NAME Introduces a new location for the executable file
(for external functions only)

WITH Introduces all modifications

If the routine modifier is a BOOLEAN value, MODIFY sets the value to be T


(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:
ALTER FUNCTION func1 WITH (MODIFY PARALLELIZABLE)
ALTER FUNCTION func1 WITH (ADD PARALLELIZABLE)

See also “Altering Routine Modifiers Example” on page 2-48.

Related Information
Related Statements: ALTER PROCEDURE, ALTER ROUTINE, CREATE
FUNCTION, and CREATE PROCEDURE

For a discussion on how to create and use SPL routines, see the IBM Informix
Guide to SQL: Tutorial.

For a discussion on how to create and use external routines, see IBM Informix
User-Defined Routines and Data Types Developer’s Guide.

For information about how to create C UDRs, see the IBM Informix DataBlade
API Programmer’s Guide.

2-40 IBM Informix Guide to SQL: Syntax


ALTER INDEX

+
ALTER INDEX
Use the ALTER INDEX statement to change the clustering attribute or the
locking mode of an existing index.

Syntax

ALTER INDEX index IDS TO CLUSTER

XPS NOT NORMAL

LOCK MODE COARSE

Element Purpose Restrictions Syntax


index Name of the index to be altered Must exist Database Object Name, p. 4-46

Usage
ALTER INDEX is valid only on indexes created explicitly with the CREATE
INDEX statement. It cannot modify indexes that were created implicitly to
support constraints, and it cannot modify an index on a temporary table.

IDS You cannot change the collating order of an existing index. If you use ALTER
INDEX to modify an index after SET COLLATION has specified a non-default
collating order, the SET COLLATION statement has no effect on the index. ♦

TO CLUSTER Option
The TO CLUSTER option causes the database server to reorder the rows of the
physical table according to the indexed order.

The next 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);
ALTER INDEX ix_cust TO CLUSTER;

SQL Statements 2-41


ALTER INDEX

For an ascending index, TO CLUSTER puts rows in lowest-to-highest order.


For a descending index, the rows are reordered in highest-to-lowest order.

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.

While a table is clustering, it is locked IN EXCLUSIVE MODE. When another


process is using the table to which the index name belongs, the database
server cannot execute the ALTER INDEX statement with the TO CLUSTER
option; it returns an error unless lock mode is set to WAIT. (When lock mode
is set to WAIT, the database server retries the ALTER INDEX statement.)

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. ♦

TO NOT CLUSTER Option


The TO NOT CLUSTER option drops the cluster attribute on the index name
without affecting the physical table. Because only one clustered index per
table can exist, you must use the TO NOT CLUSTER option to release the
cluster attribute from one index before you assign it to another. The following
statements illustrate how to remove clustering from one index and how a
second index physically reclusters the table:
CREATE UNIQUE INDEX ix_ord
ON orders (order_num);

CREATE CLUSTER INDEX ix_cust


ON orders (customer_num);
. . .
ALTER INDEX ix_cust TO NOT CLUSTER;

ALTER INDEX ix_ord TO CLUSTER;

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.

2-42 IBM Informix Guide to SQL: Syntax


ALTER INDEX

XPS LOCK MODE Options


Use the LOCK MODE clause to specify the locking granularity of the index.

When you use the COARSE 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.

The COARSE mode offers performance advantages when you know the index
is not going to change; for example, when read-only operations are
performed on the index.

Use the NORMAL 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 LOCK MODE COARSE option, it
acquires an exclusive lock on the table for the duration of the ALTER INDEX
statement. Any transactions currently using a lock of finer granularity 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.

SQL Statements 2-43


ALTER PROCEDURE

+ ALTER PROCEDURE
IDS
Use the ALTER PROCEDURE statement to change the routine modifiers or
pathname of a previously defined external procedure.

Syntax
,
ALTER PROCEDURE procedure ( ) WITH ( ADD Routine )
Modifier
, p. 4-257
MODIFY

parameter_type Ext DROP


Shared-
Specific Object
SPECIFIC PROCEDURE Name MODIFY EXTERNAL NAME = Filename
p. 4-274 p. 4-270

Element Purpose Restrictions Syntax


procedure User-defined Must be registered in the database. If the name does Database Object
procedure to not uniquely identify a function, you must enter one Name,
modify or more appropriate values for parameter_type. p. 4-46
parameter_type Data type of a Must be the same data types (and specified in the Identifier,
parameter same order) as in the definition of procedure. p. 4-189

Usage
The ALTER PROCEDURE statement allows you to modify an external
procedure to tune its performance by modifying characteristics that control
how it executes. You can also add or replace related UDRs that provide alter-
natives for the optimizer, which can improve performance.

To use the ALTER PROCEDURE statement, you must be the owner of the UDR
or have the DBA privilege.

If the name is not unique among routines registered in the database, you
must enter one or more appropriate values for parameter_type.

All modifications take effect on the next invocation of the procedure.

2-44 IBM Informix Guide to SQL: Syntax


ALTER PROCEDURE

Use the following keywords to introduce the items in the external procedure
that you want to modify.

Keyword Purpose

ADD Introduces a routine modifier that you want to


add to the external procedure

MODIFY Introduces a routine modifier for which you want


to modify a value

DROP Introduces a routine modifier that you want to


remove from the external procedure

MODIFY EXTERNAL NAME Introduces a new location for the executable file,
(for external routines only) specifying a different pathname from the original

WITH Introduces all modifications

If the routine modifier is a BOOLEAN value, MODIFY sets the value to be T


(equivalent to 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:
ALTER PROCEDURE proc1 WITH (MODIFY PARALLELIZABLE)
ALTER PROCEDURE proc1 WITH (ADD PARALLELIZABLE)

See also “Altering Routine Modifiers Example” on page 2-48.

Related Information
Related Statements: ALTER FUNCTION, ALTER ROUTINE, CREATE
FUNCTION, CREATE PROCEDURE, DROP PROCEDURE, and DROP ROUTINE

For a discussion on how to create and use SPL routines, see the IBM Informix
Guide to SQL: Tutorial.

For a discussion on how to create and use external routines, see IBM Informix
User-Defined Routines and Data Types Developer’s Guide.

For information about how to create C UDRs, see the IBM Informix DataBlade
API Programmer’s Guide.

SQL Statements 2-45


ALTER ROUTINE

+ ALTER ROUTINE
IDS
Use the ALTER ROUTINE statement to change the routine modifiers or
pathname of a previously defined user-defined routine (UDR).

Syntax
,
ALTER ROUTINE routine ( ) WITH ( ADD Routine )
Modifier
, p. 4-257
MODIFY

parameter_type Ext DROP


Shared-
Specific Object
SPECIFIC ROUTINE Name MODIFY EXTERNAL NAME = Filename
p. 4-274 p. 4-270

Element Purpose Restrictions Syntax


routine User-defined Must be registered in the database. If the name does Database
routine to not uniquely identify a routine, you must enter one or Object Name,
modify more appropriate values for parameter_type. p. 4-46
parameter_type Data type of a Must be the same data types (and specified in the Identifier,
parameter same order) as in the definition of routine. p. 4-189

Usage
The ALTER ROUTINE statement allows you to modify a previously defined
UDR to tune its performance by modifying characteristics 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.

All modifications take effect on the next invocation of the UDR.

2-46 IBM Informix Guide to SQL: Syntax


ALTER ROUTINE

To use the ALTER ROUTINE statement, you must be the owner of the UDR or
have the DBA privilege.

Restrictions
If the name does not uniquely identify a UDR, you must enter one or more
appropriate values for parameter_type.

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 applies 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.

Keywords That Introduce Modifications


Use the following keywords to introduce the items in the UDR that you want
to modify.

Keyword Purpose

ADD Introduces a routine modifier that you want to


add to the UDR

MODIFY Introduces a routine modifier for which you want


to modify a value

DROP Introduces a routine modifier that you want to


remove from the UDR

MODIFY EXTERNAL NAME Introduces a new location for the executable file
(for external UDRs only)

WITH Introduces all modifications

If the routine modifier is a BOOLEAN value, MODIFY sets the value to be T


(equivalent to using the keyword ADD to add the routine modifier).

SQL Statements 2-47


ALTER ROUTINE

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)
ALTER ROUTINE func1 WITH (ADD PARALLELIZABLE)

Altering Routine Modifiers Example


Suppose you have an external function func1 that is set to handle NULL
values and has a cost per invocation set to 40. The following ALTER ROUTINE
statement adjusts the settings of the function by dropping the ability to
handle NULL values, tunes the func1 by changing the cost per invocation to
20, and indicates that the function can execute in parallel:

ALTER ROUTINE func1(CHAR, INT, BOOLEAN)


WITH (
DROP HANDLESNULLS,
MODIFY PERCALL_COST = 20,
ADD PARALLELIZABLE
)

Because the name func1 is not unique to the database, the data type param-
eters 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 IBM Informix
Guide to SQL: Tutorial.

For a discussion on how to create and use external routines, see IBM Informix
User-Defined Routines and Data Types Developer’s Guide.

For information about how to create C UDRs, see the IBM Informix DataBlade
API Programmer’s Guide.

2-48 IBM Informix Guide to SQL: Syntax


ALTER SEQUENCE

+ ALTER SEQUENCE
IDS
Use the ALTER SEQUENCE statement to modify the definition of a sequence.

Syntax

ALTER SEQUENCE sequence

owner . 1 NOCYCLE

1 INCREMENT BY step CYCLE

1 RESTART WITH restart 1 CACHE size

1 MAXVALUE max NOCACHE

NOMAXVALUE 1 NOORDER

1 MINVALUE min ORDER

NOMINVALUE

Element Purpose Restrictions Syntax


max New upper limit on values Must be integer > CURRVAL and restart Literal Number, p. 4-216
min New lower limit on values Must be integer < CURRVAL and restart Literal Number, p. 4-216
owner Owner of sequence Cannot be changed by this statement Owner Name, p. 4-234
restart New first value in sequence Must be integer in the INT8 range Literal Number, p. 4-216
sequence Name of an existing Must exist. Cannot be a synonym. Identifier, p. 4-189
sequence
size New number of values to Integer > 2 but < cardinality of values in Literal Number, p. 4-216
preallocate in memory one cycle (= |(max - min)/step|)
step New interval between values Must be a nonzero integer Literal Number, p. 4-216

Usage
ALTER SEQUENCE redefines an existing sequence object. It only affects subse-
quently generated values (and any unused values in the sequence cache).

You cannot use the ALTER SEQUENCE statement to rename a sequence nor to
change the owner of a sequence.

SQL Statements 2-49


ALTER SEQUENCE

You must be the owner, or the DBA, or else have the ALTER privilege on the
sequence to modify its definition. Only elements of the sequence definition
that you specify explicitly in the ALTER SEQUENCE statement are modified.
An error occurs if you make contradictory changes, such as specifying both
MAXVALUE and NOMAXVALUE, or both the CYCLE and NOCYCLE options.

INCREMENT BY Option
Use the INCREMENT BY option to specify a new interval between successive
numbers in a sequence. The interval, or step value, can be a positive whole
number (for ascending sequences) or a negative whole number (for
descending sequences) in the INT8 range. The BY keyword is optional.

START WITH Option


Use the START WITH option to specify a new first number of the sequence.
The restart value must be an integer within the INT8 range that is greater than
or equal to the min value (for an ascending sequence) or that is less than or
equal to the max value (for a descending sequence), if min or max is specified
in the ALTER SEQUENCE statement. The WITH keyword is optional.

MAXVALUE or NOMAXVALUE Option


Use the MAXVALUE option to specify a new upper limit of values in the
sequence. The maximum value, or max, must be an integer in the INT8 range
that is greater than sequence.CURRVAL and restart (or greater than the origin in
the original CREATE SEQUENCE statement, if restart is not specified).

Use the NOMAXVALUE option to replace the current limit with a new default
maximum of 2e64 for ascending sequences or -1 for descending sequences.

MINVALUE or NOMINVALUE Option


Use the MINVALUE option to specify a new lower limit of values in the
sequence. The minimum value, or min, must be an integer the INT8 range that
is less than sequence.CURRVAL and restart (or less than the origin in the original
CREATE SEQUENCE statement, if restart is not specified).

Use the NOMINVALUE option to replace the current lower limit with a default
of 1 for ascending sequences or -(2e64) for descending sequences.

2-50 IBM Informix Guide to SQL: Syntax


ALTER SEQUENCE

CYCLE or NOCYCLE Option


Use the CYCLE option to continue generating sequence values after the
sequence reaches the maximum (ascending) or minimum (descending) limit,
to replace the NOCYCLE attribute. After an ascending sequence reaches max,
it generates the min value for the next value. After a descending sequence
reaches min, it generates the max value for the next sequence value.

Use the NOCYCLE option to prevent the sequence from generating more
values after reaching the declared limit. Once the sequence reaches the limit,
the next reference to sequence.NEXTVAL returns an error message.

CACHE or NOCACHE Option


Use the CACHE option to specify a new number of sequence values that are
preallocated in memory for rapid access. The cache size must be a whole
number in the INT range that is less than the number of values in a cycle (or
less than |(max - min)/step|). The minimum size is 2 preallocated values.

Use NOCACHE to have no values preallocated in memory. (See also the


description of SEQ_CACHE_SIZE in “CREATE SEQUENCE” on page 2-206.)

ORDER or NOORDER Option


These keywords have no effect on the behavior of the sequence. The sequence
always issues values to users in the order of their requests, as if the ORDER
keyword were always specified. The ORDER and NOORDER keywords are
accepted by the ALTER SEQUENCE statement, however, for compatibility
with implementations of sequence objects in other dialects of SQL.

Related Information
Related statements: CREATE SEQUENCE, DROP SEQUENCE, RENAME
SEQUENCE, CREATE SYNONYM, DROP SYNONYM, GRANT, REVOKE, INSERT,
UPDATE, and SELECT

For information about the syssequences system catalog table in which


sequence objects are registered, see the IBM Informix Guide to SQL: Reference.

For information about initializing, generating, or reading values from a


sequence, see “NEXTVAL and CURRVAL Operators” on page 4-102.

SQL Statements 2-51


ALTER TABLE

+
ALTER TABLE
Use the ALTER TABLE statement to modify the definition of a table.

Syntax

Basic Table Options


ALTER TABLE table p. 2-53
synonym Logging TYPE Options
p. 2-79
Typed-Table Options
IDS p. 2-80

Element Purpose Restrictions Syntax


synonym Synonym for the table to be Synonym and its table must exist; Database Object Name, p. 4-46
altered USETABLENAME is not set
table Name of table to be altered Must exist in current database Database Object Name, p. 4-46

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.
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 a violation table or a diagnostics table
associated with it. If the USETABLENAME environment variable is set, you
cannot specify a synonym for the table in the ALTER TABLE statement.
XPS If a table has range fragmentation, only the Logging TYPE options and LOCK
MODE clause are valid. All other ALTER TABLE options return an error. ♦

If you have a static or raw table, the only information that you can alter is the
logging type of the table. That is, the Logging TYPE options are the only part
of the ALTER TABLE statement that you can use.

2-52 IBM Informix Guide to SQL: Syntax


ALTER TABLE

To use ALTER TABLE, you must meet one of the following conditions:

■ You must have DBA privilege on the database containing the table.
■ 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


The Basic Table Options segment of ALTER TABLE has the following syntax.

Basic Table Options Back to ALTER TABLE


p. 2-52
,
ADD Clause
p. 2-55
ADD CONSTRAINT Clause
p. 2-72
MODIFY Clause
p. 2-65
DROP CONSTRAINT Clause
p. 2-75
DROP Clause
p. 2-63
MODIFY NEXT SIZE Clause
1 p. 2-76
LOCK MODE Clause
1 p. 2-76
ADD TYPE Clause
1 p. 2-78
IDS PUT Clause
p. 2-71

IDS ADD ROWIDS

DROP ADD CRCOLS

DROP

SQL Statements 2-53


ALTER TABLE

You can use the Basic Table Options segment to modify the schema of a table
by adding, modifying, or dropping columns and constraints, or changing the
extent size or locking granularity of a table. The database server performs
alterations in the order that you specify. If any of the actions fails, the entire
operation is cancelled.

IDS You can also associate a table with a named ROW type or specify a new
storage space to store large-object data. You can also add or drop rowid
columns and shadow columns for Enterprise Replication. You cannot,
however, specify these options in conjunction with any other alterations. ♦

IDS Using the ADD ROWIDS Keywords


Use the ADD ROWIDS keywords to add a new column called rowid to a
fragmented table. (Fragmented tables do not contain the hidden rowid
column by default.) 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. It is recommended that you use
primary keys as an access method rather than exploiting the rowid column.

For additional information about the rowid column, refer to your Adminis-
trator’s Reference.

IDS Using the DROP ROWIDS Keywords


The DROP ROWIDS keywords can drop a rowid column that you added (with
either the CREATE TABLE or ALTER FRAGMENT statement) to a fragmented
table. You cannot drop the rowid column of a nonfragmented table.

IDS Using the ADD CRCOLS Keywords


The ADD CRCOLS keywords create shadow columns, cdrserver and cdrtime,
that Enterprise Replication uses for conflict resolution. These columns enable
the database server to use the time-stamp or SPL conflict-resolution rule.
For more information, refer to “Using the WITH CRCOLS Option” on
page 2-235 and to the IBM Informix Dynamic Server Enterprise Replication Guide.

2-54 IBM Informix Guide to SQL: Syntax


ALTER TABLE

IDS Using the DROP CRCOLS Keywords


Use the DROP CRCOLS keywords to drop the cdrserver and cdrtime shadow
columns. You cannot drop these columns if Enterprise Replication is in use.

ADD Clause
Use the ADD clause to add a column to a table.

ADD Back to Basic Table Options


Clause , p. 2-53

ADD ( New Column )

New Column
New Column

new_column Data
Type
p. 4-49 Single-Column
DEFAULT Constraint BEFORE column
Clause Format
p. 2-56 p. 2-57

Element Purpose Restrictions Syntax


column Name of column before which Must already exist in the table. Identifier, p. 4-189
new_column is to be placed
new_column Name of column that you are You cannot add a serial column Identifier, p. 4-189
adding if the table contains data.

The following restrictions apply to the ADD clause:


■ 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. ♦

SQL Statements 2-55


ALTER TABLE

Using the BEFORE Option


The BEFORE option specifies the column before which to add the new
column(s). 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)

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.

DEFAULT Clause
Use the DEFAULT clause to specify at value that the database server should
insert in a column when an explicit value for the column is not specified.

DEFAULT Back to ADD Clause p. 2-55


Clause Back to MODIFY Clause p. 2-65

DEFAULT literal

NULL

+ USER
DATETIME Field
CURRENT Qualifier p. 4-65
TODAY

SITENAME

DBSERVERNAME

Element Purpose Restrictions Syntax


literal Literal default value Must be appropriate for the data type of the column. Expression,
for the column See “Using a Literal as a Default Value” on page 2-218. p. 4-67

You cannot specify a default value for serial columns. 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.

2-56 IBM Informix Guide to SQL: Syntax


ALTER TABLE

The following example adds a column to the items table. In items, the new
column item_weight has a literal default value:
ALTER TABLE items
ADD item_weight DECIMAL (6, 2) DEFAULT 2.00
BEFORE total_price

In this example, each existing row in the items table has a default value of
2.00 for the item_weight column.

For more information about the options of the DEFAULT clause, refer to
“DEFAULT Clause” on page 2-217.

Single-Column Constraint Format


Use the Single-Column Constraint Format to associate constraints with a
specified column.

Single-Column Back to ADD Clause


Constraint Format p. 2-55

UNIQUE
+ +
NOT NULL
+ DISTINCT
Constraint
PRIMARY KEY Definition
Constraint p. 2-58
Definition
p. 2-58 REFERENCES
Clause
p. 2-59

CHECK Clause
p. 2-62

You cannot specify a primary-key or unique constraint on a new column if


the table contains data. In the case of a unique constraint, however, the table
can contain a single row of data. When you want to add a column with a
primary-key constraint, the table must be empty when you issue the ALTER
TABLE statement.

SQL Statements 2-57


ALTER TABLE

The following rules apply when you place primary-key or unique constraints
on existing columns:

■ When you place a primary-key or unique constraint on a column or


set of columns, the database server creates an internal B-tree index on
the constrained column or set of columns unless a user-created index
was defined on the column or set of columns.
■ When you place a primary-key or unique constraint on a column or
set of columns, and a unique index already exists on that column or
set of columns, the constraint shares the index. If the existing index
allows duplicates, however, the database server returns an error. You
must then drop the existing index before you add the constraint.
■ When you place a primary-key or unique constraint on a column or
set of columns, and a referential constraint already exists on that
column or set of columns, the duplicate index is upgraded to unique
(if possible), and the index is shared.

You cannot place a unique constraint on a BYTE or TEXT column, nor can you
place referential constraints on columns of these types. A check constraint on
a BYTE or TEXT column can check only for IS NULL, IS NOT NULL, or LENGTH.

When you place a referential constraint on a column or set of columns, and


an index already exists on that column or set of columns, the index is
upgraded to unique (if possible) and the index is shared.

Using Not-Null Constraints with ADD


If a table contains data, when you add a column with a not-null constraint
you must also include a DEFAULT clause. If the table is empty, however, you
can add a column and apply only the not-null constraint. 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 In Dynamic Server, use the Constraint Definition portion of the ALTER TABLE
statement to declare the name of a constraint and to set the mode of the
constraint to disabled, enabled, or filtering. ♦

2-58 IBM Informix Guide to SQL: Syntax


ALTER TABLE

XPS In Extended Parallel Server, use the Constraint Definition portion of the
ALTER TABLE statement to declare the name of a constraint. ♦

Constraint Definition Back to Single-Column Constraint Format p. 2-57


Back to Multiple-Column Constraint Format p. 2-73

CONSTRAINT constraint IDS ENABLED

DISABLED
FILTERING WITHOUT ERROR

WITH ERROR

Element Purpose Restrictions Syntax


constraint Name declared here to the constraint Must be unique. Identifier, p. 4-189

For more information about constraint-mode options, see “Choosing a


Constraint-Mode Option” on page 2-230.

REFERENCES Clause
The REFERENCES clause has the following syntax.

REFERENCES Back to Single-Column Constraint Format p. 2-57


Clause Back to Multiple-Column Constraint Format p. 2-73

REFERENCES table
, +
( column ) ON DELETE CASCADE

Element Purpose Restrictions Syntax


column Referenced column in See “Restrictions on Referential Identifier, p. 4-189
the referenced table Constraints” on page 2-60.
table The referenced table The referenced and the referencing tables Database Object Name,
must reside in the same database. p. 4-46

SQL Statements 2-59


ALTER TABLE

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 in a different table in the same database.

If the referenced table is different from the referencing table, the default is the
primary-key column. If the referenced table is the same as the referencing
table, there is no default.

Restrictions on Referential Constraints


You must have the REFERENCES privilege to create a referential constraint.

The following restrictions apply to the column that is specified (the referenced
column) in the REFERENCES clause:

■ The referenced and referencing tables must be in the same database.


■ The referenced column (or set of columns) must have a unique or
primary-key constraint.
■ The referencing and referenced columns must be the same data type.
(The only exception is that a referencing column must be an integer
data type if the referenced column is a serial data type.)
■ You cannot place a referential constraint on a BYTE or TEXT column.
IDS ■ Constraints uses the collation in effect at their time of creation. ♦
■ A column-level REFERENCES clause can include only a single
column name.
■ The maximum number of columns in a table-level REFERENCES
clause is 16.
IDS ■ The total length of the columns in a table-level REFERENCES clause
cannot exceed 390 bytes. ♦
XPS ■ The total length of the columns in a table-level REFERENCES clause
cannot exceed 255 bytes. ♦

Default Values for the Referenced Column


If the referenced table is different from the referencing table, you do not need
to specify the referenced column; the default column is the primary-key
column (or columns) of the referenced table. If the referenced table is the
same as the referencing table, you must specify the referenced column.

2-60 IBM Informix Guide to SQL: Syntax


ALTER TABLE

The following example creates a new column in the cust_calls table,


ref_order. The ref_order column is a foreign key that references the
order_num column in the orders table.
ALTER TABLE cust_calls
ADD ref_order INTEGER
REFERENCES orders (order_num)
BEFORE user_id

When you place a referential constraint on a column or set of columns, and a


duplicate or unique index already exists on that column or set of columns, the
index is shared.

Using the ON DELETE CASCADE Option


Use the ON DELETE CASCADE option if you want rows deleted in the child
table when corresponding rows are deleted in the parent table. If you do not
specify cascading deletes, the default behavior of the database server
prevents you from deleting data in a table if other tables reference it.

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 advantage of the ON DELETE CASCADE option is that it
allows you to reduce the quantity of SQL statements needed 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

ALTER TABLE catalog ADD CONSTRAINT


(FOREIGN KEY (stock_num, manu_code) REFERENCES stock
ON DELETE CASCADE CONSTRAINT ab)

With cascading deletes specified on the child table, in addition to deleting a


stock item from the stock table, the delete cascades to the catalog table that is
associated with the stock_num foreign key. This cascading delete works only
if the stock_num that you are deleting was not ordered; otherwise, the
constraint from the items table would disallow the cascading delete. For
more information, see “Restrictions on DELETE When Tables Have
Cascading Deletes” on page 2-346.

SQL Statements 2-61


ALTER TABLE

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-346.

Locks Held During Creation of a Referential Constraint


When you create a referential constraint, the database server places an
exclusive lock on the referenced table. The lock is released after you finish
with the ALTER TABLE statement or at the end of a transaction (if you are
altering the table in a database that uses transaction logging).

CHECK Clause
A check constraint designates a condition that must be met before data can be
inserted into a column.

CHECK Back to Single-Column Constraint Format p. 2-57


Clause Back to Multiple-Column Constraint Format p. 2-73

Condition
CHECK ( p. 4-24 )

During an insert or update, if a row returns false for any check constraint
defined on a table, the database server returns an error. No error is returned,
however, if a row returns NULL for a check constraint. In some cases, you
might want to use both a check constraint and a NOT NULL constraint.

Check constraints are defined using search conditions. The search condition
cannot contain user-defined routines, subqueries, aggregates, host variables,
or rowids. In addition, the condition cannot contain the variant built-in
functions CURRENT, USER, SITENAME, DBSERVERNAME, or TODAY.

The check constraint cannot include columns in different tables. When you
are using the ADD or MODIFY clause, the check constraint cannot depend
upon values in other columns of the same table.

2-62 IBM Informix Guide to SQL: Syntax


ALTER TABLE

The next example adds a new unit_price column to the items table and
includes a check constraint to ensure 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 Back to Basic Table Options


Clause , p. 2-53

DROP ( column )
column

Element Purpose Restrictions Syntax


column Name of a column Must exist in the table. If any fragment expression references it, Identifier,
to be dropped or if it is the last column in the table, column cannot be dropped. p. 4-189

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.
You cannot drop a column that is part of a fragmentation strategy.

XPS In Extended Parallel Server, you cannot use the DROP clause if the table has
a dependent GK index. ♦

How Dropping a Column Affects Constraints


When you drop a column, all constraints on that column are also dropped:

■ All single-column constraints are dropped.


■ All referential constraints that reference the column are dropped.

SQL Statements 2-63


ALTER TABLE

■ All check constraints that reference the column are dropped.


■ If the column is part of a multiple-column primary-key or unique
constraint, the constraints placed on the multiple columns are also
dropped. This action, in turn, triggers the dropping of all referential
constraints that reference the multiple columns.

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.

How Dropping a Column Affects Triggers


In general, when you drop a column from a table, the triggers based on that
table remain unchanged. If the column that you drop appears in the action
clause of a trigger, however, dropping the column can invalidate the trigger.
The following statements illustrate the possible effects on triggers:
CREATE TABLE tab1 (i1 int, i2 int, i3 int);
CREATE TABLE tab2 (i4 int, i5 int);
CREATE TRIGGER col1trig UPDATE OF i2 ON tab1
BEFORE(INSERT INTO tab2 VALUES(1,1));
ALTER TABLE tab2 DROP i4;

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-269.
If a trigger is invalidated when you alter the underlying table, drop and then
re-create the trigger.

How Dropping a Column Affects Views


When you drop a column from a table, the views based on that table remain
unchanged. That is, the database server does not automatically drop the
corresponding columns from associated views.

2-64 IBM Informix Guide to SQL: Syntax


ALTER TABLE

The view is not automatically dropped because ALTER TABLE 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, but retain their original sequence of columns.

If a view is invalidated when you alter the underlying table, you must rebuild
the view.

XPS How Dropping a Column Affects a Generalized-Key Index


In Extended Parallel Server, if you drop a column from a table that has a
dependent GK index, all GK indexes on the table that refer to the dropped
column are dropped. Any GK indexes on other tables that refer to the
dropped column are also dropped.

MODIFY Clause
Use the MODIFY clause to change the data type, length, or default value of a
column, or to allow or disallow NULL values in a column.

MODIFY Back to Basic Table Options


Clause , p. 2-53

MODIFY ( Modify Column )


Clause

Modify Column Clause


Modify Column
Clause

column Data Type


p. 4-49
DEFAULT Clause Single-Column Constraint Format
p. 2-56 p. 2-57

Element Purpose Restrictions Syntax


column Column to modify Must exist in table. Cannot be a collection data type. Identifier, p. 4-189

XPS In Extended Parallel Server, you cannot use the MODIFY clause if the table
has a dependent GK index. ♦

SQL Statements 2-65


ALTER TABLE

IDS You cannot change the data type of a column to a collection 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, but you want to keep the default value (in this case,
1) and the NOT NULL column attribute, you can issue this statement:

ALTER TABLE items MODIFY (quantity SMALLINT DEFAULT 1 NOT NULL)

Tip: Both attributes are specified again in the MODIFY clause.

When you change the data type of a column, the database server does not
perform the modification in-place. The next example (for Dynamic Server
only) changes a VARCHAR(15) column to an LVARCHAR(3072) column:
ALTER TABLE stock MODIFY (description LVARCHAR(3072))

When you modify a column that has column constraints associated with it,
the following constraints are dropped:

■ All single-column constraints are dropped.


■ All referential constraints that reference the column are dropped.
■ If the modified column is part of a multiple-column primary-key or
unique constraint, all referential constraints that reference the
multiple columns also are dropped.

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 another example, suppose that a column is part of a multiple-column


primary-key constraint. This primary key is referenced 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.

2-66 IBM Informix Guide to SQL: Syntax


ALTER TABLE

Using the MODIFY Clause in Different Situations


The characteristics of the object you are attempting to modify can affect how
you handle your modifications.

Altering BYTE and TEXT Columns


You can use the MODIFY clause to change a BYTE column to a TEXT column,
and vice versa. You cannot use the MODIFY clause, however, to change a BYTE
or TEXT column to any other type of column, and vice versa.

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. ♦

Altering the Next Serial Number


You can use the MODIFY clause to reset the next value of a serial column. You
cannot set the next value below the current maximum value in the column
because that action can cause the database server to generate duplicate
numbers. You can set the next value, however, to any value higher than the
current maximum, which creates gaps in the sequence.

The following example sets the next serial number to 1000:


ALTER TABLE my_table MODIFY (serial_num serial (1000))

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-495.

IDS Altering the Next Serial Number of a Typed Table


You can set the initial serial number or modify the next serial number for a
row-type field with the MODIFY clause of the ALTER TABLE statement. (You
cannot set the start number for a serial field when you create a row type.)

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;

SQL Statements 2-67


ALTER TABLE

You then create corresponding typed tables:


CREATE TABLE OF TYPE parent;
CREATE TABLE OF TYPE child1 UNDER parent;
CREATE TABLE OF TYPE child2 UNDER child1;
CREATE TABLE OF TYPE child3 UNDER child2;

To change the next SERIAL and SERIAL8 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.

Altering the Structure of Tables


When you use the MODIFY clause, you can also alter the structure of other
tables. If the modified column is referenced by other tables, those referential
constraints are dropped. You must add those constraints to the referencing
tables again, using the ALTER TABLE statement.

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))

When a primary-key or unique constraint exists, however, conversion takes


place only if it does not violate the constraint. If a data type conversion would
result in duplicate values (by changing FLOAT to SMALLFLOAT, for example,
or by truncating CHAR values), the ALTER TABLE statement fails.

Modifying Tables for NULL Values


You can modify an existing column that formerly permitted NULLs to
disallow NULLs, provided that the column contains no NULL values. To do
this, specify MODIFY with the same column name and data type and the NOT
NULL keywords. Those keywords create a not-null constraint on the column.

2-68 IBM Informix Guide to SQL: Syntax


ALTER TABLE

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.

An alternative method of permitting NULLs in an existing column that did


not permit NULLs is to use the DROP CONSTRAINT clause to drop the not-null
constraint on the column.

IDS Adding a Constraint When Existing Rows Violate the Constraint


If you use the MODIFY clause to add a constraint in the enabled mode and
receive an error message because existing rows would violate the constraint,
take the following steps to add the constraint successfully:

1. Add the constraint in the disabled mode.


Issue the ALTER TABLE statement again, but this time specify the DIS-
ABLED keyword in the MODIFY clause.
2. Start a violations and diagnostics table for the target table with the
START VIOLATIONS TABLE statement.
3. Issue the SET CONSTRAINTS statement to switch the database object
mode of the constraint to the enabled mode.
When you issue this statement, existing rows in the target table that
violate the constraint are duplicated in the violations table; however,
you receive an integrity-violation error message, and the constraint
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
constraint.
6. After you fix all the nonconforming rows in the target table, issue the
SET statement again to enable the constraint that were disabled.
Now the constraint is enabled, and no integrity-violation error mes-
sage is returned because all rows in the target table now satisfy the
new constraint.

SQL Statements 2-69


ALTER TABLE

XPS How Modifying a Column Affects a Generalized-Key Index


In Extended Parallel Server, when you modify a column, all GK indexes that
reference the column are dropped if the column is used in the GK index in a
way that is incompatible with the new data type of the column.

For example, if a numeric column is changed to a character column, any GK


indexes involving that column are dropped if they involve arithmetic
expressions.

How Modifying a Column Affects Triggers


If you modify a column that appears in the triggering column list of an
UPDATE trigger, the trigger is unchanged.

When you modify a column in a table, the triggers based on that table remain
unchanged, but the column modification might invalidate the trigger.

The following statements illustrate the possible affects on triggers:


CREATE TABLE tab1 (i1 int, i2 int, i3 int);
CREATE TABLE tab2 (i4 int, i5 int);
CREATE TRIGGER col1trig UPDATE OF i2 ON tab1
BEFORE(INSERT INTO tab2 VALUES(1,1));
ALTER TABLE tab2 MODIFY i4 char;

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 re-create the trigger.

How Modifying a Column Affects Views


When you modify a column in a table, the views based on that table remain
unchanged. If a view is invalidated when you alter the underlying table, you
must rebuild the view.

2-70 IBM Informix Guide to SQL: Syntax


ALTER TABLE

IDS PUT Clause


Use the PUT clause to specify the storage space (an sbspace) for a column that
contains smart large objects. This clause can specify storage characteristics
for a new column or replace the storage characteristics of an existing column.

PUT Clause Back to Basic Table Options


p. 2-53
,
PUT column IN ( sbspace )

,
( )
EXTENT SIZE kilobytes

NO LOG

LOG

HIGH INTEG

NO KEEP ACCESS TIME

KEEP ACCESS TIME

Element Purpose Restrictions Syntax


column Column to store in the Must contain a user-defined, or Identifier, p. 4-189
specified sbspace complex, or BLOB, or CLOB data type.
kilobytes Number of kilobytes to Must be an integer value. Literal Number, p. 4-216
allocate for the extent size
sbspace Name of an area of storage The sbspace must exist. Identifier, p. 4-189
for smart large objects

When you modify the storage characteristics of a column, all attributes previ-
ously associated with the storage space for that column are dropped. When
you want certain attributes to remain, you must respecify those attributes.
For example, to retain logging, you must respecify the LOG keyword.

The format column.field is not valid here. That is, the smart large object that
you are storing cannot be one field of a ROW type.

SQL Statements 2-71


ALTER TABLE

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, but applies the new storage characteristics to only those smart
large objects that are inserted after the ALTER TABLE statement takes effect.

For more information on the available storage characteristics, refer to the


counterpart of this section in the CREATE TABLE statement, “PUT Clause” on
page 2-249. For a discussion of large-object characteristics, refer to “Large-
Object Data Types” on page 4-57.

ADD CONSTRAINT Clause


Use the ADD CONSTRAINT clause to specify a constraint on a new or existing
column or on a set of columns.

ADD CONSTRAINT Back to Basic Table Options


Clause p. 2-53

Multiple-Column Constraint Format


ADD CONSTRAINT p. 2-73

( Multiple-Column Constraint Format )


p. 2-73

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)

To declare a name for the constraint, change the preceding statement:


ALTER TABLE customer
ADD CONSTRAINT UNIQUE (lname, fname) CONSTRAINT u_cust

When you do not specify a name for a new constraint, 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 IBM Informix Guide to SQL: Reference.
IDS When you add a constraint, the collating order must be the same as when the
table was created. ♦

2-72 IBM Informix Guide to SQL: Syntax


ALTER TABLE

Multiple-Column Constraint Format


Use the Multiple-Column Constraint Format option to assign a constraint to
one column or a set of columns.

Multiple-Column Back to ADD CONSTRAINT Clause


Constraint Format p. 2-72
,

UNIQUE ( 16 column )
+
+ DISTINCT CHECK Clause
p. 2-62
PRIMARY KEY Constraint
Definition
, p. 2-58
REFERENCES
FOREIGN KEY ( ) Clause
16 column p. 2-59

Element Purpose Restrictions Syntax


column A column on which the constraint is placed No more than 16 columns. Identifier, p. 4-216

A multiple-column constraint has these restrictions:


■ It can include no more than 16 column names.
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 declare a name for the constraint and set its mode by means of
“Constraint Definition” on page 2-58.

SQL Statements 2-73


ALTER TABLE

Adding a Primary-Key or Unique Constraint


When you place a primary-key or unique constraint on a column or set of
columns, those columns must contain unique values. The database server
checks for existing constraints and indexes:

■ If a user-created unique index already exists on that column or set of


columns, the constraint shares the index.
■ If a user-created index that allows duplicates already exists on that
column or set of columns, the database server returns an error.
In this case, you must drop the existing index before adding the pri-
mary-key or unique constraint.
■ If a referential constraint already exists on that column or set of
columns, the duplicate index is upgraded to unique (if possible) and
the index is shared.
■ If no referential constraint or user-created index exists on that
column or set of columns, the database server creates an internal
B-tree index on the specified columns.

When you place a referential constraint on a column or set of columns, and


an index already exists on that column or set of columns, the index is shared.

If you own the table or have the Alter privilege on the table, you can create a
check, primary-key, or unique constraint on the table and specify yourself as
the owner of the constraint. To add a referential constraint, you must have the
References privilege on either the referenced columns or the referenced table.
When you have the DBA privilege, you can create constraints for other users.

IDS Recovery from Constraint Violations


If you use the ADD CONSTRAINT clause to add a constraint in the enabled
mode, you receive an error message because existing rows would violate the
constraint. For a procedure to add the constraint successfully, see “Adding a
Constraint When Existing Rows Violate the Constraint” on page 2-69.

2-74 IBM Informix Guide to SQL: Syntax


ALTER TABLE

DROP CONSTRAINT Clause


Use the DROP CONSTRAINT clause to drop a named constraint.

DROP CONSTRAINT Back to Basic Table Options


Clause , p. 2-53

DROP CONSTRAINT ( constraint )


constraint

Element Purpose Restrictions Syntax


constraint Constraint to be dropped Must exist. Database Object Name, p. 4-46

To drop an existing constraint, specify the DROP CONSTRAINT keywords


and the name of the constraint. Here is an example of dropping a constraint:
ALTER TABLE manufact DROP CONSTRAINT con_name

If no name is specified when the constraint is created, the database server


generates the name. You can query the sysconstraints system catalog table
for the name and owner of a constraint. For example, to find the name of the
constraint placed on the items table, you can issue the following statement:
SELECT constrname FROM sysconstraints
WHERE tabid = (SELECT tabid FROM systables
WHERE tabname = 'items')

When you drop a primary-key or unique constraint that has a corresponding


foreign key, the referential constraints are dropped. For example, if you drop
the primary-key constraint on the order_num column in the orders table and
order_num exists in the items table as a foreign key, that referential
relationship is also dropped.

SQL Statements 2-75


ALTER TABLE

MODIFY NEXT SIZE Clause


Use the MODIFY NEXT SIZE clause to change the size of new extents.

MODIFY NEXT SIZE Back to Basic Table Options p. 2-53


Clause Back to Typed-Table Options p. 2-80

MODIFY NEXT SIZE kilobytes

Element Purpose Restrictions Syntax


kilobytes Length (in kilobytes) assigned here for Minimum length is four times the disk- Expression,
the next extent for this table page size on your system. p. 4-67

For example, if you have a 2-kilobyte page system, the minimum length is
8 kilobytes. The maximum length is equal to the chunk size. The following
example specifies an extent size of 32 kilobytes:
ALTER TABLE customer MODIFY NEXT SIZE 32

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.

To change the size of existing extents, you must unload all the data, modify
the extent and next-extent sizes in the CREATE TABLE statement of the
database schema, re-create the database, and reload the data. For information
about how to optimize extents, see your Administrator’s Guide.

LOCK MODE Clause


Use the LOCK MODE keywords to change the locking granularity of a table.

LOCK MODE Back to Basic Table Options


Clause p. 2-53

LOCK MODE ( PAGE )


ROW

XPS TABLE

2-76 IBM Informix Guide to SQL: Syntax


ALTER TABLE

The following table describes the locking-granularity options available.

Granularity Purpose

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 especially appropriate.

ROW Obtains and releases one lock per row


Row-level locking provides the highest level of concurrency. 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.

TABLE Places a lock on the entire table


(XPS only) This type of lock reduces update concurrency in comparison to row
and page locks. A table lock reduces the lock-management overhead
for a table. Multiple read-only transactions can still access the table.

IDS Precedence and Default Behavior


The LOCK MODE setting in an ALTER TABLE statement takes precedence over
the settings of the IFX_DEF_TABLE_LOCKMODE environment variable and
the DEF_TABLE_LOCKMODE configuration parameter. For information about
the IFX_DEF_TABLE_LOCKMODE environment variable, refer to the
IBM Informix Guide to SQL: Reference. For information about the
DEF_TABLES_LOCKMODE configuration parameter, refer to the IBM Informix
Dynamic Server Administrator’s Reference.

SQL Statements 2-77


ALTER TABLE

IDS ADD TYPE Clause


Use the ADD TYPE clause to convert a table that is not based on a named ROW
data type into a typed table.

ADD TYPE Back to Basic Table Options


Clause p. 2-53

ADD TYPE row_type_name

Element Purpose Restrictions Syntax


row_type_name Name of the row type being The field types of this ROW type must match Data Type,
added to the table the column types of the table. p. 4-49

To add a named ROW type to a table, all of the following must be true:
■ The named ROW type already exists.
■ The named ROW type fields match the column types in the table.
■ You have the Usage privilege on the table.

When you use the ADD TYPE clause, you assign a named ROW data type to a
table whose columns match the fields of the ROW type. The table cannot be a
fragmented table that has rowids.

You cannot combine the ADD TYPE clause with any clause that changes the
structure of the table. No other ADD, DROP, or MODIFY clause is valid in the
same ALTER TABLE statement that has the ADD TYPE clause. The ADD TYPE
clause does not allow you to change column data types. (To change the data
type of a column, use the MODIFY clause.)

2-78 IBM Informix Guide to SQL: Syntax


ALTER TABLE

Logging TYPE Options


Use the Logging TYPE options to specify that the table have particular charac-
teristics that can improve various bulk operations on it.

Logging TYPE Options Back to ALTER TABLE


p. 2-52

TYPE ( STANDARD )
RAW
XPS

OPERATIONAL

STATIC

Other than the default option (STANDARD) that is used for online transaction
processing (OLTP) databases, these Logging TYPE options are used primarily
to improve performance in data warehousing databases.

A table can have any of the following logging characteristics.

Option Purpose

STANDARD Logging table that allows rollback, recovery, and restoration


from archives. This is the default. Use this type for recovery and
constraints functionality on OLTP databases.

RAW Nonlogging table that cannot have indexes or referential


constraints but can be updated. Use this type for quickly loading
data. In XPS, raw tables take advantage of light appends and
avoid the overhead of logging, checking constraints, and
building indexes.

OPERATIONAL Logging table that uses light appends and cannot be restored
(XPS only) from archive. Use this type on tables that are refreshed
frequently. Light appends allow the quick addition of many
rows.

STATIC Nonlogging table that can contain index and referential


(XPS only) constraints but cannot be updated. Use this type for read-only
operations because there is no logging or locking overhead.

SQL Statements 2-79


ALTER TABLE

Warning: Use raw tables for fast loading of data. It is recommended that you alter the
logging type to STANDARD and perform a level-0 backup before you use the table in
a transaction or modify the data within the table. If you must use a raw table within
a transaction, either set the isolation level to Repeatable Read or lock the table in
exclusive mode to prevent concurrency problems.

For more information on these logging types of tables, refer to your Adminis-
trator’s Guide.

The Logging TYPE options have the following restrictions:


■ You must perform a level-0 archive before the logging type of a table
can be altered to STANDARD from any other logging type.
■ If you want to change the logging 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
logging type to RAW or STATIC. Such tables do not support triggers.
■ The table cannot be a SCRATCH or TEMP table, and you cannot
change any of these types of tables to a SCRATCH or TEMP table.
XPS ■ The table cannot have a dependent GK index. ♦

IDS Typed-Table Options


The Typed-Table options support operations on tables of a ROW data type.

Typed-Table Back to ALTER TABLE


Options p. 2-52
,

ADD CONSTRAINT
Clause
p. 2-72
DROP CONSTRAINT Clause
p. 2-75
1 DROP TYPE
MODIFY NEXT
1 SIZE Clause
p. 2-76
LOCK MODE Clause
1 p. 2-76

2-80 IBM Informix Guide to SQL: Syntax


ALTER TABLE

In Dynamic Server, the database server performs the actions in the ALTER
TABLE statement in the order that you specify. If any action fails, the entire
operation is cancelled.

Altering Subtables and Supertables


The following considerations apply to tables that are part of inheritance
hierarchies:

■ For subtables, ADD CONSTRAINT and DROP CONSTRAINT are not


allowed on inherited constraints.
■ For supertables, ADD CONSTRAINT and DROP CONSTRAINT
propagate to all subtables.

DROP TYPE Option


Use the DROP TYPE option to drop the type from a table. DROP TYPE removes
the association between a table and a named-row type. You must drop the
type from a typed table before you can modify, drop, or change the data type
of a column in the table.

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 discussions of data-integrity constraints and the ON DELETE CASCADE


option, see the IBM Informix Guide to SQL: Tutorial.

For a discussion of database and table creation, see the IBM Informix Database
Design and Implementation Guide.

For information on how to maximize performance when you make table


modifications, see your Performance Guide.

SQL Statements 2-81


BEGIN WORK

+
BEGIN WORK
Use the BEGIN WORK statement to start a transaction (a series 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
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 that
affect 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-84 includes a LOCK TABLE statement.

Important: 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. ♦

2-82 IBM Informix Guide to SQL: Syntax


BEGIN WORK

The WORK keyword is optional in a BEGIN WORK statement. The following


two statements are equivalent:
BEGIN;

BEGIN WORK;

ANSI BEGIN WORK and ANSI-Compliant Databases


In an ANSI-compliant database, you do not need the BEGIN WORK statement
because transactions are implicit; every SQL statement occurs within a trans-
action. The database server generates a warning when you use a BEGIN
WORK statement immediately after any of the following statements:

■ DATABASE
■ COMMIT WORK
■ CREATE DATABASE
■ ROLLBACK WORK

The database server returns an error when you use a BEGIN WORK statement
after any other statement in an ANSI-compliant database.

IDS BEGIN WORK WITHOUT REPLICATION


E/C
When you use Enterprise Replication for data replication, you can use the
BEGIN WORK WITHOUT REPLICATION statement to start a transaction that
does not replicate to other database servers.

You cannot execute BEGIN WORK WITHOUT REPLICATION as a stand-alone


embedded statement in an ESQL/C application. Instead you must execute
this statement indirectly. You can use either of the following methods:
■ You can use a combination of the PREPARE and EXECUTE statements
to prepare and execute the BEGIN WORK WITHOUT REPLICATION
statement.
■ You can use the EXECUTE IMMEDIATE statement to prepare and
execute BEGIN WORK WITHOUT REPLICATION in a single step.

You cannot use the DECLARE cursor CURSOR WITH HOLD with the BEGIN
WORK WITHOUT REPLICATION statement.

SQL Statements 2-83


BEGIN WORK

For more information about data replication, see the IBM Informix Dynamic
Server Enterprise Replication Guide.

Example of BEGIN WORK


The following code fragment shows how you might place statements within
a transaction. The transaction is made up of the statements that occur
between the BEGIN WORK and COMMIT WORK statements. The transaction
locks the stock table (LOCK TABLE), updates rows in the stock table
(UPDATE), deletes rows from the stock table (DELETE), and inserts a row into
the manufact table (INSERT).
BEGIN WORK;
LOCK TABLE stock;
UPDATE stock SET unit_price = unit_price * 1.10
WHERE manu_code = 'KAR';
DELETE FROM stock WHERE description = 'baseball bat';
INSERT INTO manufact (manu_code, manu_name, lead_time)
VALUES ('LYM', 'LYMAN', 14);
COMMIT WORK;

The database server must perform this sequence of operations either


completely or not at all. When you include all of these operations within a
single transaction, the database server guarantees that all the statements are
completely and perfectly committed to disk, or else the database is restored
to the same state that it was in before the transaction began.

Related Information
Related statements: COMMIT WORK and ROLLBACK WORK

For discussions of transactions and locking, see the IBM Informix Guide to SQL:
Tutorial.

2-84 IBM Informix Guide to SQL: Syntax


CLOSE

E/C
CLOSE
Use the CLOSE statement when you no longer need to refer to the rows that
a select or function cursor retrieved, or to flush and close an insert cursor.

Use this statement with ESQL/C.

Syntax

CLOSE cursor_id

+ cursor_id_var

Element Purpose Restrictions Syntax


cursor_id Name of cursor to be closed Must have been declared. Identifier, p. 4-189
cursor_id_var Host variable that contains the Host variable must be a Must conform to language-
value of cursor_id character data type. specific rules for names.

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.

In a database that is not ANSI-compliant, you can close a cursor that has not
been opened or that has already been closed. No action is taken in these cases.

ANSI In an ANSI-compliant database, the database server returns an error if you


close a cursor that was not open. ♦

Closing a Select or Function Cursor


When a cursor identifier is associated with a SELECT or EXECUTE FUNCTION
(or EXECUTE PROCEDURE) statement, closing the cursor terminates the
SELECT or EXECUTE FUNCTION (or EXECUTE PROCEDURE) statement.

SQL Statements 2-85


CLOSE

The database server releases all resources that it might have allocated to the
active set of rows, for example, a temporary table that it used to hold an
ordered set. The database server also releases any locks that it might have
held on rows that were selected through the cursor. If a transaction contains
the CLOSE statement, the database server does not release the locks until you
execute COMMIT WORK or ROLLBACK WORK.

After you close a select or function cursor, you cannot execute a FETCH
statement that names that cursor until you have reopened it.

Closing an Insert Cursor


When a cursor identifier is associated with an INSERT statement, the CLOSE
statement writes any remaining buffered rows into the database. The number
of rows that were successfully inserted into the database is returned in the
third element of the sqlerrd array, sqlca.sqlerrd[2], in the sqlca structure. For
information on how to use SQLERRD to count the total number of rows that
were inserted, see “Error Checking” on page 2-546.

The SQLCODE field of the sqlca structure, sqlca.sqlcode, indicates the result
of the CLOSE statement for an insert cursor. If all buffered rows are success-
fully inserted, SQLCODE is set to zero. If an error is encountered, the
sqlca.sqlcode field in the SQLCODE is set to a negative error message number.

When SQLCODE is zero, the row buffer space is released, and the cursor is
closed; that is, you cannot execute a PUT or FLUSH statement that names the
cursor until you reopen it.

Tip: When you encounter an SQLCODE error, a corresponding SQLSTATE error


value also exists. For information about how to get the message text, check the GET
DIAGNOSTICS statement.

If the insert is not successful, the number of successfully inserted rows is


stored in sqlerrd. Any buffered rows that follow the last successfully inserted
row are discarded. Because the insert fails, the CLOSE statement fails also,
and the cursor is not closed. For example, a CLOSE statement can fail if insuf-
ficient disk space prevents some of the rows from being inserted. In this case,
a second CLOSE statement can be successful because no buffered rows exist.
An OPEN statement can also be successful because the OPEN statement
performs an implicit close.

2-86 IBM Informix Guide to SQL: Syntax


CLOSE

IDS Closing a Collection Cursor


You can declare both select and insert cursors on collection variables. Such
cursors are called collection cursors. Use the CLOSE statement to deallocate
resources that have been allocated for the collection cursor.

For more information on how to use a collection cursor, see “Fetching from a
Collection Cursor” on page 2-432 and “Inserting into a Collection Cursor” on
page 2-544.

Using End of Transaction to Close a Cursor


The COMMIT WORK and ROLLBACK WORK statements close all cursors
except those that are declared with a hold. It is better to close all cursors
explicitly, however. For select or function cursors, this action simply makes
the intent of the program clear. It also helps to avoid a logic error if the WITH
HOLD clause is later added to the declaration of a cursor.

For an insert cursor, it is important to use the CLOSE statement explicitly so


that you can test the error code. Following the COMMIT WORK statement,
SQLCODE reflects the result of the COMMIT statement, not the result of
closing cursors. If you use a COMMIT WORK statement without first using a
CLOSE statement, and if an error occurs while the last buffered rows are being
written to the database, the transaction is still committed.

For how to use insert cursors and the WITH HOLD clause, see “DECLARE”
on page 2-323.

ANSI In an ANSI-compliant database, a cursor cannot be closed implicitly. You


must issue a CLOSE statement. ♦

Related Information
Related statements: DECLARE, FETCH, FLUSH, FREE, OPEN, PUT, and SET
AUTOFREE

For an introductory discussion of cursors, see the IBM Informix Guide to SQL:
Tutorial.

For a more advanced discussion of cursors, see the IBM Informix ESQL/C
Programmer’s Manual.

SQL Statements 2-87


CLOSE DATABASE

+
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
(The DISCONNECT statement is valid here only if an explicit connec-
tion existed before CLOSE DATABASE was executed.)

Issue the CLOSE DATABASE statement before you drop the current database.

If your database supports transaction logging, and if you have started a


transaction, you must issue a COMMIT WORK statement before you can 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

2-88 IBM Informix Guide to SQL: Syntax


CLOSE DATABASE

E/C In ESQL/C, the CLOSE DATABASE statement cannot appear in a multi-


statement PREPARE operation.

If you use the CLOSE DATABASE statement within a UDR called by a


WHENEVER statement, specify WHENEVER SQLERROR CONTINUE and
WHENEVER SQLWARNING CONTINUE before the ROLLBACK WORK
statement. This action prevents the program from looping if the ROLLBACK
WORK statement encounters an error or a warning.

When you issue the CLOSE DATABASE statement, any declared cursors are no
longer valid. You must re-declare any cursors that you want to use. ♦

ANSI In an ANSI-compliant database, if no error is encountered while you exit from


DB-Access in non-interactive mode without issuing the CLOSE DATABASE,
COMMIT WORK, or DISCONNECT statement, the database server automati-
cally commits any open transaction. ♦

Related Information
Related statements: CONNECT, CREATE DATABASE, DATABASE,
DISCONNECT, and DROP DATABASE

SQL Statements 2-89


COMMIT WORK

COMMIT WORK
Use the COMMIT WORK statement to commit all modifications made to the
database from the beginning of a transaction.

Syntax

COMMIT

WORK

Usage
The COMMIT WORK 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
that the transaction makes are completed correctly and saved to disk.

Use COMMIT WORK only at the end of a multistatement operation in a


database with transaction logging, when you are sure that you want to keep
all changes made to the database from the beginning of a transaction.

The COMMIT WORK statement releases all row and table locks.

The WORK keyword is optional in a COMMIT WORK statement. The following


two statements are equivalent:
COMMIT;
COMMIT WORK;

The following example shows a transaction bounded by BEGIN WORK and


COMMIT WORK statements.

BEGIN WORK;
DELETE FROM call_type WHERE call_code = 'O';
INSERT INTO call_type VALUES ('S', 'order status');
COMMIT WORK;

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.

2-90 IBM Informix Guide to SQL: Syntax


COMMIT WORK

E/C In ESQL/C, the COMMIT WORK statement closes all open cursors except those
that were declared using the WITH HOLD option. ♦

Issuing COMMIT WORK in a Database That Is Not ANSI Compliant


In a database that is not ANSI compliant, but that supports transaction
logging, if you initiate a transaction with a BEGIN WORK statement, you must
issue a COMMIT WORK statement at the end of the transaction. If you fail to
issue a COMMIT WORK statement in this case, the database server rolls back
any modifications that the transaction made to the database.

If you do not issue a BEGIN WORK statement, however, each statement


executes within its own transaction. These single-statement transactions do
not require either a BEGIN WORK statement or a COMMIT WORK statement.

ANSI Issuing COMMIT WORK in an ANSI-Compliant Database


In an ANSI-compliant database, you do not need BEGIN WORK to mark the
beginning of a transaction. You only need to mark the end of each trans-
action, because a transaction is always in effect. A new transaction starts
automatically after each COMMIT WORK or ROLLBACK WORK statement.

You must, however, issue an explicit COMMIT WORK statement to mark the
end of each transaction. If you fail to do so, the database server rolls back any
modifications that the transaction made to the database.

DB-Access In an ANSI-compliant database, however, if no error is encountered while


you exit from DB-Access in non-interactive mode without issuing the CLOSE
DATABASE, COMMIT WORK, or DISCONNECT statement, the database server
automatically commits any open transaction. ♦

Related Information
Related statements: BEGIN WORK, ROLLBACK WORK, and DECLARE

For a discussion of concepts related to transactions, see the IBM Informix Guide
to SQL: Tutorial.

SQL Statements 2-91


CONNECT

+
CONNECT
Use the CONNECT statement to connect to a database environment.

Syntax

Database
CONNECT TO Environment
p. 2-97
E/C E/C
' connection ' USER
Clause
AS connection_var p. 2-99 E/C
DEFAULT

WITH CONCURRENT TRANSACTION

Element Purpose Restrictions Syntax


connection Case-sensitive name that you Must be unique among Quoted String, p. 4-243
declare here for a connection connection names.
connection_var Host variable that stores the name Must be a fixed-length Language specific
of connection character data type.

Usage
The CONNECT statement connects an application to a database environment,
which 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 appli-
cation. SQL statements fail if the application has no current connection to a
database server. If you specify a database name, the database server opens
that database. You cannot include CONNECT within a PREPARE statement.

An application can connect to several database environments at the same


time, and it can establish multiple connections to the same database
environment, provided each connection has a unique connection name.

2-92 IBM Informix Guide to SQL: Syntax


CONNECT

UNIX On UNIX, the only restriction on establishing multiple connections to the


same database environment is that an application can establish only one
connection to each local server that uses the shared-memory connection
mechanism. To find out whether a local server uses the shared-memory
connection mechanism or the local-loopback connection mechanism,
examine the $INFORMIXDIR/etc/sqlhosts file. For more information on the
sqlhosts file, refer to your Administrator’s Guide. ♦

Windows On Windows, 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 connection becomes
dormant. You can make a dormant connection current with the SET
CONNECTION statement. See also “SET CONNECTION” on page 2-646.

Privileges for Executing the CONNECT Statement


The current user, or PUBLIC, must have the Connect database privilege on the
database specified in the CONNECT statement. The user who executes the
CONNECT statement cannot have the same user name as an existing role in
the database.

For information on how to use 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-99.

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.

SQL Statements 2-93


CONNECT

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, see “Making a
Dormant Connection the Current Connection” on page 2-646.)

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.

The Implicit Connection with DATABASE Statements


If you do not execute a CONNECT statement in your application, the first SQL
statement must be one of the following database statements (or a single
statement PREPARE for one of the following statements):
■ DATABASE
■ CREATE DATABASE
■ DROP DATABASE

If one of these database statements is the first SQL statement in an application,


the statement establishes a connection to a database server, which is known
as an implicit connection. If the database statement specifies only a database
name, the database server name is obtained from the DBPATH environment
variable. This situation is described in “Specifying the Database
Environment” on page 2-98.

2-94 IBM Informix Guide to SQL: Syntax


CONNECT

An application that makes an implicit connection can establish other


connections explicitly (using the CONNECT statement) but cannot establish
another implicit connection unless the original implicit connection is discon-
nected. An application can terminate an implicit connection using the
DISCONNECT statement.

After any implicit connection is made, that connection is considered to be the


default connection, regardless of whether the database server is the default
that the INFORMIXSERVER environment variable specifies. This feature
allows the application to refer to the implicit connection if additional explicit
connections are made, because the implicit connection has no identifier.

For example, if you establish an implicit connection followed by an explicit


connection, you can make the implicit connection current by issuing the SET
CONNECTION DEFAULT statement. This means, however, that once you
establish an implicit connection, you cannot use the CONNECT DEFAULT
statement, because the implicit connection is now the default connection.

The database statements can always be used to open a database or create a


new database on the current database server.

WITH CONCURRENT TRANSACTION Option


The WITH CONCURRENT TRANSACTION clause lets you switch to a different
connection while a transaction is active in the current connection. If the
current connection was not established using the WITH CONCURRENT
TRANSACTION clause, you cannot switch to a different connection if a trans-
action is active; the CONNECT or SET CONNECTION statement fails, returning
an error, and the transaction in the current connection continues to be active.

In this case, the application must commit or roll back the active transaction in
the current connection before it switches to a different connection.

The WITH CONCURRENT TRANSACTION clause supports the concept of


multiple concurrent transactions, where each connection can have its own
transaction and the COMMIT WORK and ROLLBACK WORK statements affect
only the current connection.The WITH CONCURRENT TRANSACTION clause
does not support global transactions in which a single transaction spans
databases over multiple connections. The COMMIT WORK and ROLLBACK
WORK statements do not act on databases across multiple connections.

SQL Statements 2-95


CONNECT

The following example illustrates how to use the WITH CONCURRRENT


TRANSACTION clause:

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
*/

EXEC SQL set connection 'B'; -- switch to connection 'B'

/*
Execute SQL statements starting a transaction in 'B'.
Now there are two active transactions, one each in 'B'
and 'C'.
*/

EXEC SQL set connection 'A'; -- switch to connection 'A'

/*
Execute SQL statements starting a transaction in 'A'.
Now there are three active transactions, one each in 'A',
'B' and 'C'.
*/

EXEC SQL set connection 'C'; -- ERROR, transaction active in 'A'

/*
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.
*/

EXEC SQL commit work;-- commit tx in current connection ('A')

/*
Now, there are two active transactions, in 'B' and in 'C',
which must be committed/rolled back separately
*/

EXEC SQL set connection 'B'; -- switch to connection 'B'


EXEC SQL commit work; -- commit tx in current connection ('B')

EXEC SQL set connection 'C'; -- go back to connection 'C'


EXEC SQL commit work; -- commit tx in current connection ('C')

EXEC SQL disconnect all;


}

Warning: When an application uses the WITH CONCURRENT TRANSACTION


clause to establish multiple connections to the same database environment, a deadlock
condition can occur.

2-96 IBM Informix Guide to SQL: Syntax


CONNECT

Database Environment

Database Back to CONNECT p. 2-92


Environment Back to SET CONNECTION p. 2-646

'dbname'
'@dbservername'
'dbname@dbservername'
E/C db_var

Element Purpose Restrictions Syntax


db_var Host variable that contains a Must be a fixed-length character data type, Language
valid database environment (in whose contents are in a format from the specific
one of the formats in the syntax syntax diagram.
diagram)
dbname Database to which to connect Must already exist. Identifier,
p. 4-189
dbservername Name of the database server to Must already exist; blank space is not valid Identifier,
which a connection is made between @ symbol and dbservername. See also p. 4-189
“Restrictions on dbservername.”

If the DELIMIDENT environment variable is set, any quotation ( ' ) marks in


the database environment must be single. If DELIMIDENT is not set, then
either single ( ' ) or double ( " ) quotation marks are valid here.

Restrictions on dbservername
If you specify dbservername, it must satisfy the following restrictions.
■ If the database server that you specify is not online, you receive an
error.
UNIX ■ On UNIX, the database server that you specify in dbservername must
match the name of a database server in the sqlhosts file. ♦
Windows ■ On Windows, dbservername must match the name of a database
server in the sqlhosts subkey in the registry. It is recommended that
you use the setnet32 utility to update the registry. ♦

SQL Statements 2-97


CONNECT

Specifying the Database Environment


You can specify a database server and a database, or a database server only,
or a database only. How a database is located and opened depends on
whether you specify a database server name in the database environment
expression.

Only Database Server Specified


The @dbservername option establishes a connection to the database server
only; it does not open a database. When you use this option, you must subse-
quently use the DATABASE or CREATE DATABASE statement (or a PREPARE
statement for one of these statements and an EXECUTE statement) to open a
database.

Database Server and Database Specified


If you specify both a database server and a database, your application
connects to the database server, which locates and opens the database.

Only Database Specified


The dbname option establishes a connection to the default database server or
to another database server in the DBPATH environment variable. It also
locates and opens the named database. (The same is true of the db_var option
if this specifies only a database name.)

If you specify only dbname, its database server is read from the DBPATH
environment variable. The database server in the INFORMIXSERVER
environment variable is always added before the DBPATH value.

UNIX On UNIX, set the INFORMIXSERVER and DBPATH environment variables as


the following example (for the C shell) shows:
setenv INFORMIXSERVER srvA
setenv DBPATH //srvB://srvC

2-98 IBM Informix Guide to SQL: Syntax


CONNECT

Windows On Windows, choose Start➞Programs➞Informix➞setnet32 from the Task


Bar and set the INFORMIXSERVER and DBPATH environment variables:
set INFORMIXSERVER = srvA
set DBPATH = //srvA://srvB://srvC

The next example shows the resulting DBPATH that your application uses:
//srvA://srvB://srvC

The application first establishes a connection to the database server that


INFORMIXSERVER specifies. The database server uses parameters in the
configuration file to locate the database. If the database does not reside on the
default database server, or if the default database server is not online, the
application connects to the next database server in DBPATH. In the previous
example, that database server would be srvB.

USER Clause
The USER clause specifies information that is used to determine whether the
application can access the target computer on a remote host.

USER Back to CONNECT


Clause p. 2-92

USER 'user _id ' USING validation_var

user_id_var

Element Purpose Restrictions Syntax


user_id Valid login name See “Restrictions on the User Identifier Quoted String,
Parameter” on page 2-100. p. 4-243
user_id_var Host variable that contains Must be a fixed-length character data Language
user_id type; same restrictions as user_id. specific
validation_var Host variable that contains a Must be a fixed-length character data Language
valid password for login name type. See “Restrictions on the specific
in user_id or user_id_var Validation Variable Parameter” on
page 2-100.

SQL Statements 2-99


CONNECT

The USER clause is required 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.

Restrictions on the Validation Variable Parameter


UNIX On UNIX, the password stored in validation_var must be a valid password and
must exist in the /etc/passwd file. If the application connects to a remote
database server, the password must exist in this file on both the local and
remote database servers. ♦

Windows On Windows, the password stored in validation_var must be a valid password


and must be the one entered in User Manager. If the application connects to
a remote database server, the password must exist in the domain of both the
client and the server. ♦

Restrictions on the User Identifier Parameter


UNIX On UNIX, the login name you specify in user_id must be a valid login name
and must exist in the /etc/passwd file. If the application connects to a remote
server, the login name must exist in this file on both the local and remote
database servers. ♦

Windows On Windows, the login name that 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 connection is rejected if the following conditions occur:

■ 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 specification. If the validation_var is not
present, however, the database server rejects the connection at runtime. ♦

2-100 IBM Informix Guide to SQL: Syntax


CONNECT

Use of the Default User ID


If you do not supply the USER clause, the default user ID is used to attempt
the connection. The default user ID is the login name of the user running the
application. In this case, you obtain network permissions with the standard
authorization procedures. For example, on UNIX, the default user ID must
match a user ID in the /etc/hosts.equiv file. On Windows, you must be a
member of the domain, or if the database server is installed locally, you must
be a valid user on the computer where it is installed.

Related Information
Related Statements: DISCONNECT, SET CONNECTION, DATABASE, and
CREATE DATABASE

For more information about sqlhosts, refer to your Administrator’s Guide.

SQL Statements 2-101


CREATE ACCESS_METHOD

+ CREATE ACCESS_METHOD
IDS
Use the CREATE ACCESS_METHOD statement to register a new access method
in the sysams system catalog table.

Syntax
,

CREATE SECONDARY ACCESS_METHOD access_method ( Purpose Options )


p. 4-237
PRIMARY

Element Purpose Restrictions Syntax


access Name declared here for the Must be unique among access-method Database Object
_method new access method names in the sysams system catalog table. Name, p. 4-46

Usage
The CREATE ACCESS_METHOD statement adds a user-defined access method
to a database.

When you create an access method, you specify purpose functions or


methods, purpose flags, or purpose values as attributes of the access method,
and you associate purpose keywords in the sysams system catalog table with
user-defined functions or methods.

The am_getnext keyword is required in the Purpose Options list. You must
use this to specify a UDR (or the name of a method) to scan for the next item
that satisfies a query. For information on how to set purpose options, refer to
“Purpose Options” on page 4-237.

The PRIMARY keyword specifies a user-defined primary-access method for a


virtual table. The SECONDARY keyword specifies creating a user-defined
secondary-access method for a virtual index. The SECONDARY keyword (and
creating virtual indexes) is not supported in the Java Virtual-Table Interface.

You must have the DBA or Resource privilege to create an access method.

2-102 IBM Informix Guide to SQL: Syntax


CREATE ACCESS_METHOD

The following statement creates a secondary-access method named T-tree


that resides in an sbspace:
CREATE SECONDARY ACCESS_METHOD T_tree
(
am_getnext = ttree_getnext,
am_unique,
am_cluster,
am_sptype = 'S'
);

In the preceding example, the am_getnext keyword is associated with the


user-defined function ttree_getnext( ). The T_tree access method supports
unique keys and clustering.

The following statement creates a primary-access method named


am_tabprops that resides in an extspace.
CREATE PRIMARY ACCESS_METHOD am_tabprops
(
am_open = FS_open,
am_close = FS_close,
am_beginscan = FS_beginScan,
am_create = FS_create,
am_scancost = FS_scanCost,
am_endscan = FS_endScan,
am_getnext = FS_getNext,
am_getbyid = FS_getById,
am_drop = FS_drop,
am_rowids,
am_sptype = ’x’
);

Related Information
Related statements: ALTER ACCESS_METHOD and DROP ACCESS_METHOD

For detailed information about how to set purpose-option specifications, see


“Purpose Options” on page 4-237.

For more information on primary-access methods, see the IBM Informix


Virtual-Table Interface Programmer’s Guide.

For more information on secondary-access methods, see the IBM Informix


Virtual-Index Interface Programmer’s Guide (C only).

For a discussion of privileges, see the GRANT or REVOKE statements or the


IBM Informix Database Design and Implementation Guide.

SQL Statements 2-103


CREATE AGGREGATE

+ CREATE AGGREGATE
IDS
Use the CREATE AGGREGATE statement to create a new aggregate function
and register it in the sysaggregates system catalog table. User-defined aggre-
gates extend the functionality of the database server by performing
aggregate computations that the user implements.

Syntax
,

CREATE AGGREGATE aggregate WITH ( Modifiers )


Owner Name
p. 4-234

Modifiers

INIT = init_func

ITER = iter_func

COMBINE = comb_func FINAL = final_func

HANDLESNULLS

Element Purpose Restrictions Syntax


aggregate Name of the new aggregate Must be unique among names of Identifier, p. 4-189
built-in aggregates and UDRs
comb_func Function that merges one partial Must specify the combined function Database Object
result into the other and returns both for parallel queries and for Name, p. 4-46
the updated partial result sequential queries
final_func Function that converts a partial If this is omitted, then the returned Database Object
result into the result type value is the final result of iter_func Name, p. 4-46
init_func Function that initializes the data Must be able to handle NULL Database Object
structures required for the arguments Name, p. 4-46
aggregate computation
iter_func Function that merges a single Must specify an iterator function. If Database Object
value with a partial result and init_func is omitted, iter_func must be Name, p. 4-46
returns updated partial result able to handle NULL arguments

2-104 IBM Informix Guide to SQL: Syntax


CREATE AGGREGATE

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.

If you omit the HANDLESNULLS modifier, rows with NULL aggregate


argument values do not contribute to the aggregate computation. If you
include the HANDLESNULLS modifier, you must define all the support
functions to handle NULL values as well.

Extending the Functionality of Aggregates


Dynamic Server provides two ways to extend the functionality of aggregates.
Use the CREATE AGGREGATE statement only for the second of the two cases.

■ Extensions of built-in aggregates


A built-in aggregate is an aggregate that the database server pro-
vides, such as COUNT, SUM, or AVG. These support only built-in
data types. To extend a built-in aggregate so that it supports a user-
defined data type (UDT), you must create user-defined routines that
overload the binary operators for that aggregate. For further infor-
mation on extending built-in aggregates, see the IBM Informix User-
Defined Routines and Data Types Developer’s Guide.
■ Creation of user-defined aggregates
A user-defined aggregate is an aggregate that you define to perform
an aggregate computation that the database server does not provide.
You can use user-defined aggregates with built-in data types,
extended data types, or both. To create a user-defined aggregate, use
the CREATE AGGREGATE statement. In this statement, you name the
new aggregate and specify the support functions that compute the
aggregate result. These support functions perform initialization,
sequential aggregation, combination of results, and type conversion.

SQL Statements 2-105


CREATE AGGREGATE

Example of Creating a User-Defined Aggregate


The following example defines a user-defined aggregate named average:
CREATE AGGREGATE average
WITH (
INIT = average_init,
ITER = average_iter,
COMBINE = average_combine,
FINAL = average_final
)

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.

Keyword Support Function Effect

INIT average_init Allocates and initializes an extended data type


storing the current sum and the current row count

ITER average_iter For each row, adds the value of the expression to
the current sum and increments the current row
count by one

COMBINE average_combine Adds the current sum and the current row count
of one partial result to the other and returns the
updated result

FINAL average_final Returns the ratio of the current sum to the current
row count and converts this ratio to the result type

Parallel Execution
The database server can break up an aggregate computation into several
pieces and compute them in parallel. The database server uses 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.

2-106 IBM Informix Guide to SQL: Syntax


CREATE AGGREGATE

Related Information
Related statements: CREATE FUNCTION and DROP AGGREGATE

For information about how to invoke a user-defined aggregate, see “User-


Defined Aggregates” on page 4-173 in the Expression segment.

For a description of the sysaggregates system catalog table that stores data
about user-defined aggregates, see the IBM Informix Guide to SQL: Reference.

For a discussion of user-defined aggregates, see IBM Informix User-Defined


Routines and Data Types Developer’s Guide.

SQL Statements 2-107


CREATE CAST

+ CREATE CAST
IDS
Use the CREATE CAST statement to register a cast that converts data from one
data type to another.

Syntax

CREATE EXPLICIT CAST ( source_type AS target_type )


IMPLICIT WITH function

Element Purpose Restrictions Syntax


function User-defined function See “WITH Clause” on page 2-111. Database
that you register to Object Name,
implement the cast p. 4-46
source_type Data type to be Must exist in the database at the time when the cast Data Type,
converted is registered. See also “Source and Target Data p. 4-49
Types” on page 2-109.
target_type Data type that results The same restrictions that apply for the source_type Data Type,
from the conversion (as listed above) also apply for the target_type. p. 4-49

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 compare two values in the WHERE clause of a SELECT, UPDATE, or


DELETE statement
■ To pass values as arguments to user-defined routines
■ To return values from user-defined routines

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. To create a cast to or from an OPAQUE, DISTINCT, or named ROW
data type, however, requires the Usage privilege on that data type.

2-108 IBM Informix Guide to SQL: Syntax


CREATE CAST

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 IBM Informix Guide to SQL: Reference.

Source and Target Data Types


The CREATE CAST statement defines a cast that converts a source data type to
a target data type. Both the source data type and target data type must exist in the
database when you execute the CREATE CAST statement to register the cast.
The source data type and the target data type have the following restrictions:
■ 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 and Implicit Casts


To process queries with multiple data types often requires casts that convert
data from one data type to another. You can use the CREATE CAST statement
to create the following kinds of casts:

■ Use the CREATE EXPLICIT CAST statement to define an explicit cast.


■ Use the CREATE IMPLICIT CAST statement to define an implicit cast.

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)

SQL Statements 2-109


CREATE CAST

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 to
convert from the CHAR data type to a distinct data type, percent:
CREATE IMPLICIT CAST (CHAR AS percent WITH char_to_prcnt)

This cast only supports automatic conversion from the CHAR data type to
percent. For the database server to convert from percent to CHAR, you also
need to define another implicit cast, as follows:
CREATE IMPLICIT CAST (percent AS CHAR WITH prcnt_to_char)

The database server automatically invokes the char_to_prcnt( ) function to


evaluate the WHERE clause of the following SELECT statement:
SELECT commission FROM sales_rep WHERE commission > "25%"

Users can also invoke implicit casts explicitly. For more information on how
to explicitly invoke a cast function, see “Explicit Casts” on page 2-109.

When a built-in cast does not exist for conversion between data types, you
can create user-defined casts to make the necessary conversion.

2-110 IBM Informix Guide to SQL: Syntax


CREATE CAST

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:

■ Both data types have the same length and alignment


■ Both data types are passed by reference or both are passed by value

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 the
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 IBM Informix Guide to SQL: Reference.

For examples that show how to create and use casts, see the IBM Informix
Database Design and Implementation Guide.

SQL Statements 2-111


CREATE DATABASE

+
CREATE DATABASE
Use the CREATE DATABASE statement to create a new database.

Syntax

CREATE DATABASE database

IN dbspace WITH LOG

BUFFERED
LOG MODE ANSI

Element Purpose Restrictions Syntax


database Name that you declare here for the Must be unique among the names of Database Name,
new database that you are creating databases on the database server. p. 4-44
dbspace The dbspace to store the data for this Must already exist. Identifier,
database; default is the root dbspace p. 4-189

Usage
This statement is an extension to ANSI-standard syntax. (The ANSI/ISO
standard for the SQL language does not specify any syntax for construction
of a database, the process by which a database comes into existence.)

The database that CREATE DATABASE specifies becomes the current database.

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 can access it. It remains inaccessible
to other users until you, as DBA, grant database privileges. For information
on how to grant database privileges, see “GRANT” on page 2-459.

E/C In ESQL/C, the CREATE DATABASE statement cannot appear in a


multistatement PREPARE operation. ♦

2-112 IBM Informix Guide to SQL: Syntax


CREATE DATABASE

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

The following statement creates the vehicles database in the research


dbspace:
CREATE DATABASE vehicles IN research

XPS In Extended Parallel Server you can create a database in the dbspace of the
primary coserver (coserver 1) only. ♦

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 IMPLICIT TRANSACTION,
SET LOG, and SET ISOLATION).

XPS If you are using Extended Parallel Server, the CREATE DATABASE statement
always creates a database with logging. If you do not specify the WITH LOG
option, the unbuffered log type is used by default. ♦

Designating Buffered Logging


The following example creates a database that uses a buffered log:
CREATE DATABASE vehicles WITH BUFFERED LOG

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 IBM Informix Database Design and
Implementation Guide.)

SQL Statements 2-113


CREATE DATABASE

ANSI ANSI-Compliant Databases


When you use the LOG MODE ANSI option in the CREATE DATABASE
statement, the database that you create is an ANSI-compliant database. The
following example creates an ANSI-compliant database:
CREATE DATABASE employees WITH LOG MODE ANSI

ANSI-compliant databases are different from databases that are not ANSI
compliant in several ways, including 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 with the related SQL statement
in this manual. For a detailed discussion of the differences between ANSI
compliant databases and databases that are not ANSI-compliant, see the
IBM Informix Database Design and Implementation Guide.

Creating an ANSI-compliant database does not mean that you automatically


get warnings for Informix extensions to the ANSI/ISO standard for SQL
syntax when you run the database. You must also use the -ansi flag or the
DBANSIWARN environment variable to receive such warnings.

For additional information about -ansi and DBANSIWARN, see the


IBM Informix Guide to SQL: Reference.

Related Information
Related statements: CLOSE DATABASE, CONNECT, DATABASE, and DROP
DATABASE

2-114 IBM Informix Guide to SQL: Syntax


CREATE DISTINCT TYPE

+ CREATE DISTINCT TYPE


IDS
Use the CREATE DISTINCT TYPE statement to create a new distinct data type.

Syntax

CREATE DISTINCT TYPE distinct_type AS source_type

Element Purpose Restrictions Syntax


distinct_type Name that you In an ANSI-compliant database, the combination of the Data Type,
declare here for the owner and data type must be unique within the database. p. 4-49
new distinct data In a database that is not ANSI compliant, the name must
type be unique among names of data types in the database.
source_type Name of an existing Must be either a built-in data type or one created with the Data Type,
type on which the CREATE DISTINCT TYPE, CREATE OPAQUE TYPE, or p. 4-49
new type is based CREATE ROW TYPE statement.

Usage
A distinct type is a data type based on a built-in data type or on an existing
opaque data type, a named-row data type, or another distinct data type.
Distinct data types are strongly typed. Although the distinct type has the
same physical representation as data of its source type, values of the two
types cannot be compared without an explicit cast from one type to the other

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 user informix owns.

Important: You cannot create a distinct type on the SERIAL or SERIAL8 data type.
To create a distinct type from an opaque type, a named-ROW type, or another
distinct type, you must be the owner of the data type or have the Usage
privilege on the 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.

SQL Statements 2-115


CREATE DISTINCT TYPE

A distinct type has the same storage structure as its source type. The
following statement creates the distinct type birthday, based on the built-in
DATE data type:

CREATE DISTINCT TYPE birthday AS DATE

Although Dynamic Server uses the same storage format for the distinct type
as it does for its source type, a distinct type and its source type cannot be
compared in an operation unless one type is explicitly cast to the other type.

Privileges on Distinct Types


To create a distinct type, you must have the Resource privilege on the
database. When you create the distinct type, only you, the owner, have Usage
privilege on this type. Use the GRANT or REVOKE statements to grant or
revoke Usage privilege to other database users.

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 data type privileges that might have been
granted. For more information on system catalog tables, see the IBM Informix
Guide to SQL: Reference.

DB The DB-Access utility can also display privileges on distinct types. ♦

Support Functions and Casts


When you create a distinct type, Dynamic Server automatically defines two
explicit casts:

■ A cast from the distinct type to its source type


■ A cast from the source type to the distinct type

Because the two data 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. To
create an implicit cast, use the Table Options clause to specify the format of
the external data. You must first drop the default explicit cast, however,
between the distinct type and its source type.

2-116 IBM Informix Guide to SQL: Syntax


CREATE DISTINCT TYPE

All support functions and casts that are defined on the source type can be
used on the distinct type. Casts and support functions that are defined on the
distinct type, however, Use the Table Options clause to specify the format of
the external data.are not available to the source type.

Manipulating Distinct Types


When you compare or manipulate data of a distinct type and its 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);

SELECT col1, col2


FROM t WHERE (col1::NUMERIC) > col2;

SELECT col1, col2, (col1 + col2::dist_type) sum_col


FROM tab;

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 IBM Informix Guide to SQL: Tutorial.

For more information on when you might create a distinct type, see
IBM Informix User-Defined Routines and Data Types Developer’s Guide.

SQL Statements 2-117


CREATE DUPLICATE

+ CREATE DUPLICATE
XPS
Use the CREATE DUPLICATE statement to create a duplicate copy of an
existing table for read-only use in a specified dbslice or in specified dbspaces
across coservers.

Syntax
,

CREATE DUPLICATE OF TABLE table IN ( dbspace )


dbslice

Element Description Restrictions Syntax


dbslice Name of a dbslice in which to Must exist and must contain at most one Database Object
duplicate one fragment of table dbspace on each target coserver. Name
dbspace Name of a dbspace in which to Must exist and must not already contain an Database Object
duplicate one fragment of table original or duplicate fragment of table. Name
table Name of the original table from Must already exist in the database. See also Database Object
which to create a duplicate “Supported Operations” on page 2-120. Name

Usage
If the original table resides entirely on a single coserver, you can create
duplicate copies of small tables across coservers for read-only use. For each
attached index of the original table, a similarly defined index is built on each
table duplicate, using the same dbspaces as the table.

Because query operators read the local copy of the table, duplicating small
tables across coservers might improve the performance of some queries.

If a local copy of a duplicated table exists but is not available because the
dbspace that stores it is offline (or for some similar reason), a query that
requires access to the table fails. The database server does not attempt to
access the original table.

2-118 IBM Informix Guide to SQL: Syntax


CREATE DUPLICATE

The location of a duplicated table can be either a dbslice or a comma-


separated list of dbspaces. You can combine dbslices and lists of dbspaces in
a single CREATE DUPLICATE statement.

■ If the original table is not fragmented, the dbspace list need provide
only a single dbspace on each coserver.
For example, if the table tab1 is not fragmented, enter the following
statement to create a duplicate on the remaining three of the four
coservers if the original table is stored in the dbspace db1 on coserver
1 and db2 is on coserver 2, db3 is on coserver 3, and db4 is on
coserver 4.
CREATE DUPLICATE OF TABLE tab1 IN (db2, db3, db4)
■ If the original table is fragmented with one fragment in the first
dbspace of several dbslices that contain dbspaces on all coservers,
you can create duplicate copies of the table in the remaining
dbspaces of the dbslice.
For example, you might create the tab3 table in the first dbspace of
three dbslices, each of which contains a dbspace on each coserver, as
follows:
CREATE TABLE tab3 (...)
FRAGMENT BY HASH (....) IN dbsl1.l, dbsl2.1, dbsl3.1
To duplicate the tab3 table across the remaining coservers, use the
following statement:
CREATE DUPLICATE OF TABLE tab3 IN dbsl1, dbsl2, dbsl3
■ You can mix dbslice names and dbspace lists in the same CREATE
DUPLICATE statement. For example, instead of using dbspaces in a
dbslice, for the previous example you might enter the following
statement in which dbsp2a is on coserver 2, dbsp3a is on coserver 3,
and dbsp4a is on coserver 4:
CREATE DUPLICATE OF TABLE tab3 IN
dbsl1, dbsl2, (dbsp2a, dbsp3a, dbsp4a)

The first fragment of the original table is duplicated into dbsl1, which
contains a dbspace on each coserver, the second fragment into dbsl2, which
also contains a dbspace on each coserver, and the third fragment into the list
of dbspaces.

SQL Statements 2-119


CREATE DUPLICATE

Only one fragment of a duplicated table can reside in any single dbspace. You
cannot list an existing dbspace of the duplicated table in the list of dbspaces
into which it is duplicated, but it is not an error for an existing dbspace to be
a member of a dbslice that specifies duplication dbspaces. Matching
dbspaces in the dbslice are ignored.

The CREATE DUPLICATE statement requires the ALTER privilege.

Supported Operations
The following operations are permitted on duplicated tables:

■ SELECT
■ UPDATE STATISTICS
■ LOCK and UNLOCK
■ SET RESIDENCY
■ DROP TABLE

You cannot duplicate a table in certain circumstances. The table must not:

■ Have GK or detached indexes


■ Use range fragmentation
■ Be a temporary table
■ Be a violations or diagnostic table
■ Contain BYTE, TEXT, or SERIAL columns
■ Have referential constraints

The CREATE DUPLICATE statement does not support incremental dupli-


cation. It also does not support multiple duplicates of the same table on a
single coserver, nor duplication of tables that are fragmented across
coservers.

If you need to take a dbspace offline and it contains a copy of a duplicated


table, or if you need to update data in a duplicated table, first drop all dupli-
cates of the table, as described in “DROP DUPLICATE.”

Related Statement
DROP DUPLICATE

2-120 IBM Informix Guide to SQL: Syntax


CREATE EXTERNAL TABLE

+ CREATE EXTERNAL TABLE


XPS
Use the CREATE EXTERNAL TABLE statement to define an external source that
is not part of your database to load and unload data for your database.

Syntax

Column DATAFILES
CREATE EXTERNAL TABLE table Definition USING ( Clause )
p. 2-122 p.2-126
Table Table
Options , , Options
p. 2-128 p. 2-128

Element Purpose Restrictions Syntax


table Name declared here for a Must be unique among names of tables, views, Database Object
table to store external data and synonyms in the current database. Name, p. 4-46

Usage
The left-hand portion of the syntax diagram declares the name of the table
and defines its columns and any column-level constraints.

The portion that follows the USING keyword specifies external files that the
database server opens when you use the external table, and additional
options for characteristics of the external table.

After executing the CREATE EXTERNAL TABLE statement, you can move data
to and from the external source with an INSERT INTO ... SELECT statement. See
the section “INTO EXTERNAL Clause” on page 2-635 for more information
about loading the results of a query into an external table.

SQL Statements 2-121


CREATE EXTERNAL TABLE

Column Definition

Column Back to CREATE EXTERNAL TABLE


Definition p. 2-121

SAMEAS template
,
Data Type
column p. 4-49

' HEX' Default Column-Level


Clause Constraints
p. 2-217 p. 2-125
' TEXT'
Data Type
EXTERNAL p. 4-49

' PACKED( p , s )' NULL 'null_string '

' ZONED( p , s )'


' BINARY( n )'

Element Purpose Restrictions Syntax


column One column name for each For each column, you must Identifier, p. 4-189
column of the external table specify a built-in data type
n Number of 8-bit bytes to For FIXED format binary n=2 for 16-bit integers;
represent the integer integers; big-endian byte order n=4 for 32-bit integers
p Precision (total number of digits) For FIXED-format files only Literal Number, p. 4-216
s Scale (digits in fractional part) For FIXED-format files only Literal Number, p. 4-216
null_string Value to be interpreted as NULL See “Defining NULL Values” on Quoted String, p. 4-243
page 2-123.
template Existing table with the same Cannot be subset of columns nor Database Object Name,
schema as the external table differ in any column data type p. 4-46

Using the SAMEAS Clause


The SAMEAS template clause uses all the column names and data types from
the template table in the definition of new table. You cannot, however, use
indexes in the external table definition, and you cannot use the SAMEAS
clause for FIXED-format files.

2-122 IBM Informix Guide to SQL: Syntax


CREATE EXTERNAL TABLE

Using the EXTERNAL Keyword


Use the EXTERNAL keyword to specify a data type for each column of your
external table that has a data type different from the internal table. For
example, you might have a VARCHAR column in the internal table that you
want to map to a CHAR column in the external table.

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-124.

Integer Data Types


Besides valid Informix integer data types, you can specify packed decimal,
zoned decimal, and IBM-format binary representation of integers. For packed
or zoned decimal, specify precision (total number of digits in the number) and
scale (number of digits that are to the right of the decimal point). Packed
decimal representation can store two digits, or a digit and a sign, in each byte.
Zoned decimal requires (p + 1) bytes to store p digits and the sign.

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.

Defining NULL Values


The packed decimal, zoned decimal, and binary data types do not have a
natural NULL value, so you must define a value to be interpreted as a NULL
when loading or unloading data from an external source. You can define the
null_string as a number outside the set of numbers stored in the data file (for
example, -9999.99). You can also define a bit pattern in the field as a
hexadecimal pattern, such as 0xffff, that is to be interpreted as a NULL.

SQL Statements 2-123


CREATE EXTERNAL TABLE

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.

TEXT and HEX External Types


An Informix BYTE or TEXT column can be encoded in either the TEXT or HEX
external type. You can use only delimited BYTE and TEXT formats with these
external types. Fixed formats are not allowed. In addition, you cannot use
these external types with any other type of delimited-format columns (such
as character columns).

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.

2-124 IBM Informix Guide to SQL: Syntax


CREATE EXTERNAL TABLE

User-defined delimiters are limited to one byte each. During unloading,


delimiters and backslash ( \ ) symbols are escaped. During loading, any
character that follows a backslash is interpreted as a literal. In TEXT format,
nonprintable characters are directly embedded in the data file. For delimiter
rules in a multibyte locale, see the IBM Informix GLS User’s Guide.

For more information on BYTE and TEXT data, see your Administrator’s Guide.

Manipulating Data in Fixed Format Files


For files in FIXED format, you must declare the column name and the
EXTERNAL item for each column to set the name and number of characters.
For FIXED-format files, the only data type allowed is CHAR. You can use the
keyword NULL to specify what string to interpret as a NULL value.

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.

Column-Level Back to Column-Definition


Constraints p. 2-122

( Condition )
NOT NULL CHECK p. 4-24

Using 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 that case, no default value
exists for the column. If you place a not-null constraint on a column (and no
default value is specified), the data in the external table must have a value set
for the column when loading through the external table.

When no reject file exists and no value is encountered, the database server
returns an error and the loading stops. When a reject file exists and no value
is encountered, the error is reported in the reject file and the load continues.

SQL Statements 2-125


CREATE EXTERNAL TABLE

Using the CHECK Constraint


Check constraints allow you to designate conditions that must be met before
data can be assigned to a column during an INSERT or UPDATE statement.
When a reject file does not exist and a row evaluates to false for any check
constraint defined on a table during an insert or update, the database server
returns an error. When there is a reject file and a row evaluates to false for a
check constraint defined on the table, the error is reported in the reject file
and the statement continues to execute.

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 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 specifies external files that are opened when you use
external tables.

DATAFILES Back to CREATE EXTERNAL TABLE p. 2-121


Clause Back to INTO EXTERNAL Clause p. 2-632

DATAFILES ( ' DISK : coserver_num : fixed_path ' )

PIPE coserver_group formatted_path

Element Purpose RestrictionsSyntax


coserver_group Coserver group that contains the external data Must exist. Identifier, p. 4-189
coserver_num Numeric ID of coserver containing the external data Must exist. Literal Number, p. 4-216
fixed_path Pathname for input or output files in the definition Must exist. Must conform to
of the external table operating-system rules.
formatted_path Formatted pathname that uses pattern-matching Must exist. Must conform to
characters operating-system rules.

2-126 IBM Informix Guide to SQL: Syntax


CREATE EXTERNAL TABLE

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
underscore symbols.

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 specifying each coserver and file
separately. Whenever you use all coservers to manage external files, you can
use the predefined coserver_group.

For examples of the DATAFILES clause, see “Examples” on page 2-131.

Using Formatting Characters


You can use a formatted pathname to designate a filename. If you use a
formatted pathname, you can take advantage of the substitution characters
%c, %n, and %r(first ... last).

Formatting String Effect

%c Replaced with the number of the coserver that manages the file

%n Replaced with the name of the node on which the coserver that
manages the file resides

%r(first ... last) Specifies multiple files on a single coserver

Important: The formatted pathname option does not support the %o formatting
string.

SQL Statements 2-127


CREATE EXTERNAL TABLE

Table Options
These options specify additional characteristics that define the table.

Table Back to CREATE EXTERNAL TABLE


Options p. 2-121
,

FORMAT ' DELIMITED '


INFORMIX EBCDIC '
FIXED CODESET ' ASCII
DEFAULT DELIMITER ' field_delimiter '
ESCAPE RECORDEND ' record_delimiter '
EXPRESS MAXERRORS num_errors

DELUXE REJECTFILE ' filename '


SIZE num_rows

Element Purpose Restrictions Syntax


field_delimiter Character to separate fields. For nonprinting Quoted String, p. 4-243
Default is pipe (|) character characters, use octal
filename Full pathname for conversion See “Reject Files” on Must conform to
error messages from coservers page 2-130. operating-system rules.
num_errors Errors per coserver before load Value ignored unless Literal Number, p. 4-216
operations are terminated MAXERRORS is set
num_rows Approximate number of rows Cannot be a negative Literal Number, p. 4-216
contained in the external table number
quoted_string ASCII character that represents Only a single character is Quoted String, p. 4-243
the escape valid
record_delimiter Character to separate records. For nonprinting Quoted String, p. 4-243
Default is Newline (\n). characters, use octal

The num_errors specification is ignored during unload tasks. If MAXERRORS


environment variable is not set, the database server processes all data in load
operations, regardless of the number of errors or num_errors value.

2-128 IBM Informix Guide to SQL: Syntax


CREATE EXTERNAL TABLE

If the RECORDEND environment variable is not set, record_delimiter defaults


to the Newline character (\n). To specify a nonprinting character as the
record delimiter or field delimiter, you must encode it as the octal represen-
tation of the ASCII character. For example, '\006' can represent CTRL-F.

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

CODESET Specifies the type of code set of the data

DEFAULT Specifies replacing missing values in delimited input files with


(load only) column defaults (if they are defined) instead of NULLs, so input
files can be sparsely populated. Files do not need an entry for every
column in the file where a default is the value to be loaded.

DELIMITER Specifies the character that separates fields in a delimited text file

DELUXE Sets a flag causing the database server to load data in deluxe mode
(load only) Deluxe mode is required for loading into STANDARD tables.

ESCAPE Defines a character to mark ASCII special characters in ASCII-text-


based data files

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 that reports the problem.

FORMAT Specifies the format of the data in the data files

MAXERRORS Sets the number of errors that are allowed per coserver before the
database server stops the load

RECORDEND Specifies the character that separates records in a delimited text file

REJECTFILE Sets the full pathname where all coservers write data-conversion
errors. If not specified or if files cannot be opened, any error ends
the load job abnormally. See also “Reject Files” on page 2-130.

SIZE The approximate number of rows in the external table. This can
improve performance when external table is used in a join query.

SQL Statements 2-129


CREATE EXTERNAL TABLE

Important: Check constraints on external tables are designed to be evaluated only


when loading data. The database server cannot enforce check constraints on external
tables because the data can be freely altered outside the control of the database server.
If you want to restrict rows that are written to an external table during unload, use
a WHERE clause to filter the rows.

Reject Files
Rows that have conversion errors during a load or rows that violate check
constraints 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 clause declares the name of 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 how to format characters, see the section “Using
Formatting Characters” on page 2-127.

If you perform another load to the same table during the same session, any
earlier reject file of the same name is overwritten.

Reject file entries have the following format:


coserver-number, filename, record, reason-code,
field-name: bad-line

The following table describes these elements of the reject file:

Element Purpose

coserver-number Number of the coserver from which the file is read

filename Name of the input file

record Record number in the input file where the error was detected

reason-code Description of the error

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

bad-line Line that caused the error (delimited or fixed-position character


files only): up to 80 characters

2-130 IBM Informix Guide to SQL: Syntax


CREATE EXTERNAL TABLE

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; but the
Use the Table Options clause to specify the format of the external
data.coserver-number, filename, record, reason-code, and field-name are
still reported in the reject file so you can isolate the problem.

Errors that can cause a row to be rejected include the following.

Error Text Explanation

CONSTRAINT constraint name This constraint was violated.

CONVERT_ERR Any field encounters a conversion error.

MISSING_DELIMITER No delimiter was found.

MISSING_RECORDEND No recordend was found.

NOT NULL A NULL was found in field-name.

ROW_TOO_LONG The input record is longer than 32 kilobytes.

Examples
The examples in this section show how to specify 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 speci-
fication can then be as follows:
DATAFILES ("DISK:cogroup_all:/work2/unload.dir/mytbl")

SQL Statements 2-131


CREATE EXTERNAL TABLE

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.

Then define the file locations for named pipes:


DATAFILES ("PIPE:tape_group:/usr/local/TAPE.%c")

The filenames expand as follows:


DATAFILES ("pipe:2:/usr/local/TAPE.2",
"pipe:5:/usr/local/TAPE.5",
"pipe:9:/usr/local/TAPE.9")

If, instead, you want to process three files on each of two coservers, define the
files as follows:
DATAFILES ("DISK:1:/work2/extern.dir/mytbl.%r(1..3)",
"DISK:2:/work2/extern.dir/mytbl.%r(4..6)")

The expanded list follows:


DATAFILES ("disk:1:/work2/extern.dir/mytbl.1",
"disk:1:/work2/extern.dir/mytbl.2",
"disk:1:/work2/extern.dir/mytbl.3",
"disk:2:/work2/extern.dir/mytbl.4",
"disk:2:/work2/extern.dir/mytbl.5",
"disk:2:/work2/extern.dir/mytbl.6")

Related Information
Related statements: INSERT and SET PLOAD FILE

See also the “INTO Table Clauses” of SELECT.

For more information on external tables, refer to your Administrator’s


Reference.

2-132 IBM Informix Guide to SQL: Syntax


CREATE FUNCTION

+ CREATE FUNCTION
IDS
Use the CREATE FUNCTION statement to create a user-defined function,
register an external function, or to write and register an SPL function.

Syntax

CREATE FUNCTION function ( ) Return


Clause
Routine p. 4-253
DBA Parameter List
p. 4-266

,
Specific Name WITH ( Routine Modifier
SPECIFIC p. 4-274 )
p. 4-257

Statement Block
; SPL p. 4-276 END FUNCTION

External Routine Reference


Ext p.4-187

, WITH LISTING IN 'pathname'


Quoted String
DOCUMENT p. 4-243

Element Purpose Restrictions Syntax


function Name of new function You must have the appropriate language Database Object Name,
that is defined here privileges. See “GRANT” on page 2-459 p. 4-46
and “Naming a Function” on page 2-135.
pathname Pathname to a file in The specified pathname must exist on the The path and filename
which compile-time computer where the database resides. must conform to your
warnings are stored operating-system rules.

Tip: If you are trying to create a function from text of source code that is in a separate
file, use the CREATE FUNCTION FROM statement.

SQL Statements 2-133


CREATE FUNCTION

Usage
The database server supports user-defined functions written in the following
languages:

■ Stored Procedure Language (SPL)


An SPL function can return one or more values.
■ One of the external languages (C or Java) that Dynamic Server
supports (external functions)
An external function must return exactly one value.

For information on how this manual uses the terms UDR, function, and
procedure as well as recommended usage, see “Relationship Between
Routines, Functions, and Procedures” on page 2-183 and “Using CREATE
PROCEDURE Versus CREATE FUNCTION” on page 2-183, respectively.

The entire length of a CREATE FUNCTION statement must be less than


64 kilobytes. This length is the literal length of the statement, including
whitespace characters such as blank spaces and tabs.

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. ♦
IDS Functions use the collating order that was in effect when they were created.
See SET COLLATION for information about using non-default collation ♦

Privileges Necessary for Using CREATE FUNCTION


You must have the Resource privilege on a database to create a function
within that database.

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-459. ♦

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. ♦

2-134 IBM Informix Guide to SQL: Syntax


CREATE FUNCTION

DBA Keyword and Privileges on the Created Function


The level of privilege necessary to execute a UDR depends on whether the
UDR is created with the DBA keyword.

If you create a UDR with the DBA keyword, it is known as a DBA-privileged


UDR. You need the DBA privilege to create or execute a DBA-privileged UDR.

If you omit the DBA keyword, the UDR is known as an owner-privileged UDR.

ANSI If you create an owner-privileged UDR in an ANSI-compliant database,


anyone can execute the UDR. ♦
If you create an owner-privileged UDR in a database that is not ANSI
compliant, the NODEFDAC environment variable prevents privileges on that
UDR from being granted to PUBLIC. If this environment variable is set, the
owner of a UDR must grant the Execute privilege for that UDR to other users.

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:

■ You create a user-defined function with the same name as a built-in


function (such as equal( )) to process a new user-defined data type.
■ You create type hierarchies, in which subtypes inherit data represen-
tation and functions 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 support functions from their source
types.

For a brief description of the routine signature that uniquely identifies each
user-defined function, see “Routine Overloading and Naming UDRs with a
Routine Signature” on page 4-48.

SQL Statements 2-135


CREATE FUNCTION

Using the SPECIFIC Clause to Specify a Specific Name


You can specify a specific name for a user-defined function. A specific name
is a name that is unique in the database. A specific name is useful when you
are overloading a function.

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, that “SPL Functions” on page 2-137 shows:
SELECT data FROM sysprocbody b, sysprocedures p
WHERE b.procid = p.procid
--join between the two catalog tables
AND p.procname = 'update_by_pct'
-- look for procedure named update_by_pct
AND b.datakey = 'D'-- want user document;

The preceding query returns the following text:


USAGE: Update a price by a percentage
Enter an integer percentage from 1 - 100
and a part id number

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. ♦

WITH LISTING IN Clause


The WITH LISTING IN clause specifies a filename where compile time
warnings are sent. After you compile a UDR, this file holds one or more
warning messages.

If you do not use the WITH LISTING IN clause, the compiler does not generate
a list of warnings.

2-136 IBM Informix Guide to SQL: Syntax


CREATE FUNCTION

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 SPL Functions


SPL functions are UDRs written in SPL that return one or more values. To
write and register an SPL function, use a CREATE FUNCTION statement.
Embed appropriate SQL and SPL statements between the CREATE FUNCTION
and END FUNCTION keywords. You can also follow the function with the
DOCUMENT and WITH FILE IN options.

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 IBM Informix Guide to SQL: Reference.

The END FUNCTION keywords are required in every SPL function, and a
semicolon ( ; ) must follow the clause that immediately precedes the
statement block. The following code example creates an SPL function:
CREATE FUNCTION update_by_pct ( pct INT, pid CHAR(10))
RETURNING INT;
DEFINE n INT;
UPDATE inventory SET price = price + price * (pct/100)
WHERE part_id = pid;
LET n = price;
RETURN price;
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 how to write SPL functions, see the chapter about
SPL routines in IBM Informix Guide to SQL: Tutorial.

See also the section “Transactions in SPL Routines” on page 4-280.

SQL Statements 2-137


CREATE FUNCTION

You can include valid SQL or SPL language statements in SPL functions. See,
however, the following sections in Chapter 4 that describe restrictions on SQL
and SPL statements within SPL routines: “Subset of SPL Statements Valid in
the Statement Block” on page 4-276; “SQL Statements Not Valid in an SPL
Statement Block” on page 4-277; and “Restrictions on SPL Routines in Data-
Manipulation Statements” on page 4-279.

Ext External Functions


External functions are functions you write in an external language (that is, a
programming language other than SPL) that Dynamic Server supports.

C To create a C user-defined function

1. Write the C function.


2. Compile the function and store the compiled code in a shared library
(the shared-object file for C).
3. Register the function in the database server with the CREATE
FUNCTION statement.

Java To create a user-defined function written in the Java language

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-414.
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 it executes the external
routine, the database server invokes the external object code.

2-138 IBM Informix Guide to SQL: Syntax


CREATE FUNCTION

The database server stores information about an external function in system


catalog tables, including sysprocbody and sysprocauth. For more infor-
mation on the system catalog, see the IBM Informix Guide to SQL: Reference.

C Example of Registering a C User-Defined Function


The following example registers an external C user-defined function named
equal( ) in the database. This function takes two arguments of the type
basetype1 and returns a single Boolean value. The external routine reference
name specifies the path to the C shared library where the function object code
is actually stored. This library contains a C function basetype1_equal( ),
which is invoked during execution of the equal( ) function.
CREATE FUNCTION equal ( arg1 basetype1, arg2 basetype1)
RETURNING BOOLEAN;
EXTERNAL NAME
"/usr/lib/basetype1/lib/libbtype1.so(basetype1_equal)"
LANGUAGE C
END FUNCTION

Java Example of Registering a User-Defined Function Written in the Java


Language
The following CREATE FUNCTION statement registers the user-defined
function, sql_explosive_reaction( ). This function is discussed in
“sqlj.install_jar” on page 2-418.
CREATE FUNCTION sql_explosive_reaction(int) RETURNS int
WITH (class="jvp")
EXTERNAL NAME "course_jar:Chemistry.explosiveReaction"
LANGUAGE JAVA

This function returns a single INTEGER value. 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.

SQL Statements 2-139


CREATE FUNCTION

Ownership of Created Database Objects


The user who creates an owner-privileged UDR owns any database objects
that are created by the UDR when the UDR is executed, unless another owner
is specified for the created database object. In other words, the UDR owner,
not the user who executes the UDR, is the owner of any database objects
created by the UDR unless another owner is specified in the statement that
creates the database object.

For example, assume that user mike creates this 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.

In the case of a DBA-privileged UDR, however, the user who executes a UDR
(rather than 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 this 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.

See also the section “Support for Roles and User Identity” on page 4-280.

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

Chapter 3 of this manual describes the syntax of the SPL language. For a
discussion on how to create and use SPL routines, see the IBM Informix Guide
to SQL: Tutorial.

2-140 IBM Informix Guide to SQL: Syntax


CREATE FUNCTION FROM

For a discussion on how to create and use external routines, see IBM Informix
User-Defined Routines and Data Types Developer’s Guide.

For information about how to create C UDRs, see the IBM Informix DataBlade
API Programmer’s Guide.

For more information on the NODEFDAC environment variable and the


related system catalog tables (sysprocedures, sysprocplan, sysprocbody and
sysprocauth), see the IBM Informix Guide to SQL: Reference.

+ CREATE FUNCTION FROM


IDS
Use the CREATE FUNCTION FROM statement to access a user-defined
E/C function whose CREATE FUNCTION statement resides in a separate file.

Syntax

CREATE FUNCTION FROM ' file '


file_var

Element Purpose Restrictions Syntax


file Path and filename of a file that contains the Must exist and contain Must conform to
full CREATE FUNCTION statement text. exactly one CREATE operating-system
Default pathname is current directory. FUNCTION statement. rules.
file_var Variable storing value of file Same as for file. Language specific

SQL Statements 2-141


CREATE FUNCTION FROM

Usage
An ESQL/C program cannot directly create a user-defined function. That is,
it cannot contain the CREATE FUNCTION statement.

To create these functions within an ESQL/C program

1. Create a source file with the CREATE FUNCTION statement.


2. Use the CREATE FUNCTION FROM statement to send the contents of
this source file to the database server for execution.
The file that you specify in the file parameter can contain only one
CREATE FUNCTION statement.

For example, suppose that the following CREATE FUNCTION statement is in


a separate file, called del_ord.sql:
CREATE FUNCTION delete_order( p_order_num int)
RETURNING int, int;
DEFINE item_count int;
SELECT count(*) INTO item_count FROM items
WHERE order_num = p_order_num;
DELETE FROM orders WHERE order_num = p_order_num;
RETURN p_order_num, item_count;
END FUNCTION;

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
with no pathname (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. To improve readability of the
code, however, It is recommended that you match these two statements.

2-142 IBM Informix Guide to SQL: Syntax


CREATE FUNCTION FROM

Related Information
Related statements: CREATE FUNCTION, CREATE PROCEDURE, CREATE
PROCEDURE FROM, and CREATE ROUTINE FROM

SQL Statements 2-143


CREATE INDEX

+
CREATE INDEX
Use the CREATE INDEX statement to create an index for one or more columns
in a table, or on values returned by a UDR using columns as arguments.

Syntax

CREATE INDEX index ON table

Index-Type synonym LOCK MODE


Options XPS Options
p. 2-145 p. 2-165

Index-Key
Specification
p. 2-147 IDS FILLFACTOR Storage IDS
Option Options
p. 2-155 p. 2-156 Index
XPS XPS Modes
USING Access- p. 2-161
Method Clause USING BITMAP
p. 2-153
GK SELECT Clause
GK INDEX index ON static ( p. 2-166 ) USING BITMAP

Element Purpose Restrictions Syntax


index Name declared here for a new index Must be unique among index Database Object
names in the database Name, p. 4-46
static Table on which a Generalized Key Table must exist and be static; Database Object
index is created it cannot be a virtual table Name, p. 4-46
synonym, Name or synonym of a standard or Synonym and its table must exist Database Object
table temporary table to be indexed in the current database Name, p. 4-46

Usage
When you issue the CREATE INDEX statement, the table is locked in exclusive
mode. If another process is using the table, CREATE INDEX returns an error.
IDS Indexes use the collation that was in effect when CREATE INDEX executed. ♦

2-144 IBM Informix Guide to SQL: Syntax


CREATE 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, in order to speed up the retrieval of data.
IDS Neither synonym nor table can refer to a virtual table. ♦

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.

Index-Type Back to CREATE INDEX


Options p. 2-144
DISTINCT

UNIQUE CLUSTER

UNIQUE or DISTINCT Option


Use the UNIQUE or DISTINCT keyword to require that the column(s) on
which the index is based accepts only unique data. If you do not specify the
UNIQUE or DISTINCT keyword, the index allows duplicate values in the
indexed column. The following example creates a unique index:
CREATE UNIQUE INDEX c_num_ix ON customer (customer_num)

A unique index prevents duplicate values in the customer_num column.


A column with a unique index can have, at most, one NULL value.

The DISTINCT keyword is a synonym for the keyword UNIQUE, so the


following statement has the same effect as the previous example:
CREATE DISTINCT INDEX c_num_ix ON customer (customer_num)

The index in both examples is maintained in ascending order, which is the


default order.

SQL Statements 2-145


CREATE INDEX

You can also prevent duplicates in a column or set of columns by creating a


unique constraint with the CREATE TABLE or ALTER TABLE statement. You
cannot specify an R-tree secondary-access method for a UNIQUE index key.
For more information on how to create unique constraints, see the CREATE
TABLE or ALTER TABLE statements.

How Indexes Affect Primary-Key, Unique, and Referential Constraints


The database server creates internal B-tree indexes for primary-key, unique,
and referential constraints. If a primary-key, unique, or referential constraint
is added after the table is created, any user-created indexes on the
constrained columns are used, if appropriate. An appropriate index is one
that indexes the same columns that are used in the primary-key, referential,
or unique constraint. If an appropriate user-created index is not available, the
database server creates a nonfragmented internal index on the constrained
column or columns.

CLUSTER Option
Use the CLUSTER keyword to reorder the rows of the table in the order that
the index designates. The CREATE CLUSTER INDEX statement fails if a
CLUSTER index already exists on the same table.

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.

If the CLUSTER option is specified in addition to fragments on an index, the


data is clustered only within the context of the fragment and not globally
across the entire 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. ♦

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-156). 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. ♦

2-146 IBM Informix Guide to SQL: Syntax


CREATE INDEX

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.

Index-Key Back to CREATE INDEX


Specification p. 2-144

,
( column ASC )
IDS , IDS
DESC
op_class
function ( func_col )

Element Purpose Restrictions Syntax


column Column or columns used See “Using a Column as the Index Key” on Identifier,
as a key to this index page 2-148. p. 4-189
function User-defined function Must be a nonvariant function that does not return a Database
used as a key to this index large object data type. Cannot be a built-in algebraic, Object Name,
exponential, log, or hex function. p. 4-46
func_col Column(s) on which the See “Using a Column as the Index Key” on Identifier,
user-defined function acts page 2-148. p. 4-189
op_class Operator class associated If the secondary-access method in the USING clause Identifier,
with column or function for has no default operator class, you must specify one p. 4-189
this index here. (See “Using an Operator Class” on page 2-152.)

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:
■ A column of type LVARCHAR(size), if size is fewer than 387 bytes
■ One or more columns that contain user-defined data types
■ One or more values that a user-defined function returns (referred to
as a functional index)
■ A combination of columns and functions ♦

SQL Statements 2-147


CREATE INDEX

Using a Column as the Index Key


These restrictions apply to a column or columns specified as the index key:

■ All the columns must exist and must be in the table being indexed.
■ The maximum number of columns and total width of all columns
depends on the database server. See “Creating Composite Indexes”
on page 2-149.
■ 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-149.
■ 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 that you can create on the same column or the
same set of columns is restricted. See “Restrictions on the Number of
Indexes on a Set of Columns” on page 2-152.
IDS ■ You cannot create an index on a column of an external table.
■ The column cannot be of a collection data type. ♦

IDS Using a Function as an Index Key


You can create functional indexes within an SPL routine.

You can also create an index on a nonvariant user-defined function that does
not return a large object.

A functional index can be a B-tree index, an R-tree index, or a user-defined


secondary-access method.

Functional indexes are indexed on the value that the specified function
returns, rather than on the value of a column. For example, the following
statement creates a functional index on table zones using the value that the
function Area() returns as the key:
CREATE INDEX zone_func_ind ON zones (Area(length,width));

2-148 IBM Informix Guide to SQL: Syntax


CREATE INDEX

Creating Composite Indexes


A simple index lists only one column (or for IDS, only one column or function)
in its Index Key Specification. Any other index is a composite index. You
should list the columns in a composite index in the order from most-
frequently used to least-frequently used.

XPS
IDS If you use SET COLLATION to specify a non-default locale, you can create
multiple indexes on the same set of columns, using different collations.
(Such indexes would be useful only on NCHAR or NVARCHAR columns.) ♦

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)

The UNIQUE keyword prevents any duplicates of a given combination of


stock_num and manu_code. The index is in ascending order by default.

XPS You can include up to 16 columns in a composite index. The total width of all
indexed columns in a single COMPOSITE index cannot exceed 380 bytes. ♦

XPS
IDS An index key part is either a column in a table, or the result of a user-defined
function on one or more columns. A composite index can have up to 16 key
parts that are columns, or up to 341 key parts that are values returned by a
UDR. This limit is language-dependent, and applies to UDRs written in SPL or
Java; functional indexes based on C language UDRs can have up to 102 key
parts. A composite index can have any of the following items as an index key:

■ One or more columns


■ One or more values that a user-defined function returns (referred to
as a functional index)
■ A combination of columns and user-defined functions

The total width of all indexed columns in a single CREATE INDEX statement
cannot exceed 390 bytes, except for functional indexes of Dynamic Server,
whose language-dependent limits are described earlier in this section. ♦

Using the ASC and DESC Sort-Order Options


The ASC option specifies an index maintained in ascending order; this is the
default order. The DESC option can specify an index that is maintained in
descending order. These ASC and DESC options are valid with B-trees only.

SQL Statements 2-149


CREATE INDEX

Effects of Unique Constraints on Sort Order Options


When a column or list of columns is defined as unique in a CREATE TABLE or
ALTER TABLE statement, the database server implements that UNIQUE
CONSTRAINT by creating a unique ascending index. Thus, you cannot use the
CREATE INDEX statement to add an ascending index to a column or column
list that is already defined as unique.

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 valid:
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)
)

CREATE INDEX c_temp1 ON customer (customer_num DESC)


CREATE INDEX c_temp2 ON customer (customer_num, zipcode)

In this example, the customer_num column has a unique constraint placed


on it. The first CREATE INDEX statement places an index sorted in descending
order on the customer_num column. The second CREATE INDEX includes the
customer_num column as part of a composite index. For more information
on composite indexes, see “Creating Composite Indexes” on page 2-149.

Bidirectional Traversal of Indexes


If you do not specify the ASC or DESC keywords when you create an index on
a column, key values are stored in ascending order by default; but the bidirec-
tional-traversal capability of the database server lets you create just one index
on a column and use that index for queries that specify sorting of results in
either ascending or descending order of the sort column.

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.

2-150 IBM Informix Guide to SQL: Syntax


CREATE INDEX

If you create a composite index on a table, however, 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);
CREATE INDEX stock_idx2 ON stock
(manu_code DESC, unit_price ASC);

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;
SELECT stock_num, manu_code, description, unit_price
FROM stock ORDER BY manu_code DESC, unit_price DESC;

If you want to use a composite index to improve the performance of these


queries, you need to enter one of the following CREATE INDEX statements.
You can use either one of the created indexes (stock_idx3 or stock_idx4) to
improve the performance of the preceding queries.
CREATE INDEX stock_idx3 ON stock
(manu_code ASC, unit_price ASC);
CREATE INDEX stock_idx4 ON stock
(manu_code DESC, unit_price DESC);

You can create no more than one ascending index and one descending index
on a single column. Because of the bidirectional-traversal capability of the
database server, you only need to create one of the indexes. Creating both
would achieve exactly the same results for an ascending or descending sort
on the stock_num column.

SQL Statements 2-151


CREATE INDEX

Restrictions on the Number of Indexes on a Set of Columns


You can create multiple indexes on a set of columns, provided that each index
has a unique combination of ascending and descending columns. For
example, to create all possible indexes on the stock_num and manu_code
columns of the stock table, you could create four indexes:

■ The ix1 index on both columns in ascending order


■ The ix2 index on both columns in descending order
■ The ix3 index on stock_num in ascending order and on manu_code
in descending order
■ The ix4 index on stock_num in descending order and on manu_code
in ascending order

Because of the bidirectional-traversal capability of the database server, you


do not need to create these four indexes. You only need to create two indexes:

■ The ix1 and ix2 indexes achieve the same results for sorts in which
the user specifies the same sort direction (ascending or descending)
for both columns, so you only need one index of this pair.
■ The ix3 and ix4 indexes achieve 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). Thus, you only need to create one index of this pair.
(See also “Bidirectional Traversal of Indexes” on page 2-150.)

IDS Dynamic Serve can also suppport multiple indexes on the same combination
of ascending and descending columns, if each index has a different collating
order; see “SET COLLATION” on page 2-643.

IDS Using an Operator Class


An operator class is the set of operators associated with a secondary-access
method for query optimization and building the index. You must specify an
operator class when you create an index if either one of the following is true:

■ No default operator class for the secondary-access method exists. (A


user-defined access method can provide no default operator class.)
■ You want to use an operator class that is different from the default
operator class that the secondary-access method provides.

2-152 IBM Informix Guide to SQL: Syntax


CREATE INDEX

If you use an alternative access method, and if the access method has a
default operator class, you can omit the operator class here; but if you do not
specify an operator class and the secondary-access method does not have a
default operator class, the database server returns an error. For more infor-
mation, see “Default Operator Classes” on page 2-180. 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);

IDS USING Access-Method Clause


The USING clause specifies the secondary-access method for the new index.

USING Access-Method Back to CREATE INDEX


Clause p. 2-144

,
USING sec_acc_method ( parameter = value )

Element Purpose Restrictions Syntax


parameter Secondary-access-method See the user documentation for your Quoted String,
parameter for this index user-defined access method. p. 4-243
sec_acc_method Secondary-access method Method can be a B-tree, R-tree, or user- Identifier, p. 4-189
for this index defined access method, such as one that
a DataBlade module defines.
value Value of the specified Must be a valid literal value for parameter Quoted String,
parameter in this secondary-access method. p. 4-243 or Literal
Number, p. 4-216

A secondary-access method is a set of routines that perform all of the operations


needed for an index, such as create, drop, insert, delete, update, and scan.

SQL Statements 2-153


CREATE INDEX

The database server provides the following secondary-access methods:

■ The generic B-tree index is the built-in secondary-access method.


A B-tree index is good for a query that retrieves a range of data val-
ues. The database server implements this secondary-access method
and registers it as btree in the system catalog tables.
■ The R-tree method is a registered secondary-access method.
An R-tree index is good for searches on multidimensional data. The
database server registers this secondary-access method as rtree in the
system catalog tables of a database. An R-tree secondary-access
method is not valid for a UNIQUE index key. For more information
on R-tree indexes, see the IBM Informix R-Tree Index User’s Guide.

The access method that you specify must be a valid access method in the
sysams system catalog table. The default secondary-access method is B-tree.

If the access method is B-tree, you can create only one index for each unique
combination of ascending and descending columnar or functional keys with
operator classes. (This does not apply to other secondary-access methods.)
By default, CREATE INDEX creates a generic B-tree index. If you want to
create an index with a secondary-access method other than B-tree, you must
specify the name of the secondary-access method in the USING clause.

Some user-defined access methods are packaged as DataBlades. Some


DataBlade modules provide indexes that require specific parameters when
you create them. For more information about user-defined access methods,
refer to your access-method or DataBlade documentation.

The following example (for a database that implements R-tree indexes)


creates an R-tree index on the location column that contains an opaque data
type, point, and performs a query with a filter on the location column.
CREATE INDEX loc_ix ON TABLE emp (location) USING rtree;
SELECT name FROM emp WHERE location N_equator_equals point('500, 0');

The following CREATE INDEX statement creates an index that uses the
secondary-access method fulltext, which takes two parameters:
WORD_SUPPORT and PHRASE_SUPPORT. It indexes a table t, which has two
columns: i, an integer column, and data, a TEXT column.
CREATE INDEX tx ON t(data)
USING fulltext (WORD_SUPPORT=‘PATTERN’,
PHRASE_SUPPORT=’MAXIMUM’);

2-154 IBM Informix Guide to SQL: Syntax


CREATE INDEX

FILLFACTOR Option
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.

Use the FILLFACTOR option to provide for expansion of an index at a later


date or to create compacted indexes.

FILLFACTOR Back to CREATE INDEX


Option p. 2-144

FILLFACTOR percent

Element Purpose Restrictions Syntax


percent Percentage of each index page that is filled by index 1 ≤ percent ≤ 100 Literal Number,
data when the index is created. The default is 90. p. 4-216

When the index is created, the database server initially fills only that
percentage of the nodes specified with the FILLFACTOR value.
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, see your Administrator’s Guide.

Providing a Low Percentage Value


If you provide a low percentage value, such as 50, you allow room for growth
in your index. The nodes of the index initially fill to a certain percentage and
contain space for inserts. The amount of available space depends on the
number of keys in each page as well as the percentage value.

For example, with a 50-percent FILLFACTOR value, the page would be half
full and could accommodate doubling in size. A low percentage value can
result in faster inserts and can be used for indexes that you expect to grow.

SQL Statements 2-155


CREATE INDEX

Providing a High Percentage Value


If you provide a high percentage value, such as 99, your indexes are
compacted, and any new index inserts result in splitting nodes. The
maximum density is achieved with 100 percent. With a 100-percent
FILLFACTOR value, the index has no room available for growth; any
additions to the index result in splitting the nodes.

A 99-percent FILLFACTOR value allows room for at least one insertion per
node. A high percentage value can result in faster selects and can be used for
indexes that you do not expect to grow or for mostly read-only indexes.

Storage Options
The storage options specify the distribution scheme of an index. You can use
the IN clause to specify a storage space for the entire index, or you can use the
FRAGMENT BY clause to fragment the index across multiple storage spaces.

Storage Back to CREATE INDEX


Options p. 2-144

IN dbspace

XPS dbslice

IDS extspace FRAGMENT BY


Clause for Indexes
p. 2-159

Element Purpose Restrictions Syntax


dbslice The dbslice that contains all of the index fragments Must exist. Identifier, p. 4-189
dbspace The dbspace in which to store the index Must exist. Identifier, p. 4-189
extspace Name assigned by the onspaces command to a Must exist. See the documentation for
storage area outside the database server your access method.

2-156 IBM Informix Guide to SQL: Syntax


CREATE INDEX

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.

XPS For information on locally-detached and globally-detached indexes, see


“FRAGMENT BY Clause for Indexes” on page 2-159. 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-146. ♦

IDS In some earlier releases of Dynamic Server, if you did not use the storage
options to specify a distribution scheme, then by default the index inherited
the distribution scheme of the table on which it was built. Such an index is
called an attached index. In this release, CREATE INDEX creates new indexes as
detached indexes by default, but supports existing attached indexes that
were created by earlier release versions. 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.

Only B-tree indexes that are nonfragmented and that are on nonfragmented
tables can be attached. All other indexes, including extensibility related
indexes, such as R-trees and UDT indexes, must be detached. You cannot
create an attached index using a collating order different from that of the
table, nor different from what DB_LOCALE specifies. For information on how
to create attached indexes, see the description of the DEFAULT_ATTACH
environment variable in IBM Informix Guide to SQL: Reference. ♦

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.

Use the IN dbspace clause to specify the dbspace where you want your index
to reside. When you use this clause, you create a detached index.

SQL Statements 2-157


CREATE INDEX

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

CREATE INDEX idx_cust ON customer (customer_num)


IN custind

XPS Storing an Index in a dbslice


If you are using Extended Parallel Server, the IN dbslice clause allows you to
fragment an index across multiple dbspaces. The database server fragments
the table by round-robin in the dbspaces that make up the dbslice at the time
when the table is created.

IDS Storing an Index in an extspace


In general, use this option in conjunction with the “USING Access-Method
Clause” on page 2-153. You can also store an index in an sbspace. For more
information, refer to the user documentation for your custom access method.

2-158 IBM Informix Guide to SQL: Syntax


CREATE INDEX

FRAGMENT BY Clause for Indexes


Use the FRAGMENT BY clause to create a detached index and to define its
fragmentation strategy across multiple dbspaces.

FRAGMENT BY Back to Storage Options


Clause for Indexes p. 2-156
,
FRAGMENT BY EXPRESSION expr IN dbspace , REMAINDER IN dbspace

XPS , expr

HASH ( column ) IN dbslice

, ,
HYBRID ( column ) EXPRESSION ( dbspace , dbspace )
,
expr IN dbslice , REMAINDER IN dbslice
,
expr dbspace
( dbspace ) ,
dbspace ( dbspace )

Element Purpose Restrictions Syntax


column Column on which to fragment the index Must exist in the current table Identifier, p. 4-189
dbslice Dbslice storing all the index fragments Must exist Identifier, p. 4-189
dbspace Dbspace in which to store the index You must specify at least 2, but no Identifier, p. 4-189
fragment that expr defines more than 2,048 dbspace names
expr Expression defining which index keys See “Restrictions on Fragmen- Expression, p. 4-67;
each fragment stores tation Expressions,” page 2-160. Condition, p. 4-24

To specify a fragmented index, the IN keyword introduces the storage space


where an index fragment is to be stored. If you list multiple dbspace names
after the IN keyword, use parentheses to delimit the dbspace list.

SQL Statements 2-159


CREATE INDEX

Restrictions on Fragmentation Expressions


The following restrictions apply to the expression:

■ Each fragment expression can contain columns only from the current
table, with data values only from a single row.
■ The columns contained in a fragment expression must be the same as
the indexed columns or a subset of the indexed columns.
■ The expression must return a Boolean (true or false) value.
■ No subqueries, aggregates, user-defined routines, nor references to
fields of a ROW type column are allowed.
■ The built-in CURRENT, DATE, and TIME functions are not allowed.

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.

Detached indexes can be either locally detached or globally detached. A


locally detached index is an index in which, for each data tuple in a table, the
corresponding index tuple is guaranteed to be on the same coserver. The
table and index fragmentation strategies do not have to be identical as long
as co-locality can be guaranteed. If the data tuple and index tuple co-locality
do not exist, then the index is a globally-detached index. For performance impli-
cations of globally-detached indexes, see your Performance Guide.

For more information on expression, hash, and hybrid distribution schemes,


see “Fragmenting by EXPRESSION” on page 2-239, “Fragmenting by
HASH” on page 2-242, and “Fragmenting by HYBRID” on page 2-243,
respectively, in the description of the CREATE TABLE statement. ♦

Fragmentation of System Indexes


System indexes (such as those used in referential constraints and unique
constraints) utilize user indexes if they exist. If no user indexes can be
utilized, system indexes remain nonfragmented and are moved to the
dbspace where the database was created.

To fragment a system index, create the fragmented index on the constraint


columns, and then add the constraint using the ALTER TABLE statement.

2-160 IBM Informix Guide to SQL: Syntax


CREATE INDEX

IDS Fragmentation of Unique Indexes


You can fragment unique indexes only with a table that uses an expression-
based distribution scheme. The columns referenced in the fragment
expression must be part of the indexed columns. If your CREATE INDEX
statement fails to meet either of these restrictions, the CREATE INDEX fails,
and work is rolled back.

Fragmentation of Indexes on Temporary Tables


You can fragment a unique index on a temporary table only if the underlying
table uses an expression-based distribution scheme. That is, the CREATE
Temporary TABLE statement that defines the temporary table must specify an
explicit expression-based distribution scheme.

If you try to create a fragmented, unique index on a temporary table for


which you did not specify a fragmentation strategy when you created the
table, the database server creates the index in the first dbspace that the
DBSPACETEMP environment variable specifies.For more information on the
DBSPACETEMP environment variable, see the IBM Informix Guide to SQL:
Reference.

For more information on the default storage characteristics of temporary


tables, see “Where Temporary Tables are Stored” on page 2-266.

IDS Index Modes


Use the index modes to control the behavior of the index during INSERT,
DELETE, and UPDATE operations.

Index Modes Back to CREATE INDEX


p. 2-144

ENABLED

DISABLED WITHOUT ERROR

FILTERING WITH ERROR

SQL Statements 2-161


CREATE INDEX

The following table explains the index modes.

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.

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.

If you specify filtering for a unique index, you can also specify one of the
following error options.

Error Option Purpose

WITHOUT ERROR A unique-index violation during an insert or update


operation returns no integrity-violation error to the user.

WITH ERROR Any unique-index violation during an insert or update


operation returns an integrity-violation error to the user.

2-162 IBM Informix Guide to SQL: Syntax


CREATE INDEX

Specifying Modes for Unique Indexes


You must observe the following rules when you specify modes for unique
indexes in CREATE INDEX statements:

■ You can set the mode of a unique index to enabled, disabled, or


filtering.
■ If you do not specify a mode, then by default the index is enabled.
■ For an index set to filtering mode, if you do not specify an error
option, the default is WITHOUT ERROR.
■ When you add a new unique index to an existing base table and
specify the disabled mode for the index, your CREATE INDEX
statement succeeds even if duplicate values in the indexed column
would cause a unique-index violation.
■ 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.

Adding a Unique Index When Duplicate Values Exist in the Column


If you attempt to add a unique index in the enabled mode but receive an error
message because duplicate values are in the indexed column, take the
following steps to add the index successfully:
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.

SQL Statements 2-163


CREATE INDEX

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.

Specifying Modes for Duplicate Indexes


You must observe the following rules when you specify modes for duplicate
indexes in CREATE INDEX statements:

■ You can set a duplicate index to enabled or disabled mode. Filtering


mode is available only for unique indexes.
■ If you do not specify the mode of a duplicate index, by default the
index is enabled.

IDS How the Database Server Treats Disabled Indexes


Whether a disabled index is a unique or duplicate index, the database server
effectively ignores the index during data-manipulation (DML) operations.

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. 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. Similarly, you
cannot create an active (enabled) unique, foreign-key, or primary-key
constraint on a column or set of columns if the indexes on which the active
constraint depends are disabled.

2-164 IBM Informix Guide to SQL: Syntax


Generalized-Key Indexes

XPS LOCK MODE Options


The LOCK MODE options specify the locking granularity of the index.

LOCK MODE Back to CREATE INDEX


Options COARSE p. 2-144

LOCK MODE NORMAL

In 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 specify no lock mode, the default is NORMAL. That is, the database
server places item-level or page-level locks on the index as necessary.

XPS Generalized-Key Indexes


If you are using Extended Parallel Server, you can create generalized-key
(GK) indexes. Keys in a conventional index consist of one or more columns of
the STATIC table that is being indexed. A GK index stores information about
the records in a STATIC table based on the results of a query.

GK indexes provide a form of pre-computed index capability that allows


faster query processing, especially in data-warehousing environments. The
optimizer can use the GK index to improve performance.

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:

■ All tables used in a GK index must be STATIC tables. If you try to


change the type of a table to a non-static type while a GK index
depends on that table, the database server returns an error.
■ Any table involved in a GK index must be a STATIC type. UPDATE,
DELETE, INSERT, and LOAD operations are not valid on such a table
until the dependent GK index is dropped and the table type changes.

Key-only index scans are not available with GK indexes.

SQL Statements 2-165


Generalized-Key Indexes

SELECT Clause for Generalized-Key Index


If you are using Extended Parallel Server, the options of the GK SELECT clause
are a subset of the options of “SELECT” on page 2-581. The GK SELECT clause
has the following syntax.

GK SELECT Back to CREATE INDEX


Clause p. 2-144
,
Expression GK
SELECT ALL FROM
p. 4-67
DISTINCT Clause
p. 2-167 GK
+ * WHERE
table. Clause
UNIQUE p. 2-168
synonym.
alias.

Element Purpose Restrictions Syntax


alias Temporary name assigned to the You cannot use an alias for the table Identifier, p. 4-189
table in the FROM clause on which the index is built
synonym, Synonym or table from which to The synonym and the table to Database Object
table retrieve data which it points must exist Name, p. 4-46

The following restrictions apply to expressions in the GK SELECT clause:


■ It cannot refer to any SPL routine.
■ It cannot include the USER, TODAY, CURRENT, DBINFO built-in
functions, nor any function that refers to a point in time or interval.

2-166 IBM Informix Guide to SQL: Syntax


Generalized-Key Indexes

FROM Clause for Generalized-Key Index

GK FROM Back to GK SELECT Clause


Clause p. 2-166

FROM indexed_table

synonym1
, table

synonym2 AS alias

Element Purpose Restrictions Syntax


alias Temporary name for a table You cannot use an alias with Identifier, p. 4-189
indexed_table.
indexed_table, Table on which the index is The FROM clause must include Database Object
synonym1 being built the indexed table. Name, p. 4-46
synonym2, Synonym or table from which to The synonym and the table to Database Object
table retrieve data which it points must exist. Name, p. 4-46

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)

SQL Statements 2-167


Generalized-Key Indexes

WHERE Clause for Generalized-Key Index

GK WHERE Back to GK SELECT Clause


Clause AND p. 2-166

Condition
WHERE p. 4-24

Join
p. 2-619

The WHERE clause for a GK index has the following limitations:

■ It cannot include USER, TODAY, CURRENT, nor DBINFO built-in


functions, nor any functions that refer to time or a time interval.
■ It cannot refer to any SPL routine.
■ It cannot have any subqueries.
■ It cannot use any aggregate function.
■ It cannot have any IN, LIKE, or MATCH clauses.

Related Information
Related statements: ALTER INDEX, CREATE OPCLASS, CREATE TABLE, DROP
INDEX, RENAME INDEX, and SET Database Object Mode

For a discussion of the structure of indexes, see your Administrator’s Reference.

For a discussion of the different types of indexes and information about


performance issues with indexes, see your Performance Guide.

GLS For a discussion of the GLS aspects of the CREATE INDEX statement, see the
IBM Informix GLS User’s Guide. ♦

For information about operator classes, refer to the CREATE OPCLASS


statement and IBM Informix User-Defined Routines and Data Types Developer’s
Guide.

For information about the indexes that DataBlade modules provide, refer to
your DataBlade module user’s guide.

2-168 IBM Informix Guide to SQL: Syntax


CREATE OPAQUE TYPE

+ CREATE OPAQUE TYPE


IDS
Use the CREATE OPAQUE TYPE statement to create an opaque data type.

Syntax

CREATE OPAQUE TYPE type ( INTERNALLENGTH = length )


VARIABLE

,
, Opaque-Type Modifier
p. 2-171

Element Purpose Restrictions Syntax


length Number of bytes needed to store Positive integer returned when sizeof( ) Literal Number,
a value of this data type directive is applied to the type structure. p. 4-216
type Name that you declare here for Must be unique among data type names Identifier, p. 4-189;
the new opaque data type in the database. Data Type, p. 4-49

Usage
The CREATE OPAQUE TYPE statement registers a new opaque type in the
sysxtdtypes system catalog table.

To create an opaque type, you must have the Resource privilege on the
database. When you create the opaque type, only you, the owner, have the
Usage privilege on this type. Use the GRANT or REVOKE statements to grant
or revoke the Usage privilege to other database users.

To view the privileges on a data 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 details of system catalog tables, see the IBM Informix Guide to SQL:
Reference.

SQL Statements 2-169


CREATE OPAQUE TYPE

DB The DB-Access utility can also display privileges on opaque types. ♦

Declaring a Name for an Opaque Type


The name that you declare for an opaque data type is an SQL identifier. When
you create an opaque type, the name must be unique within a database.

ANSI When you create an opaque type in an ANSI-compliant database, owner.type


combination must be unique within the database.

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 storage size that is required for
the opaque type as fixed length or varying length.

Fixed-Length Opaque Types


A fixed-length opaque type has an internal structure of fixed size. To create a
fixed-length opaque type, specify the size of the internal structure, in bytes,
for the INTERNALLENGTH modifier. The next example creates a fixed-length
opaque type called fixlen_typ and allocates 8 bytes for this type.
CREATE OPAQUE TYPE fixlen_typ(INTERNALLENGTH=8, CANNOTHASH)

Varying-Length Opaque Types


A varying-length opaque type has an internal structure whose size might
vary from one value to another. For example, the internal structure of an
opaque type might hold the actual value of a string up to a certain size but
beyond this size it might use an LO-pointer to a CLOB to hold the value.
To create a varying-length opaque data type, use the VARIABLE keyword
with the INTERNALLENGTH modifier. The following statement creates a
variable-length opaque type called varlen_typ:
CREATE OPAQUE TYPE varlen_typ
(INTERNALLENGTH=VARIABLE, MAXLEN=1024)

2-170 IBM Informix Guide to SQL: Syntax


CREATE OPAQUE TYPE

Opaque-Type Modifier

Opaque-Type Modifier Back to CREATE OPAQUE TYPE


p. 2-169

MAXLEN = length

CANNOTHASH

PASSEDBYVALUE

ALIGNMENT = align_value

Element Purpose Restrictions Syntax


align_value Byte boundary on which to align an Must be 1, 2, 4, or 8, depending on the C Literal
opaque type that is passed to a user-
definition of the opaque type and hardware Number,
defined routine. Default is 4 bytes.
and compiler used to build the object file p. 4-216
for the type.
length Maximum length to allocate for Must be a positive integer £ 32 kilobytes. Literal
instances of varying-length opaque Do not specify for fixed-length data types. Number,
types. Default is 2 kilobytes. Values that exceed this length return errors. p. 4-216

Modifiers can specify the following optional information for opaque types:

■ MAXLEN specifies the maximum length for varying-length types.


■ CANNOTHASH specifies that the database server cannot use the
built-in hash function on the opaque type.
■ ALIGNMENT specifies the byte boundary on which the database
server aligns the opaque type.
■ PASSEDBYVALUE specifies that an opaque type of 4 bytes or fewer is
passed by value.

By default, opaque types are passed to user-defined routines by reference.

SQL Statements 2-171


CREATE OPAQUE TYPE

Defining an Opaque Type


To define the opaque type to the database server, you must provide the
following information in the C or Java language:

■ A data structure that serves as the internal storage of the opaque type
The internal storage details of the type are hidden, or opaque. Once
you define a new opaque type, the database server can manipulate it
without knowledge of the C or Java 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 or Java programming language.
■ Additional user-defined functions that other support functions or
end users can invoke to operate on the opaque type (optional)
Possible support functions include operator functions and cast func-
tions. Before you can use these functions in SQL statements, they
must be registered with the appropriate CREATE CAST, CREATE PRO-
CEDURE, or CREATE FUNCTION statement.

The following table summarizes the support functions for an opaque type.

Function Description Invoked

input( ) Converts the opaque type from its external When a client application sends a
LVARCHAR representation to its internal character representation of the
representation opaque type in an INSERT,
UPDATE, or LOAD statement
output( ) Converts the opaque type from its internal When the database server sends a
representation to its external LVARCHAR character representation of the
representation opaque type as a result of a SELECT
or FETCH statement
receive( ) Converts the opaque type from its internal When a client application sends an
representation on the client computer to its internal representation of the
internal representation on the server computer opaque type in an INSERT,
Provides platform-independent results UPDATE, or LOAD statement
regardless of differences between client and
server computer types
(1 of 3)

2-172 IBM Informix Guide to SQL: Syntax


CREATE OPAQUE TYPE

Function Description Invoked

send( ) Converts the opaque type from its internal repre- When the database server sends an
sentation on the server computer to its internal internal representation of the
representation on the client computer opaque type as a result of a SELECT
Provides platform-independent results or FETCH statement
regardless of differences between client and
database server computer types
db_receive( ) Converts the opaque type from its internal repre- When a local database receives a
sentation on the local database to the dbsendrecv type from an external
DBSENDRECV type for transfer to an external database on the local database
database on the local server server
db_send( ) Converts the opaque type from its internal repre- When a local database sends a
sentation on the local database to the dbsendrecv type to an external
DBSENDRECV type for transfer to an external database on the local database
database on the local server server
server_receive( ) Converts the opaque type from its internal repre- When the local database server
sentation on the local server computer to the receives a srvsendrecv type from a
SRVSENDRECV type for transfer to a remote remote database server
database server
Use any name for this function.
server_send( ) Converts the opaque type from its internal repre- When the local database server
sentation on the local server computer to the sends a srvsendrecv type to a
SRVSENDRECV type for transfer to a remote remote database server
database server
Use any name for this function.
import( ) Performs any tasks needed to convert from the When DB-Access (LOAD) or the
external (character) representation of an opaque High-Performance Loader (HPL)
type to the internal format for a bulk copy initiates a bulk copy from a text file
to a database
export ( ) Performs any tasks needed to convert from the When DB-Access (UNLOAD) or the
internal representation of an opaque type to the High Performance Loader initiates
external (character) format for a bulk copy a bulk copy from a database to a text
file
importbinary( ) Performs any tasks needed to convert from the When DB-Access (LOAD) or the
internal representation of an opaque type on the High Performance Loader initiates
client computer to the internal representation on a bulk copy from a binary file to a
the server computer for a bulk copy database
(2 of 3)

SQL Statements 2-173


CREATE OPAQUE TYPE

Function Description Invoked

exportbinary( ) Performs any tasks needed to convert from the When DB-Access (UNLOAD) or the
internal representation of an opaque type on the High Performance Loader initiates
server computer to the internal representation on a bulk copy from a database to a
the client computer for a bulk copy binary file
assign() Performs any processing required before storing When the database server executes
the opaque type to disk INSERT, UPDATE, or LOAD, before
This support function must be named assign( ). it stores the opaque type to disk

destroy() Performs any processing necessary before When the database server executes
removing a row that contains the opaque type the DELETE or DROP TABLE,
This support function must be named destroy( ). before it removes the opaque type
from disk
lohandles() Returns a list of the LO-pointer structures When the database server must
(pointers to smart large objects) in an opaque search opaque types for references
type to smart large objects: when
oncheck runs, or an archive is
performed
compare() Compares two values of the opaque type and When the database server
returns an integer value to indicate whether the encounters an ORDER BY,
first value is less than, equal to, or greater than UNIQUE, DISTINCT, or UNION
the second value clause in a SELECT statement, or
when CREATE INDEX creates a B-
tree index
(3 of 3)

After 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.

After you have written the necessary C language or Java language source
code to define an opaque data type, you then use the CREATE OPAQUE TYPE
statement to register the opaque data type in the database.

2-174 IBM Informix Guide to SQL: Syntax


CREATE OPAQUE TYPE

Related Information
Related statements: CREATE CAST, CREATE DISTINCT TYPE, CREATE
FUNCTION, CREATE ROW TYPE, CREATE TABLE, and DROP TYPE

For a description of an opaque type, see the IBM Informix Guide to SQL:
Reference.

For information on how to define an opaque type, see IBM Informix User-
Defined Routines and Data Types Developer’s Guide.

For information on how to use the Java language to define an opaque type,
see the J/Foundation Developer’s Guide.
For information about the GLS aspects of the CREATE OPAQUE TYPE
statement, refer to the IBM Informix GLS User’s Guide.

SQL Statements 2-175


CREATE OPCLASS

+ CREATE OPCLASS
IDS
Use the CREATE OPCLASS statement to create an operator class for a secondary-
access method.

Syntax

CREATE OPCLASS opclass FOR sec_acc_method STRATEGIES

, ,
Strategy Specification
( p. 2-178 ) SUPPORT ( support_function )

Element Purpose Restrictions Syntax


opclass Name that you declare here for Must be unique among operator Database Object
operator class classes within the database.
sec_acc_method Secondary-access method with Must already exist and must be Identifier,
which the specified operator class registered in the sysams system p. 4-189
is being associated catalog table.
support_function Support function that the Must be listed in the order Identifier,
secondary-access method requires expected by the access method. p. 4-189

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.

The database server provides the B-tree and R-tree secondary-access


methods. For more information on the btree secondary-access method, see
“Default Operator Classes” on page 2-180.

2-176 IBM Informix Guide to SQL: Syntax


CREATE OPCLASS

Define a new operator class when you want one of the following:

■ An index to use a different order for the data than the sequence that
the default operator class provides
■ 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.

ANSI When you create an operator class in an ANSI-compliant database,


owner.opclass_name must be unique within the 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. ♦

The following CREATE OPCLASS statement creates a new operator class


called abs_btree_ops for the btree secondary-access method:
CREATE OPCLASS abs_btree_ops FOR btree
STRATEGIES (abs_lt, abs_lte, abs_eq, abs_gte, abs_gt)
SUPPORT (abs_cmp)

An operator class has two kinds of operator-class functions:

■ Strategy functions
Specify strategy functions of an operator class in the STRATEGY
clause of the CREATE OPCLASS statement. In the preceding CREATE
OPCLASS code example, the abs_btree_ops operator class has five
strategy functions.
■ Support functions
Specify support functions of an operator class in the SUPPORT clause.
In the preceding CREATE OPCLASS code example, 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.

SQL Statements 2-177


CREATE OPCLASS

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 IBM Informix User-Defined Routines and Data Types Developer’s
Guide.

Strategy Specification

Strategy Specification Back to CREATE OPCLASS, p. 2-176

strategy_function
,
( 2 input_type )
output_type

Element Purpose Restrictions Syntax


input_type Data type of the input argument A strategy function takes two Data Type,
for the strategy function for which input arguments and one p. 4-49
you want to use a specific optional output argument.
secondary-access method
output_type Data type of the optional output This is an optional output Data Type,
argument for the strategy function argument for side-effect indexes. p. 4-49
strategy_function Name of a strategy function to Must be listed in the order that Database Object
associate with the specified the specified secondary-access Name, p. 4-46
operator class method expects.

2-178 IBM Informix Guide to SQL: Syntax


CREATE OPCLASS

The strategy_function is an external function. The CREATE OPCLASS statement


does not verify that a user-defined function of the name you specify exists.
However, for the secondary-access method to use the strategy function, the
external function must be:

■ Compiled in a shared library


■ Registered in the database with the CREATE FUNCTION statement

Optionally, you can specify the signature of a strategy function in addition to


its name. A strategy function requires two input parameters and an optional
output parameter. To specify the function signature, specify:
■ 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 UDTs as well as built-in data 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.

Indexes on Side-Effect Data


Side-effect data are additional values that a strategy function returns after a
query that contains 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 side-effect data with the qualifying images.

SUPPORT Clause
Support functions are functions that the secondary-access method uses
internally to build and search the index. Specify these functions for the
secondary-access method in the SUPPORT clause of CREATE OPCLASS.

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-180.

SQL Statements 2-179


CREATE OPCLASS

The support function is an external function. CREATE OPCLASS does not


verify that a named support function exists. For the secondary-access method
to use a support function, however, the support function must be:

■ Compiled in a shared library


■ Registered in the database with the CREATE FUNCTION statement

Default Operator Classes


Each secondary-access method has a default operator class that is associated
with it. By default, the CREATE INDEX statement associates the default
operator class with an index. For example, the following CREATE INDEX
statement creates a B-tree index on the zipcode column and automatically
associates the default B-tree operator class with this column:
CREATE INDEX zip_ix ON customer(zipcode)

For each of the secondary-access methods that Dynamic Server provides, it


provides a default operator class, as follows:

■ The default B-tree operator class is a built-in operator class.


The database server implements the operator-class functions for this
operator class and registers it as btree_ops in the system catalog
tables of a database.
■ The default R-tree operator class is a registered operator class.
The database server registers this operator class as rtree_ops in the
system catalog tables. The database server does not implement the
operator-class functions for the default R-tree operator class.
Important: To use an R-tree index, you must install a spatial DataBlade module such
as the Geodetic DataBlade module or any other third-party DataBlade module that
implements the R-tree index. These implement the R-tree operator-class functions.

DataBlade modules can provide other types of secondary-access methods. If


a DataBlade module provides a secondary-access method, it might also
provide a default operator class. For more information, refer to your
DataBlade module user’s guide.

2-180 IBM Informix Guide to SQL: Syntax


CREATE OPCLASS

Related Information
Related statements: CREATE FUNCTION, CREATE INDEX, and DROP OPCLASS

For information on support functions and how to create and extend an


operator class, see IBM Informix User-Defined Routines and Data Types
Developer’s Guide.

For more about R-tree indexes, see the IBM Informix R-Tree Index User’s Guide.

For information about the GLS aspects of the CREATE OPCLASS statement,
refer to the IBM Informix GLS User’s Guide.

SQL Statements 2-181


CREATE PROCEDURE

+
CREATE PROCEDURE
Use the CREATE PROCEDURE statement to create a user-defined procedure.
(To create a procedure from text of source code that is in a separate file, use
the CREATE PROCEDURE FROM statement.)

Syntax

CREATE PROCEDURE procedure ( )


SPL Routine
DBA Parameter List
function p. 4-266

SPL IDS ,
Specific
Return Name IDS
SPECIFIC WITH ( Routine )
Clause p. 4-274 SPL Modifier
p. 4-253 p. 4-257

Statement Block
; SPL p. 4-276 END PROCEDURE

IDS External Routine Reference


Ext p.4-187

, WITH LISTING IN 'pathname'


Quoted String
DOCUMENT p. 4-243

Element Purpose Restrictions Syntax


function, Name declared here (XPS) The name must be unique among all Database Object Name,
procedure for a new SPL function SPL routines in the database. p. 4-46
or procedure (IDS) See “Naming a Procedure in
Dynamic Server” on page 2-185.
pathname File to store compile- Must exist on the computer where the Must conform to naming
time warnings database resides. rules of operating system.

2-182 IBM Informix Guide to SQL: Syntax


CREATE PROCEDURE

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, tabs, and other whitespace characters.

E/C In ESQL/C, you can use CREATE PROCEDURE only as text 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. ♦
IDS Routines use the collating order that was in effect when they were created.
See SET COLLATION for information about using non-default collation ♦

Using CREATE PROCEDURE Versus CREATE FUNCTION


XPS In Extended Parallel Server, besides using this statement to create SPL proce-
dures, yoau must use CREATE PROCEDURE to write and register an SPL
routine that returns one or more values (that is, an SPL function). Extended
Parallel Server does not support the CREATE FUNCTION statement. ♦

IDS In Dynamic Server, although you can use CREATE PROCEDURE to write and
register an SPL routine that returns one or more values (that is, an SPL
function), it is recommended that you use CREATE FUNCTION instead. To
register an external function, you must use CREATE FUNCTION.

Use the CREATE PROCEDURE statement to write and register an SPL


procedure or to register an external procedure. ♦

For information on how terms such as user-defined procedures and user-


defined functions are used in this manual, see “Relationship Between
Routines, Functions, and Procedures” on page 2-183.

Tip: If you are trying to create a procedure from text that is in a separate file, use the
CREATE PROCEDURE FROM statement.

Relationship Between Routines, Functions, and Procedures


A procedure is a routine that can accept arguments but does not return any
values. A function is a routine that can accept arguments and returns one or
more values. User-defined routine (UDR) is a generic term that includes both
user-defined procedures and user-defined functions. For information about
named and unnamed returned values, see “Return Clause” on page 4-253.

SQL Statements 2-183


CREATE PROCEDURE

You can write a UDR in SPL (SPL routine) or in an external language (external
routine) that the database server supports. Where the term UDR appears in the
manual, it can refer to both SPL routines and external routines.

The term user-defined procedure refers to SPL procedures and external proce-
dures. User-defined function refers to SPL functions and external functions.

SPL In earlier IBM 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. ♦

IDS The term external routine applies to an external procedure or an external


function. When it is necessary to distinguish between an external function
and an external procedure, the manual does so. ♦

XPS Extended Parallel Server does not support external routines, but the term
user-defined routine (UDR) encompasses both SPL routines and external
routines. Wherever the term UDR appears, it is applicable to SPL routines. ♦

Privileges Necessary for Using CREATE PROCEDURE


You must have the Resource privilege on a database to create a user-defined
procedure within that database.

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-459. ♦

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. ♦

DBA Keyword and Privileges on the Created Procedure


If you create a UDR with the DBA keyword, it is known as a DBA-privileged
UDR. You need the DBA privilege to create or execute a DBA-privileged UDR.
If you omit the DBA keyword, the UDR is known as an owner-privileged UDR.

ANSI If you create an owner-privileged UDR in an ANSI-compliant database,


anyone can execute the UDR. ♦

2-184 IBM Informix Guide to SQL: Syntax


CREATE PROCEDURE

If you create an owner-privileged UDR in a database that is not ANSI


compliant, the NODEFDAC environment variable prevents privileges on that
UDR from being granted to PUBLIC. If this environment variable is set, the
owner of a UDR must grant the Execute privilege for that UDR to other users.

XPS Naming a Procedure in Extended Parallel Server


In Extended Parallel Server, the name for any SPL routine that you create
must be unique among the names of all SPL routines in the database.

IDS Naming a Procedure in Dynamic Server


Because Dynamic Server offers routine overloading, you can define more than
one user-defined routine (UDR) with the same name, but different parameter
lists. You might want to overload UDRs in the following situations:

■ 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-48.

Using the SPECIFIC Clause to Specify a Specific Name


You can specify a specific name for a user-defined procedure. A specific name
is a name that is unique in the database. A specific name is useful when you
are overloading a procedure.

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.

SQL Statements 2-185


CREATE PROCEDURE

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. A UDR or application program can query the system catalog tables
to fetch the DOCUMENT clause and display it for a user.

For example, to find the description of the SPL procedure raise_prices, shown
in “SPL Procedures” on page 2-187, enter a query such as this example:
SELECT data FROM sysprocbody b, sysprocedures p
WHERE b.procid = p.procid
--join between the two catalog tables
AND p.procname = 'raise_prices'
-- look for procedure named raise_prices
AND b.datakey = 'D';-- want user document

The preceding query returns the following text:


USAGE: EXECUTE PROCEDURE raise_prices( xxx )
xxx = percentage from 1 - 100

Ext You can use a DOCUMENT clause at the end of the CREATE PROCEDURE
statement, whether or not you use the END PROCEDURE keywords. ♦

Using the WITH LISTING IN Option


The WITH LISTING IN clause specifies a filename where compile time
warnings are sent. After you compile a UDR, this file holds one or more
warning messages. This listing file is created on the computer where the
database resides.

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 computer. Otherwise,
the default directory is %INFORMIXDIR%\bin. ♦

2-186 IBM Informix Guide to SQL: Syntax


CREATE PROCEDURE

SPL SPL Procedures


SPL procedures are UDRs written in Stored Procedure Language (SPL) that do
not return a value. To write and register an SPL routine, use the CREATE
PROCEDURE statement. Embed appropriate SQL and SPL statements between
the CREATE PROCEDURE and END PROCEDURE keywords. You can also
follow the UDR definition with the DOCUMENT and WITH FILE IN options.

SPL routines are parsed, optimized (as far as possible), and stored in the
system catalog tables in executable format. The body of an SPL routine is
stored in the sysprocbody system catalog table. Other information about the
routine is stored in other system catalog tables, including sysprocedures,
sysprocplan, and sysprocauth.

If the Statement Block portion of the CREATE PROCEDURE statement is


empty, no operation takes place when you call the procedure. You might use
such a procedure in the development stage when you want to establish the
existence of a procedure but have not yet coded it.

If you specify an optional clause after the parameter list, you must place a
semicolon after the clause that immediately precedes the Statement Block.

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'

IDS External Procedures


Ext External procedures are procedures you write in an external language that the
database server supports.

To create a C user-defined procedure

1. Write a C function that does not return a value.


2. Compile the C function and store the compiled code in a shared
library (the shared-object file for C).
3. Register the C function in the database server with the CREATE
PROCEDURE statement.

SQL Statements 2-187


CREATE PROCEDURE

To create a user-defined procedure written in the Java language

1. Write a Java static method, which can use the JDBC functions to
interact with the database server.
2. Compile the Java source and create a jar file (the shared-object file).
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, using the setUDTExtName( ) procedure
that is explained in “EXECUTE PROCEDURE” on page 2-414.
5. Register the UDR with the CREATE PROCEDURE statement. (If an
external routine returns a value, you must register it with the
CREATE FUNCTION statement, rather than CREATE PROCEDURE.)

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. The database server executes an
external routine by invoking the external object code.

Registering a User-Defined Procedure


C This example registers a C user-defined procedure named check_owner( )
that takes one argument of the type LVARCHAR. The external routine
reference specifies the path to the C shared library where the procedure object
code is stored. This library contains a C function unix_owner( ), which is
invoked during execution of the check_owner( ) procedure.
CREATE PROCEDURE check_owner ( owner lvarchar )
EXTERNAL NAME "/usr/lib/ext_lib/genlib.so(unix_owner)"
LANGUAGE C
END PROCEDURE

Java This example registers a user-defined procedure named showusers( ) that is
written in the Java language:
CREATE PROCEDURE showusers()
WITH (CLASS = "jvp") EXTERNAL NAME 'admin_jar:admin.showusers'
LANGUAGE JAVA

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. ♦

2-188 IBM Informix Guide to SQL: Syntax


CREATE PROCEDURE

Ownership of Created Database Objects


The user who creates an owner-privileged UDR owns any database objects
that the UDR creates when the UDR is executed, unless another owner is
specified for the created database object. In other words, the UDR owner, not
the user who executes the UDR, is the owner of any database objects created
by the UDR unless another owner is specified in the statement that creates the
database object.

In the case of a DBA-privileged UDR, however, the user who executes the
UDR, not the UDR owner, owns any database objects that the UDR created
unless another owner is specified for the database object within the UDR.

For examples, see “Ownership of Created Database Objects” on page 2-140 in


the description of the CREATE FUNCTION statement.

XPS Using sysbdopen( ) and sysdbclose( ) Stored Procedures


To set the initial environment for one or more sessions, create and install the
sysdbopen( ) SPL procedure. The main function of these procedures is to
initialize a session’s properties without requiring the properties to be
explicitly defined within the session. These procedures are executed
whenever users connect to a database where the procedures are installed.
Such procedures are useful if users access databases through client applica-
tions that cannot modify application code or set environment options or
environment variables.

You can also create the sysdbclose( ) SPL procedure which is executed when
a user disconnects from the database.

You can include valid SQL or SPL language statements that are appropriate
when a database is opened or closed. See the following sections for restric-
tions on SQL and SPL statements within SPL routines:
■ “Subset of SPL Statements Valid in the Statement Block” on
page 4-276
■ “SQL Statements Not Valid in an SPL Statement Block” on
page 4-277
■ “Restrictions on SPL Routines in Data-Manipulation Statements” on
page 4-279

SQL Statements 2-189


CREATE PROCEDURE

Important: The sysdbopen() and sysdbclose() procedures are exceptions to the


scope rule for stored procedures. In ordinary user-created stored procedures, the scope
of variables and statements is local. SET PDQPRIORITY and SET ENVIRONMENT
statement settings do not persist when these SPL procedures exit. However, in
sysdbopen() and sysdbclose() procedures, statements that set the session
environment remain in effect until another statement resets the options.

For example, you might create the following procedure, which sets the
isolation level to Dirty Read and turns on the IMPLICIT_PDQ environment
option, to be executed when any user connect to the database:
create procedure public.sysdbopen()
set role engineer;
end procedure

Procedures do not accept arguments or return values. The sysdbopen() and


sysdbclose() procedures must be executed from the connection coserver and
must be installed in each database where you want to execute them. You can
create the following four SPL procedures.

Procedure Name Description

user.sysdbopen() This procedure is executed when the specified user opens the
database as the current database.

public.sysdbopen() If no user.sysdbopen() procedure applies, this procedure is


executed when any user opens the database as the current
database. To avoid duplicating SPL code, you can call this
procedure from a user-specific procedure.

user.sysdbclose() This procedure is executed when the specified user closes the
database, disconnects from the database server, or the user
session ends. If the sysdbclose() procedure did not exist
when a session opened the database, however, it is not
executed when the session closes the database.

public.sysdbclose() If no user.sysdbopen() procedure applies, this procedure is


executed when the specified user closes the database, discon-
nects from the database server, or the user session ends.
If the sysdbclose() procedure did not exist when a session
opened the database, however, it is not executed when the
session closes the database.

See also the section “Transactions in SPL Routines” on page 4-280.

2-190 IBM Informix Guide to SQL: Syntax


CREATE PROCEDURE

Make sure that you set permissions appropriately to allow intended users to
execute the SPL procedure statements. For example, if the SPL procedure
executes a command that writes output to a local directory, permissions must
be set to allow users to write to this directory. If you want the procedure to
continue if permission failures occur, include an ON EXCEPTION error
handler for this condition.

See also the section “Support for Roles and User Identity” on page 4-280.

Warning: If a sysdbopen() procedure fails, the database cannot be opened. If a


sysdbclose() procedure fails, the failure is ignored. While you are writing and
debugging a sysdbopen() procedure, set the DEBUG environment variable to
NODBPROC before you connect to the database. When DEBUG is set to NODBPROC
the procedure is not executed, and failures cannot prevent the database from opening.
Failures from these procedures can be generated by the system or simulated by the
procedures with the SPL statement RAISE EXCEPTION. For more information, refer
to “RAISE EXCEPTION” on page 3-43.

Only a user with DBA privileges can install these procedures. For security
reasons, non-DBAs cannot prevent execution of these procedures. For some
applications, however, such as ad hoc query applications, users can execute
commands and SQL statements that subsequently change the environment.
For general information about how to write and install SPL procedures, refer
to the chapter about SPL routines in IBM Informix Guide to SQL: Tutorial.

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, PREPARE, REVOKE,
and UPDATE STATISTICS
For a discussion of how to create and use SPL routines, see the IBM Informix
Guide to SQL: Tutorial. For a discussion of external routines, see IBM Informix
User-Defined Routines and Data Types Developer’s Guide.

For information about how to create C UDRs, see the IBM Informix DataBlade
API Programmer’s Guide. For more information on the NODEFDAC
environment variable and the related system catalog tables (sysprocedures,
sysprocplan, sysprocbody and sysprocauth), see the IBM Informix Guide to
SQL: Reference.

SQL Statements 2-191


CREATE PROCEDURE FROM

+ CREATE PROCEDURE FROM


E/C
Use the CREATE PROCEDURE FROM statement to access a user-defined
procedure. The actual text of the CREATE PROCEDURE statement resides in a
separate file. Use this statement with ESQL/C.

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

CREATE PROCEDURE FROM ' file '


file_var

Element Purpose Restrictions Syntax


file Pathname and filename of file that Must exist, and can contain only one Must conform to
contains full text of a CREATE CREATE PROCEDURE statement. the rules of the
PROCEDURE statement. Default Se also “Default Directory That operating system.
pathname is the current directory. Holds the File” on page 2-193.
file_var Name of a program variable that Character data type; contents have Language specific
contains file specification same restrictions as file.

Usage
You cannot create a user-defined procedure directly in an ESQL/C program.
That is, the program cannot contain the CREATE PROCEDURE statement.

To use a user-defined procedure in an ESQL/C program


1. Create a source file with the CREATE PROCEDURE statement.
2. Use the CREATE PROCEDURE FROM statement to send the contents of
this source file to the database server for execution.
The file can contain only one CREATE PROCEDURE statement.

2-192 IBM Informix Guide to SQL: Syntax


CREATE PROCEDURE FROM

For example, suppose that the following CREATE PROCEDURE statement is in


a separate file, called raise_pr.sql:
CREATE PROCEDURE raise_prices( per_cent int )
UPDATE stock -- increase by percentage;
SET unit_price = unit_price +
( unit_price * (per_cent / 100) );
END PROCEDURE;

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. ♦
IDS Procedures use the collating order that was in effect when they were created.
See SET COLLATION for information about using non-default collation ♦

Default Directory That Holds the File


The filename (and any pathname) that you specify is relative.

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. ♦

Windows On Windows, 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. To improve readability of the
code, however, it is recommended that you match these two statements.

Related Information
Related statements: CREATE PROCEDURE, CREATE FUNCTION FROM, and
CREATE ROUTINE FROM

SQL Statements 2-193


CREATE ROLE

+ CREATE ROLE
Use the CREATE ROLE statement to create a new role.

Syntax Usage

CREATE ROLE role

' role '

Element Purpose Restrictions Syntax


role Name declared here for a Must be unique among role names in the database. Identifier,
role that the DBA created The maximum number of bytes in role is 32. p. 4-189

The database administrator (DBA) can use 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.

The role name is an authorization identifier. It cannot be a user name that is


known to the database server or to the operating system of the database
server. The role name cannot already be listed in the username column of the
sysusers system catalog table, nor in the grantor or grantee columns of the
systabauth, syscolauth, sysprocauth, and sysroleauth system catalog tables.

IDS Also, the role name cannot already be listed in the grantor or grantee
columns of the sysfragauth system catalog table. ♦

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.

2-194 IBM Informix Guide to SQL: Syntax


CREATE ROLE

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.

To create the role engineer, enter the following statement:


CREATE ROLE engineer

Related Information
Related statements: DROP ROLE, GRANT, REVOKE, and SET ROLE

For a discussion on how to use roles, see the IBM Informix Database Design and
Implementation Guide.

SQL Statements 2-195


CREATE ROUTINE FROM

+ CREATE ROUTINE FROM


IDS
Use the CREATE ROUTINE FROM statement to access a user-defined routine
(UDR). The actual text of the CREATE FUNCTION or CREATE PROCEDURE
statement resides in a separate file.

Syntax

CREATE ROUTINE FROM ' file '


file_var

Element Purpose Restrictions Syntax


file Pathname and filename of file that contains Must exist and can contain only one Operating-
the text of a CREATE PROCEDURE or CREATE FUNCTION or CREATE system
CREATE FUNCTION statement PROCEDURE statement. dependent
Default path is current directory.
file_var Name of a program variable that contains file Must be a character data type; Language
specification contents must satisfy file restrictions. specific

Usage
An IBM Informix ESQL/C program cannot directly define a UDR. That is, it
cannot contain the CREATE FUNCTION or CREATE PROCEDURE statement.

To use a UDR in an ESQL/C program

1. Create a source file with the CREATE FUNCTION or CREATE


PROCEDURE statement.
2. Use the CREATE ROUTINE FROM statement to send the contents of
this source file to the database server for execution.
The file that you specify can contain only one CREATE FUNCTION or
CREATE PROCEDURE statement.

The filename that you provide is relative. If you provide no pathname, the
client application looks for the file in the current directory.

2-196 IBM Informix Guide to SQL: Syntax


CREATE ROUTINE FROM

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. If you do know if the UDR is a function or a procedure, it is recom-
mended that you use the matching statement to access the source file:

■ To access user-defined functions, use CREATE FUNCTION FROM.


■ To access user-defined procedures, use CREATE PROCEDURE FROM.

Use of the matching statements improves the readability of the code.


IDS Routines use the collating order that was in effect when they were created.
See SET COLLATION for information about using non-default collation ♦

Related Information
Related statements: CREATE FUNCTION, CREATE FUNCTION FROM, CREATE
PROCEDURE, and CREATE PROCEDURE FROM

SQL Statements 2-197


CREATE ROW TYPE

+ CREATE ROW TYPE


IDS
Use the CREATE ROW TYPE statement to create a named row type.

Syntax
,
row_type ( Field Definition )
CREATE ROW TYPE p. 2-201
UNDER supertype

Element Purpose Restrictions Syntax


row_type Name that you declare here for a See “Procedure for Creating a Subtype” on Identifier,
new named row data type page 2-200. p. 4-189
supertype Name of the supertype within Must already exist as a named row type. Data type,
an inheritance hierarchy p. 4-49

Usage
The CREATE ROW TYPE statement creates a named ROW data type. You can
assign a named ROW type to a table or view to create a typed table or typed
view. You can also define a column as a named ROW type. Although you can
assign a ROW type to a table to define the schema 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, defined using the Field Definition syntax.
A named ROW type is valid in most contexts where you can specify a data
type. Named ROW types are strongly typed. No two named ROW types are
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 information, see “Row Data Types” on page 4-62.

Privileges on named ROW type columns are the same as privileges on any
column. For more information, see “Table-Level Privileges” on page 2-463.
(To see what privileges you have on a column, check the syscolauth system
catalog table, which is described in the IBM Informix Guide to SQL: Reference.)

2-198 IBM Informix Guide to SQL: Syntax


CREATE ROW TYPE

Privileges on Named Row Data Types


This table indicates which privileges you must have to create a ROW type.

Task Privileges Required

Create a named ROW type Resource privilege on the database

Create a named ROW type as a subtype Under privilege on the supertype, as


under a supertype well as the Resource privilege

For information about Resource and Under privileges, and the ALL keyword
in the context of privileges, see the GRANT statement.

To find out what privileges exist on a ROW type, check the sysxtdtypes
system catalog table for the owner name and the sysxtdtypeauth system
catalog table for privileges that might have been granted.

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
Privileges” on page 2-463.

To find out what privileges you have on a given table, check the systabauth
system catalog table. For more information on system catalog tables, see the
IBM Informix Guide to SQL: Reference.

Inheritance and Named ROW Types


A named ROW type can belong to an inheritance hierarchy, as either a
subtype or a supertype. Use the UNDER clause in the CREATE ROW TYPE
statement to create a named ROW type as a subtype.

The supertype must also be a named ROW type. If you create a named ROW
type under an existing supertype, then the new type name row_type becomes
the name of the subtype.

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 for its subtype.

SQL Statements 2-199


CREATE ROW TYPE

For example, consider 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 (its supertype). To create the fields of a
named ROW type, use the field definition clause, as described in “Field
Definition” on page 2-201. 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; but 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.

Thus, 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
discussion of type inheritance, refer to the IBM Informix Guide to SQL: Tutorial.

Procedure for Creating a Subtype


Before you create a named ROW type as a subtype in an inheritance hierarchy,
check the following information:

■ Verify that you are authorized to create new data types. You must
have the Resource privilege on the database. You can find this infor-
mation in the sysusers system catalog table.

2-200 IBM Informix Guide to SQL: Syntax


CREATE ROW TYPE

■ Verify that the supertype exists. You can find this information in the
sysxtdtypes system catalog table.
■ Verify that you are authorized to create subtypes to that supertype.
You must have the Under privilege on the supertype. You can find
this information in the sysusers system catalog table.
■ Verify that the name that you assign to the named ROW type is
unique within the database. In an ANSI-compliant database, the
owner.type combination must be unique within the database. In a
database that is not ANSI-compliant, the name must be unique
among data type names in the database. To verify whether the name
you want to assign to a new data type is unique within the schema,
check the sysxtdtypes system catalog table. The name must not be
the name of an existing data type.
■ If you are defining fields for the ROW type, check that no duplicate
field names exist in both new and inherited fields.
Important: When you create a subtype, do not redefine fields that it inherited for its
supertype. If you attempt to redefine these fields, the database server returns an error.

You cannot apply constraints to named ROW types, but you can specify
constraints when you create or alter a table that uses named ROW types.

Field Definition
Use the field definition portion of CREATE ROW TYPE to define a new field in
a named ROW type.

Field Definition Back to CREATE ROW TYPE

field data_type

NOT NULL

Element Purpose Restrictions Syntax


data_type Data type of the field See “Restrictions on Serial and Simple-Large- Identifier,
Object Data Types” on page 2-202. p. 4-189
field Name of a field in data_type Must be unique among field names of this row Identifier,
type and of its supertype. p. 4-189

SQL Statements 2-201


CREATE ROW TYPE

The NOT NULL constraint on named ROW type field applies to corresponding
columns when the named ROW type is used to create a typed table.

Restrictions on Serial and Simple-Large-Object Data Types


Serial and simple-large-object data types cannot be nested within a table.
Therefore, if a ROW type contains a BYTE, TEXT, SERIAL, or SERIAL8 field, you
cannot use the ROW type to define a column in a table that is not based on a
ROW type. For example, the following code example produces an error:

CREATE ROW TYPE serialtype (s serial, s8 serial8);


CREATE TABLE tab1 (col1 serialtype) --INVALID CODE

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 or SERIAL8 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.

Serial fields in ROW types havte performance implications across a table


hierarchy. To 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

For a discussion of named ROW types, see the IBM Informix Database Design
and Implementation Guide and the IBM Informix Guide to SQL: Reference.

2-202 IBM Informix Guide to SQL: Syntax


CREATE SCHEMA

DB CREATE SCHEMA
SQLE
Use the CREATE SCHEMA statement to issue a block of data definition
language (DDL) and GRANT statements as a logical unit. Use this statement
with DB-Access.

Syntax

CREATE TABLE Statement


CREATE SCHEMA AUTHORIZATION user p. 2-214

CREATE VIEW Statement


p. 2-310
GRANT Statement
p. 2-459
OP CREATE OPTICAL CLUSTER Statement
+ See the “IBM Informix Optical Subsystem
CREATE INDEX Statement
p. 2-144
CREATE SYNONYM Statement
p. 2-210
CREATE TRIGGER Statement
IDS p. 2-269
CREATE ROW TYPE Statement
p. 2-198
CREATE OPAQUE TYPE Statement
p. 2-169
CREATE DISTINCT TYPE Statement
p. 2-115
CREATE CAST Statement
p. 2-108

Element Purpose Restrictions Syntax


user User who owns the If you have DBA privileges, you can specify the name of Identifier,
database objects that this any user. Otherwise, you must have the Resource p. 4-189
statement creates privilege and you must specify your own user name.

SQL Statements 2-203


CREATE SCHEMA

Usage
The CREATE SCHEMA statement allows the DBA to specify an owner for all
database objects that the CREATE SCHEMA statement creates. You cannot
issue CREATE SCHEMA until you create the database that stores the objects.

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, 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);

Creating Database Objects Within CREATE SCHEMA


All database objects that a CREATE SCHEMA statement creates are owned by
user, even if you do not explicitly name each database object. If you are the
DBA, you can create database objects for another user. If you are not the DBA,
specifying an owner other than yourself results in an error message.

You can only grant privileges with the CREATE SCHEMA statement; you
cannot revoke or drop privileges.

If you create a database object or use the GRANT statement outside a CREATE
SCHEMA statement, you receive warnings if you use the -ansi flag or set
DBANSIWARN.

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 IBM Informix Database
Design and Implementation Guide.

2-204 IBM Informix Guide to SQL: Syntax


CREATE SCRATCH TABLE

XPS CREATE SCRATCH TABLE


Use the CREATE SCRATCH TABLE statement to create a non-logging
temporary table in the current Extended Parallel Server database.

Syntax

Scratch Table
CREATE SCRATCH TABLE table Definition

Scratch Table ,
Definition ,
Column Multiple-Column
( Definition , Constraint Format )
p. 2-216 p. 2-264
Scratch Table
Options

Scratch Table Options

+ IN dbslice LOCK MODE PAGE


USING
Access-
dbspace ROW Method
Clause
FRAGMENT BY Clause TABLE p. 2-252
p. 2-238

Element Purpose Restrictions Syntax


dbslice Name of dbslice to store table Must already exist. Identifier, p. 4-189
dbspace Name of dbspace to store table. Default is the Must already exist. Identifier, p. 4-189
dbspace that stores the current database.
table Name that you declare here for a nonlogging Must be unique in the Database Object
temporary table current session. Name, p. 4-46

Usage
CREATE SCRATCH TABLE is a special case of the CREATE Temporary TABLE
statement. See “CREATE Temporary TABLE” on page 2-261.

SQL Statements 2-205


CREATE SEQUENCE

+ CREATE SEQUENCE
IDS
Use the CREATE SEQUENCE statement to create a new sequence. A sequence is
a database object from which multiple users can generate unique integers.

Syntax

CREATE SEQUENCE sequence

owner . 1 NOCYCLE

1 INCREMENT BY step CYCLE

1 START WITH origin 1 CACHE size

1 MAXVALUE max NOCACHE

NOMAXVALUE 1 NOORDER

1 MINVALUE min ORDER

NOMINVALUE

Element Purpose Restrictions Syntax


max Upper limit of values Must be an integer > origin Literal number, p. 4-216
min Lower limit of values Must be an integer less than origin Literal number, p. 4-216
origin First number in the sequence Must be an integer in INT8 range Literal number, p. 4-216
owner Owner of sequence Must be aauthorization identifier Owner Name, p. 4-234
sequence Name that you declare here for the Must be unique among sequence, Identifier, p. 4-189
new sequence table, view, and synonym names
size Number of values that are preallo- Integer > 1, but < cardinality of Literal number, p. 4-216
cated in memory a cycle (= |(max - min)/step|)
step Interval between successive values Nonzero integer in INT range Literal number, p. 4-216

Usage
A sequence (sometimes called a sequence generator) returns a monotonically
ascending or descending series of unique integers, one at a time. The CREATE
SEQUENCE statement defines a new sequence and declares its identifier.

2-206 IBM Informix Guide to SQL: Syntax


CREATE SEQUENCE

Authorized users of a sequence can request a new value by including the


sequence.NEXTVAL expression in SQL statements. The sequence.CURRVAL
expression returns the current value of the specified sequence.

Generated values logically resemble the SERIAL8 data type, but are unique
within the sequence. Because the database server generates the values,
sequences support a much higher level of concurrency than a serial column
can. The values are independent of transactions; a generated value cannot be
rolled back, even if the transaction in which it was generated fails.

You can use a sequence to generate primary key values automatically, using
one sequence for many tables, or each table can have its own sequence.
CREATE SEQUENCE can specify the following characteristics of a sequence:

■ Initial value
■ Size and sign of the increment between values.
■ Maximum and minimum values
■ Whether the sequence recycles values after reaching its limit
■ How many values are preallocated in memory for rapid access

A database can support multiple sequences concurrently, but the name of a


sequence must be unique within the current database among the names of
tables, temporary tables, views, synonyms, and sequences.

ANSI In an ANSI-compliant database, the owner.sequence combination must be


unique among tables, temporary tables, views, synonyms, and sequences. ♦

An error occurs if you include contradictory options, such as specifying both


the MINVALUE and NOMINVALUE options, or both CACHE and NOCACHE.

INCREMENT BY Option
Use the INCREMENT BY option to specify the interval between successive
numbers in the sequence. The interval, or step value, can be a positive whole
number (for an ascending sequence) or a negative whole number (for a
descending sequence) in the INT8 range. The BY keyword is optional.

If you do not specify any step value, the default interval between successive
generated values is 1, and the sequence is an ascending sequence.

SQL Statements 2-207


CREATE SEQUENCE

START WITH Option


Use the START WITH option to specify the first number of the sequence. This
origin value must be an integer within the INT8 range that is greater than or
equal to the min value (for an ascending sequence) or that is less than or equal
to the max value (for a descending sequence), if min or max is specified in the
CREATE SEQUENCE statement. The WITH keyword is optional.

If you do not specify an origin value, the default initial value is min for an
ascending sequence or max for a descending sequence. (The “MAXVALUE or
NOMAXVALUE Option” and “MINVALUE or NOMINVALUE Option”
sections that follow describe the max and min specifications respectively.)

MAXVALUE or NOMAXVALUE Option


Use the MAXVALUE option to specify the upper limit of values in a sequence.
The maximum value, or max, must be an integer in the INT8 range that is
greater than the value of the origin.

If you do not specify a max value, the default is NOMAXVALUE. This default
setting supports values that are less than or equal to 2e64 for ascending
sequences, or less than or equal to -1 for descending sequences.

MINVALUE or NOMINVALUE Option


Use the MINVALUE option to specify the lower limit of values in a sequence.
The minimum value, or min, must be an integer in the INT8 range that is less
than the value of the origin.

If you do not specify a min value, the default is NOMINVALUE. This default
setting supports values that are greater than or equal to 1 for ascending
sequences, or greater than or equal to -(2e64) for descending sequences.

CYCLE or NOCYCLE Option


Use the CYCLE option to continue generating sequence values after the
sequence reaches the maximum (ascending) or minimum (descending) limit.
After an ascending sequence reaches the max value, it generates the min value
for the next sequence value. After a descending sequence reaches the min
value, it generates the max value for the next sequence value.

2-208 IBM Informix Guide to SQL: Syntax


CREATE SEQUENCE

The default is NOCYCLE. At this default setting, the sequence cannot generate
more values after reaching the declared limit. Once the sequence reaches the
limit, the next reference to sequence.NEXTVAL returns an error.

CACHE or NOCACHE Option


Use the CACHE option to specify the number of sequence values that are
preallocated in memory for rapid access. This feature can enhance the perfor-
mance of a heavily used sequence. The cache size must be a positive whole
number in the INT range. If you specify the CYCLE option, then size must be
less than the number of values in a cycle (or less than |(max - min)/step|).
The minimum is 2 preallocated values. The default is 20 preallocated values.
The NOCACHE keyword specifies that no generated values (that is, zero) are
preallocated in memory for this sequence object.

The configuration parameter SEQ_CACHE_SIZE specifies the maximum


number of sequence objects that can have preallocated values in the sequence
cache. If this configuration parameter is not set, then by default no more than
10 different sequence objects can be defined with the CACHE option.

ORDER or NOORDER Option


These keywords have no effect on the behavior of the sequence. The sequence
always issues values to users in the order of their requests, as if the ORDER
keyword were always specified. The ORDER and NOORDER keywords are
accepted by the CREATE SEQUENCE statement for compatibility with imple-
mentations of sequence objects in other dialects of SQL.

Related Information
Related statements: ALTER SEQUENCE, DROP SEQUENCE, RENAME
SEQUENCE, CREATE SYNONYM, DROP SYNONYM, GRANT, REVOKE, INSERT,
UPDATE, and SELECT

For information about the syssequences system catalog table in which


sequence objects are registered, see the IBM Informix Guide to SQL: Reference.

For information about initializing a sequence and generating or reading


values from a sequence, see “NEXTVAL and CURRVAL Operators” on
page 4-102.

SQL Statements 2-209


CREATE SYNONYM

+
CREATE SYNONYM
Use the CREATE SYNONYM statement to declare and register an alternative
name for an existing table, view, or sequence object.

Syntax
CREATE SYNONYM synonym FOR table

PUBLIC IDS view

PRIVATE sequence

Element Purpose Restrictions Syntax


sequence Name of a local sequence Must exist in current database Identifier, p. 4-189
table, Name of table or view for which Must exist in current database, or in a Database Object
view synonym is being created database specified in a qualifier Name, p. 4-46
synonym Synonym declared here for the Must be unique among table object Database Object
name of a table, view, or sequence names; see also Usage notes. Name, p. 4-46

Usage
Users have the same privileges for a synonym that they have for the database
object that the synonym references. The syssynonyms, syssyntable, and
systables system catalog tables maintain information about synonyms.

You cannot create a synonym for a synonym in the same database.

The identifier of the synonym must be unique among the names of tables,
temporary tables, views, and sequence objects in the same database. (See,
however, the section “Synonyms with the Same Name” on page 2-212.)

Once a synonym is created, it persists until the owner executes the DROP
SYNONYM statement. (This persistence distinguishes a synonym from an
alias that you can declare in the FROM clause of a SELECT statement; the alias
is in scope only during execution of that SELECT statement.) If a synonym
refers to a table, view, or sequence in the same database, the synonym is
automatically dropped if the referenced table, view, or sequence is dropped.

2-210 IBM Informix Guide to SQL: Syntax


CREATE SYNONYM

Synonyms for Remote and External Tables and Views


A synonym can be created for any table or view in any database on your
database server. This example declares a synonym for a table outside your
current database, in the payables database of your current database server.
CREATE SYNONYM mysum FOR payables:jean.summary

You can also create a synonym for a table or view that exists in a database of
a database server that is not your current database server. Both database
servers must be online when you create the synonym. In a network, the
remote database server verifies that the table or view referenced by the
synonym exists when you create the synonym. The next example reates a
synonym for a table supported by a remote database server:
CREATE SYNONYM mysum FOR payables@phoenix:jean.summary

The identifier mysum now refers to the table jean.summary, which is in the
payables database on the phoenix database server. 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 You cannot create synonyms, however, for these external objects:

■ Typed tables (including any table that is part of a table hierarchy)


■ Tables or views that contain any extended data types.
■ Sequence objects outside the local database ♦

PUBLIC and PRIVATE Synonyms


If you use the PUBLIC keyword (or no keyword at all), anyone who has access
to the database can use your synonym. If the database is not ANSI-compliant,
a user does not need to know the name of the owner of a public synonym.
Any synonym in a database that is not ANSI compliant and was created in an
Informix database server earlier than Version 5.0 is a public synonym.

ANSI In an ANSI-compliant database, all synonyms are private. If you use the
PUBLIC or PRIVATE keywords, the databasde server issues a syntax error. ♦

If you use the PRIVATE keyword to declare a synonym in a database that is


not ANSI-compliant, the unqualified synonym can be used by its owner.
Other users must qualify the synonym with the name of the owner.

SQL Statements 2-211


CREATE SYNONYM

Synonyms with the Same Name


ANSI In an ANSI-compliant database, the owner.synonym combination must be
unique among all synonyms, tables, views. and sequences . You must specify
owner when you refer to a synonym that you do not own, as in this example:
CREATE SYNONYM emp FOR accting.employee ♦
In a database that is not ANSI-compliant, no two public synonyms can have
the same identifier, and the identifier of a synonym must also be unique
among the names of tables, views, and sequences in the same database.

The owner.synonym combination of a private synonym must be unique


among all the synonyms in the database. That is, more than one private
synonym with the same name can exist in the same database, but a different
user must own each of these synonyms. The same user cannot create both a
private and a public synonym that have 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!!!

A private synonym can be declared with the same name as a public synonym
only if the two synonyms have different owners. If you own a private
synonym, and a public synonym exists with the same name, the database
server resolves the unqualified name as the private synonym. (In this case,
you must specify owner.synonym to reference the public synonym.) If you use
DROP SYNONYM with the unqualified synonym identifier when your private
synonym and the public synonym of another user both have the same
identifier, only your private synonym is dropped. If you repeat the same
DROP SYNONYM statement, the database server drops the public synonym.

Chaining Synonyms
If you create a synonym for a table or view that is not in the current database,
and this table or view is dropped, the synonym stays in place. You can create
a new synonym for the dropped table or view with the name of the dropped
table or view as the synonym, which points to another external or remote
table or view. (Synonyms for external sequence objects are not supported.)

In this way, you can move a table or view to a new location and chain
synonyms together so that the original synonyms remain valid. (You can
chain up to 16 synonyms in this manner.)

2-212 IBM Informix Guide to SQL: Syntax


CREATE SYNONYM

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):

1. In the stores_demo database on the database server that is called


training, issue the following statement:
CREATE TABLE customer (lname CHAR(15)...)
2. On the database server called accntg, issue the following statement:
CREATE SYNONYM cust FOR stores_demo@training:customer
3. On the database server called zoo, issue the following statement:
CREATE TABLE customer (lname CHAR(15)...)
4. On the database server called training, issue the following
statement:
DROP TABLE customer
CREATE SYNONYM customer FOR stores_demo@zoo:customer

The synonym cust on the accntg database server now points to the customer
table on the zoo database server.

The following steps show an example of chaining two synonyms together


and changing the table to which a synonym points:

1. On the database server called training, issue the following


statement:
CREATE TABLE customer (lname CHAR(15)...)
2. On the database server called accntg, issue the following statement:
CREATE SYNONYM cust FOR stores_demo@training:customer
3. On the database server called training, issue the following
statement:
DROP TABLE customer
CREATE TABLE customer (lastname CHAR(20)...)

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

For a discussion of concepts related to synonyms, see the IBM Informix


Database Design and Implementation Guide.

SQL Statements 2-213


CREATE TABLE

CREATE TABLE
Use the CREATE TABLE statement to create a new table in the current
database, to place data-integrity constraints on columns, to designate where
the table should be stored, to indicate the size of its initial and subsequent
extents, and to specify how to lock the new table.

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-261.

Syntax

CREATE STANDARD TABLE table Table


Definition
RAW STATIC

XPS OPERATIONAL

Table
Definition
, ,

( Column Definition , Multiple-Column ) Options


p. 2-216 Constraint Format p. 2-235
+ p. 2-231
IDS
OF TYPE Clause
p. 2-255

Element Purpose Restrictions Syntax


table Name that you declare Must be unique among names of tables, synonyms, Database Object
here for the new table views, and sequences within the current database Name, p. 4-46

Usage
When you create a new table, every column must have a data type associated
with it. The table name must be unique among all the names of tables, views,
sequences, and synonyms within the same database, but the names of
columns need only be unique among the column names of the same table.

2-214 IBM Informix Guide to SQL: Syntax


CREATE TABLE

ANSI In an ANSI-compliant database, the combination owner.table must be unique


within the database. ♦

DB In DB-Access, using the CREATE TABLE statement outside the CREATE


SCHEMA statement generates warnings if you use the -ansi flag or set
DBANSIWARN. ♦

E/C In ESQL/C, using the CREATE TABLE statement generates warnings if you use
the -ansi flag or set DBANSIWARN. ♦

For information about the DBANSIWARN environment variable, refer to the


IBM Informix Guide to SQL: Reference.

Logging Options
Use the Logging Type options to specify characteristics that can improve
performance in various bulk operations on the table. Other than the default
option (STANDARD) that is used for OLTP databases, these logging options
are used primarily to improve performance in data warehousing databases.

A table can have either of the following logging characteristics.

Logging Type Description

STANDARD Logging table that allows rollback, recovery, and restoration from
archives. This type is the default. Use this type of table for all the
recovery and constraints functionality that OLTP databases require.

RAW Nonlogging table that cannot have indexes or referential constraints


but can be updated. Use this type of table for quickly loading data. .

XPS By using raw tables with Extended Parallel Server, you can take advantage of
light appends and avoid the overhead of logging, checking constraints, and
building indexes. ♦

Warning: Use raw tables for fast loading of data, but set the logging type to
STANDARD and perform a level-0 backup before you use the table in a transaction or
modify the data within the table. If you must use a raw table within a transaction,
either set the isolation level to Repeatable Read or lock the table in exclusive mode to
prevent concurrency problems.

SQL Statements 2-215


CREATE TABLE

XPS Extended Parallel Server supports two additional logging type options.

Option Effect

OPERATIONAL Logging table that uses light appends; it cannot be restored from
archive. Use this type on tables that are refreshed frequently,
because light appends allow the quick addition of many rows.

STATIC Nonlogging table that can contain index and referential


constraints but cannot be updated. Use this type for read-only
operations, because no logging or locking overhead occurs. ♦

For more information on these logging types of tables, refer to your


Administrator’s Guide.

Column Definition
Use the column definition portion of CREATE TABLE to list the name, data
type, default values, and constraints of a single column.

Column Back to CREATE TABLE


Definition p. 2-214

column Data Type


p. 4-49
DEFAULT Single-Column
Clause Constraint Format
p. 2-217 p. 2-220

Element Purpose Restrictions Syntax


column Name of a column in the table Must be unique in this table. Identifier, p. 4-189

Because of the maximum row size limit of 32,767 bytes, no more than 195
columns in the table can be of the data types BYTE, TEXT, ROW, LVARCHAR,
NVARCHAR, VARCHAR, and varying-length UDTs. Similarly, no more than
97 columns can be of COLLECTION data types (SET, LIST, and MULTISET).

As with any SQL identifier, syntactic ambiguities can occur if the column
name is a keyword. For information on reserved words for Dynamic Server,
see Appendix A, “Reserved Words for IBM Informix Dynamic Server.”

2-216 IBM Informix Guide to SQL: Syntax


CREATE TABLE

For more information on reserved words for Extended Parallel Server, see
Appendix B, “Reserved Words for IBM Informix Extended Parallel Server.”
For more information on the ambiguities that can occur, see “Using
Keywords as Column Names” on page 4-195.

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 for the database server
to insert into a column when no explicit value for the column is specified.

DEFAULT Back to Column Definition


Clause p. 2-216

DEFAULT NULL

literal CURRENT DATETIME


Field Qualifier
p. 4-65
USER
TODAY
+
SITENAME

DBSERVERNAME

Element Purpose Restrictions Syntax


literal String of alphabetic or Must be an appropriate data type for the column. See Expression,
numeric characters “Using a Literal as a Default Value” on page 2-218. p. 4-67

You cannot specify default values for SERIAL or SERIAL8 columns.

Using NULL as a Default Value


If you specify no default value for a column, the default is NULL unless you
place a NOT NULL constraint on the column. In this case, no default exists.

If you specify NULL as the default value for a column, you cannot specify a
NOT NULL constraint as part of the column definition. (For details of NOT
NULL constraints, see“Using the NOT NULL Constraint” on page 2-221.)

SQL Statements 2-217


CREATE TABLE

NULL is not a valid 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 valid default value.

IDS If the column is BLOB or CLOB data type, NULL is the only valid default
value. ♦

Using a Literal as a Default Value


You can designate a literal value as a default value. A literal value is a string
of alphabetic or numeric characters. To use a literal value as a default value,
you must adhere to the syntax restrictions in the following table.

For Columns of Data Type Format of Default Value

BOOLEAN Use 't' or 'f' (respectively for


true or false) as a Quoted String,
p. 4-243

CHAR, CHARACTER VARYING, DATE, Quoted String, p. 4-243. See note that
VARCHAR, NCHAR, NVARCHAR follows for DATE.

DATETIME Literal DATETIME, p. 4-212

DECIMAL, MONEY, FLOAT, Literal Number, p. 4-216 (DECIMAL)


SMALLFLOAT

INTEGER, SMALLINT, DECIMAL, Literal Number, p. 4-216 (INTEGER)


MONEY, FLOAT, SMALLFLOAT, INT8

INTERVAL Literal INTERVAL, p. 4-214

Opaque data types (IDS only) Quoted String, p. 4-243 in Single-


Column Constraint format (p. 2-220)

DATE literals must be of the format that the DBDATE (or else GL_DATE)
environment variable specifies. In the default locale, if neither DBDATE nor
GL_DATE is set, DATE literals must be of the mm/dd/yyyy format.

2-218 IBM Informix Guide to SQL: Syntax


CREATE TABLE

Using a Built-in Function as a Default Value


You can specify a built-in function as the default column value. The following
table lists built-in functions that you can specify, the data type requirements,
and the recommended size (in bytes) for their corresponding columns.

Built-In Function Data Type Requirement Recommended Size

CURRENT DATETIME column with Enough bytes to accom-


matching qualifier modate the longest
DATETIME value for
locale

DBSERVERNAME CHAR, VARCHAR, NCHAR, 128 bytes


NVARCHAR, or CHARACTER
VARYING column

SITENAME CHAR, VARCHAR, NCHAR, 128 bytes


NVARCHAR, or CHARACTER
VARYING column

TODAY DATE column Enough bytes to accom-


modate the longest DATE
value for locale

USER CHAR, VARCHAR, NCHAR, 32 bytes


NVARCHAR, or CHARACTER
VARYING column

These column sizes are recommended because, if the column length is too
small to store the default value during INSERT or 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. ♦

For descriptions of these functions, see “Constant Expressions” on page 4-95.

SQL Statements 2-219


CREATE TABLE

The following example creates a table called accounts. In accounts, the


acc_num, acc_type, and acc_descr columns have literal default values. The
acc_id column defaults to the login name of the user.
CREATE TABLE accounts (
acc_num INTEGER DEFAULT 1,
acc_type CHAR(1) DEFAULT 'A',
acc_descr CHAR(20) DEFAULT 'New Account',
acc_id CHAR(32) DEFAULT USER)

Single-Column Constraint Format


Use the Single-Column Constraint format to associate one or more
constraints with a column, in order to perform any of the following tasks:

■ Create one or more data-integrity constraints for a column.


■ Specify a meaningful name for a constraint.
■ Specify the constraint-mode that controls the behavior of a constraint
during INSERT, DELETE, and UPDATE operations.

Single-Column Back to Column Definition


Constraint Format p. 2-216

+ DISTINCT
REFERENCES +
NOT NULL UNIQUE
Clause
+ p. 2-223
PRIMARY KEY
Constraint
Constraint Definition CHECK Clause Definition
p. 2-228 p. 2-227 p. 2-228

The following example creates a standard table with two constraints: num, a
primary-key constraint on the acc_num column; and code, a unique
constraint on the acc_code column:
CREATE TABLE accounts (
acc_num INTEGER PRIMARY KEY CONSTRAINT num,
acc_code INTEGER UNIQUE CONSTRAINT code,
acc_descr CHAR(30))

The constraints used in this example are defined in the following sections.

2-220 IBM Informix Guide to SQL: Syntax


CREATE TABLE

Restrictions on Using the Single-Column Constraint Format


The single-column constraint format cannot specify a constraint that involves
more than one column. Thus, you cannot use the single-column constraint
format to define a composite key. For information on multiple-column
constraints, see “Multiple-Column Constraint Format” on page 2-231.

You cannot place unique, primary-key, or referential constraints on BYTE or


TEXT columns. You can, however, check for NULL or non-NULL values with
a check constraint.

IDS You cannot place unique constraints, primary-key constraints, or referential


constraints on BLOB or CLOB columns. ♦

Using the NOT NULL Constraint


Use the NOT NULL keywords to require that a column receive a value during
insert or update operations. If you place a NOT NULL constraint on a column
(and no default value is specified), you must enter a value into this column
when you insert a row or update that column in a row. If you do not enter a
value, the database server returns an error, because no default value exists.

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))

You cannot specify NULL as the explicit default value for a column and also
specify the NOT NULL constraint.

Using the UNIQUE or DISTINCT Constraints


Use the UNIQUE or DISTINCT keyword to require that a column or set of
columns accepts only unique data values. You cannot insert values that
duplicate the values of some other row into a column that has a unique
constraint. When you create a UNIQUE or DISTINCT constraint, the database
server automatically creates an internal index on the constrained column or
columns. (In this context, the keyword DISTINCT is a synonym for UNIQUE.)

SQL Statements 2-221


CREATE TABLE

You cannot place a unique constraint on a column that already has a primary-
key constraint.

You cannot place a unique constraint on a BYTE or TEXT column.

IDS You cannot place a unique or primary-key constraint on a BLOB or CLOB


column.

Opaque data types support a unique constraint only where a secondary-


access method supports uniqueness for that type. The default secondary-
access method is a generic B-tree, which supports the equal( ) operator
function. Therefore, if the definition of the opaque type includes the equal( )
function, a column of that opaque type can have a unique constraint. ♦

The following example creates a simple table that has a unique constraint on
one of its columns:
CREATE TABLE accounts
(acc_name CHAR(12),
acc_num SERIAL UNIQUE CONSTRAINT acc_num)

For an explanation of the constraint name, refer to “Declaring a Constraint


Name” on page 2-229.

Using the PRIMARY KEY Constraint


A primary key is a column (or a set of columns, when you use the multiple-
column constraint format) that contains a non-NULL, unique value for each
row in a table. When you create a PRIMARY KEY constraint, the database
server automatically creates an internal index on the column or columns that
make up the primary key.

You can designate only one primary key for a table. If you define a single
column as the primary key, then it is unique by definition. You cannot
explicitly give the same column a unique constraint.

IDS You cannot place a unique or primary-key constraint on a BLOB or CLOB


column.

Opaque types support a primary key constraint only where a secondary-


access method supports the uniqueness for that type. The default secondary-
access method is a generic B-tree, which supports the equal() function.
Therefore, if the definition of the opaque type includes the equal() function,
a column of that opaque type can have a primary-key constraint. ♦

2-222 IBM Informix Guide to SQL: Syntax


CREATE TABLE

You cannot place a primary-key constraint on a BYTE or TEXT column.

In the previous two examples, a unique constraint was placed on the column
acc_num. The following example creates this column as the primary key for
the accounts table:
CREATE TABLE accounts
(acc_name CHAR(12),
acc_num SERIAL PRIMARY KEY CONSTRAINT acc_num)

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 Back to Single-Column Constraint Format p. 2-220


Clause Back to Multiple-Column Constraint Format p. 2-231

REFERENCES table
, +
( column ) ON DELETE CASCADE

Element Purpose Restrictions Syntax


column Name of the referenced column See “Restrictions on Referential Identifier, p.4-189
or columns Constraints” on page 2-224.
table Name of the referenced table Must reside in the same database Database Object
as the referencing table. Name, p. 4-46

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(s) can contain NULL and duplicate values, but values in the
referenced column (or set of columns) must be unique.

The relationship between referenced and referencing columns is called a


parent-child relationship, where the parent is the referenced column (primary
key) and the child is the referencing column (foreign key). The referential
constraint establishes this parent-child relationship.

SQL Statements 2-223


CREATE TABLE

When you create a referential constraint, the database server automatically


creates an internal index on the constrained column or columns.

Restrictions on Referential Constraints


You must have the References privilege to create a referential constraint.

When you use the REFERENCES clause, you must observe the following
restrictions:
■ The referenced and referencing tables must be in the same database.
■ The referenced column (or set of columns when you use the
multiple-column constraint format) must have a unique or primary-
key constraint.
■ The data types of the referencing and referenced columns must be
identical.
The only exception is that a referencing column must be an integer
data type if the referenced column is a serial.
■ You cannot place a referential constraint on a BYTE or TEXT column.
■ When you use the single-column constraint format, you can
reference only one column.
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 380 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. ♦

Default Values for the Referenced Column


If the referenced table is different from the referencing table, you do not need
to specify the referenced column; the default column is the primary-key
column (or columns) of the referenced table. If the referenced table is the
same as the referencing table, you must specify the referenced column.

2-224 IBM Informix Guide to SQL: Syntax


CREATE TABLE

Referential Relationships Within a Table


You can establish a referential relationship between two columns of the same
table. In the following example, the emp_num column in the employee table
uniquely identifies every employee through an employee number. The
mgr_num column in that table contains the employee number of the
manager who manages that employee. In this case, mgr_num references
emp_num. Duplicate values appear in the mgr_num column because
managers manage more than one employee.
CREATE TABLE employee
(
emp_num INTEGER PRIMARY KEY,
mgr_num INTEGER REFERENCES employee (emp_num)
)

Locking Implications of Creating a Referential Constraint


When you create a referential constraint, an exclusive lock is placed on the
referenced table. The lock is released when the CREATE TABLE statement is
finished. If you are creating a table in a database with transactions, and you
are using transactions, the lock is released at the end of the transaction.

Example That Uses the Single-Column Constraint Format


The following example uses the single-column constraint format to create a
referential relationship between the sub_accounts and accounts tables. The
ref_num column in the sub_accounts table references the acc_num column
(the primary key) in the accounts table.
CREATE TABLE accounts (
acc_num INTEGER PRIMARY KEY,
acc_type INTEGER,
acc_descr CHAR(20))
CREATE TABLE sub_accounts (
sub_acc INTEGER PRIMARY KEY,
ref_num INTEGER REFERENCES accounts (acc_num),
sub_descr CHAR(20))

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-231.

SQL Statements 2-225


CREATE TABLE

Using the ON DELETE CASCADE Option


Use the ON DELETE CASCADE option to specify whether you want rows
deleted in a child table when corresponding rows are deleted in the parent
table. If you do not specify cascading deletes, the default behavior of the
database server prevents you from deleting data in a table if other tables
reference it.

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, the all_candy table contains the candy_num column as a


primary key. The hard_candy table refers to the candy_num column as a
foreign key. The following CREATE TABLE statement creates the hard_candy
table with the cascading-delete option on the foreign key:
CREATE TABLE all_candy
(candy_num SERIAL PRIMARY KEY,
candy_maker CHAR(25));

CREATE TABLE hard_candy


(candy_num INT,
candy_flavor CHAR(20),
FOREIGN KEY (candy_num) REFERENCES all_candy
ON DELETE CASCADE)

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-346.

2-226 IBM Informix Guide to SQL: Syntax


CREATE TABLE

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 Back to Single-Column Constraint Format p. 2-220


Clause Back to Multiple-Column Constraint Format p. 2-231

( Condition )
CHECK p. 4-24

IDS The condition cannot include a user-defined function or procedure. ♦

During an insert or update, if the check constraint of a row evaluates to false,


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 want to use both a check constraint and a NOT NULL constraint.

Using a Search Condition


You use search conditions to define check constraints. The search condition
cannot contain the following items: user-defined routines, subqueries, aggre-
gates, host variables, or rowids. In addition, the search condition cannot
contain the following built-in functions: CURRENT, USER, SITENAME,
DBSERVERNAME, or TODAY.

Warning: When you specify a date value in a search condition, make sure you specify
4 digits for the year, so that the DBCENTURY environment variable has no effect on
the condition. When you specify a 2-digit year, the DBCENTURY environment
variable can produce unpredictable results if the condition depends on an abbreviated
year value. For more information on the DBCENTURY environment variable, see the
“IBM Informix Guide to SQL: Reference.” More generally, the database server saves
the settings of environment variables from the time of creation of check constraints.
If any of these settings are subsequently changed in a way that can affect the evalu-
ation of a condition in a check constraint, the new settings are disregarded, and the
original environment variable settings are used when the condition is evaluated.

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 column.

SQL Statements 2-227


CREATE TABLE

Restrictions When Using the Single-Column Constraint Format


When you use the single-column constraint format to define a check
constraint, the check constraint cannot depend on values in other columns of
the table. The following example creates the my_accounts table that has two
columns with check constraints, each in the single-column constraint format:
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-231.

Constraint Definition
Use the constraint definition portion of CREATE TABLE for these purposes:

■ To declare a name for the constraint


IDS ■ To set a constraint to disabled, enabled, or filtering mode ♦

Constraint Back to Single-Column Constraint Format p. 2-220


Definition Back to Multiple-Column Constraint Format p. 2-231

IDS
CONSTRAINT constraint
ENABLED

DISABLED

FILTERING WITHOUT ERROR

WITH ERROR

Element Purpose Restrictions Syntax


constraint Name of constraint Must be unique among index names Database Object Name, p. 4-46

2-228 IBM Informix Guide to SQL: Syntax


CREATE TABLE

Declaring a Constraint Name


The database server implements the constraint as an index. Whenever you
use the single- or multiple-column constraint format to place a data
restriction on a column, but without declaring a constraint name, the database
server creates a constraint and adds a row for that constraint in the syscon-
straints system catalog table. The database server also generates an identifier
and adds a row to the sysindexes system catalog table for each new primary-
key, unique, or referential constraint that does not share an index with an
existing constraint. Even if you declare a name for a constraint, the database
server generates the name that appears in the sysindexes table.

If you want, you can specify a meaningful name for the constraint. The name
must be unique among the names of constraints and indexes in the database.

Constraint names appear in error messages having to do with constraint


violations. You can use this name when you use the DROP CONSTRAINT
clause of the ALTER TABLE statement.

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 combination 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. ♦

Constraint Names That the Database Server Generates


If you do not specify a constraint name, the database server generates a
constraint name using the following template:
<constraint_type><tabid>_<constraintid>

In this template, constraint_type is the letter u for unique or primary-key


constraints, r for referential constraints, c for check constraints, and n for NOT
NULL constraints. In the template, tabid and constraintid are values from the
tabid and constrid columns of the systables and sysconstraints system
catalog tables, respectively. For example, the constraint name for a unique
constraint might look like ” u111_14” (with a leading blank space).

SQL Statements 2-229


CREATE TABLE

If the generated name conflicts with an existing identifier, the database server
returns an error, and you must then supply an explicit constraint name.

The generated index name in sysindexes (or sysindices) has this format:
[blankspace]<tabid>_<constraintid>

For example, the index name might be something like “ 111_14 “ (with
quotation marks used here to show the blank space).

IDS Choosing a Constraint-Mode Option


Use the constraint-mode options to control the behavior of constraints in
INSERT, DELETE, and UPDATE operations. These are the options.

Mode Purpose

DISABLED Does not enforce the constraint during INSERT, DELETE, and
UPDATE operations.

ENABLED Enforces the constraint during INSERT, DELETE, and UPDATE


operations. If a target row causes a violation of the constraint, the
statement fails. This mode is the default.

FILTERING Enforces the constraint during INSERT, DELETE, and UPDATE


operations. If a target row causes a violation of the constraint, the
statement continues processing. The database server writes the row
in question to the violations table associated with the target table and
writes diagnostic information to the associated diagnostics table.

If you choose filtering mode, you can specify the WITHOUT ERROR or WITH
ERROR options. The following list explains these options.

Error Option Purpose

WITHOUT ERROR Does not return an integrity-violation error when a filtering-


mode constraint is violated during an insert, delete, or update
operation. This is the default error option.

WITH ERROR Returns an integrity-violation error when a filtering-mode


constraint is violated during an insert, delete, or update
operation

2-230 IBM Informix Guide to SQL: Syntax


CREATE TABLE

To set the constraint mode after the table exists, see “SET Database Object
Mode” on page 2-652. For information about where the database server
stores rows that violate a constraint set to FILTERING, see “START VIOLA-
TIONS TABLE” on page 2-729.

Multiple-Column Constraint Format


Use the multiple-column constraint format to associate one or more columns
with a constraint. This alternative to the single-column constraint format
allows you to associate multiple columns with a constraint.

Multiple-Column Back to CREATE TABLE p. 2-214


Constraint Format , Back to OF TYPE Clause p. 2-255

UNIQUE ( column )
+ DISTINCT +

PRIMARY KEY
, Constraint
REFERENCES Definition
( column ) Clause p. 2-228
FOREIGN KEY p. 2-223
CHECK Clause
p. 2-227

Element Purpose Restrictions Syntax


column Columns on which to place constraint Not BYTE, TEXT, BLOB, nor CLOB Identifier, p.4-189

You can include a maximum of 16 columns in a constraint list. The total


length of all columns cannot exceed 380 bytes.

When you define a unique constraint (by using the UNIQUE or DISTINCT
keyword), a column cannot appear in the constraint list more than once.

Using the multiple-column constraint format, you can perform these tasks:

■ Create data-integrity constraints for a set of one or more columns


■ Specify a mnemonic name for a constraint
■ Specify the constraint-mode option that controls the behavior of a
constraint during insert, delete, and update operations

SQL Statements 2-231


CREATE TABLE

When you use this format, you can create composite primary and foreign
keys, or define check constraints that compare data in different columns.

Restrictions with the Multiple-Column Constraint Format


When you use the multiple-column constraint format, you cannot define any
default values for columns. In addition, you cannot establish a referential
relationship between two columns of the same table.

To define a default value for a column or establish a referential relationship


between two columns of the same table, refer to “Single-Column Constraint
Format” on page 2-220 and “Referential Relationships Within a Table” on
page 2-225 respectively.

Using Large-Object Types in Constraints


You cannot place unique, primary-key, or referential (FOREIGN KEY)
constraints on BYTE or TEXT columns. You can, however, check for NULL or
non-NULL values with a check constraint.

IDS You cannot place unique or primary-key constraints on BLOB or CLOB


columns. ♦

You can find detailed discussions of specific constraints in these sections.

Constraint For more information, see For an example, see

CHECK “CHECK Clause” on “Defining Check Constraints


page 2-227 Across Columns” on page 2-233

DISTINCT “Using the UNIQUE or “Examples of the Multiple-


DISTINCT Constraints” on Column Constraint Format” on
page 2-221 page 2-233

FOREIGN KEY “Using the FOREIGN KEY “Defining Composite Primary


Constraint” on page 2-233 and Foreign Keys” on page 2-234

PRIMARY KEY “Using the PRIMARY KEY “Defining Composite Primary


Constraint” on page 2-222 and Foreign Keys” on page 2-234

UNIQUE “Using the UNIQUE or “Examples of the Multiple-


DISTINCT Constraints” on Column Constraint Format” on
page 2-221 page 2-233

2-232 IBM Informix Guide to SQL: Syntax


CREATE TABLE

Using the FOREIGN KEY Constraint


A foreign key joins and establishes dependencies between tables. That is, it
creates a referential constraint. (For more information on referential
constraints, see the “REFERENCES Clause” on page 2-223.)

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.

You cannot specify BYTE or TEXT columns as foreign keys.

IDS You cannot specify BLOB or CLOB columns as foreign keys. ♦

Examples of the Multiple-Column Constraint Format


The following example creates a standard table, called accounts, with a
unique constraint, called acc_num, using the multiple-column constraint
format. (Nothing in this example, however, would prevent you from using
the single-column constraint format to define this constraint.)
CREATE TABLE accounts
(acc_name CHAR(12),
acc_num SERIAL,
UNIQUE (acc_num) CONSTRAINT acc_num)

For constraint names, see “Declaring a Constraint Name” on page 2-229.

Defining Check Constraints Across Columns


When you use the multiple-column constraint format to define check
constraints, a check constraint can apply to more than one column in the
same table. (You cannot, however, create a check constraint whose condition
uses a value from a column in another table.)

This example compares two columns, acct1 and acct2, in the new table:
CREATE TABLE my_accounts
(
chk_id SERIAL PRIMARY KEY,
acct1 MONEY,
acct2 MONEY,
CHECK (0 < acct1 AND acct1 < 99999),
CHECK (0 < acct2 AND acct2 < 99999),
CHECK (acct1 > acct2)
)

SQL Statements 2-233


CREATE TABLE

In this example, the acct1 column must be greater than the acct2 column, or
the insert or update fails.

Defining Composite Primary and Foreign Keys


When you use the multiple-column constraint format, you can create a
composite key. A composite key specifies multiple columns for a primary-key
or foreign-key constraint.

The next 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))

CREATE TABLE sub_accounts (


sub_acc INTEGER PRIMARY KEY,
ref_num INTEGER NOT NULL,
ref_type INTEGER NOT NULL,
sub_descr CHAR(20),
FOREIGN KEY (ref_num, ref_type) REFERENCES accounts
(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.

A referential constraint must have a one-to-one relationship between refer-


encing and referenced columns. In other words, if the primary key is a set of
columns (a composite key), then the foreign key also must be a set of columns
that corresponds to the composite key.

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

2-234 IBM Informix Guide to SQL: Syntax


CREATE TABLE

Options
The CREATE TABLE options let you specify storage locations, extent size,
locking modes, and user-defined access methods.

Options Back to CREATE TABLE


p. 2-214

IDS + USING
LOCK MODE Access-Method
Storage Options
WITH CRCOLS Options Clause
p. 2-253 p. 2-252
p. 2-236

IDS Using the WITH CRCOLS Option


Use the WITH CRCOLS keywords to create two shadow columns that Enter-
prise Replication uses for conflict resolution. The first column, cdrserver,
contains the identity of the database server where the last modification
occurred. The second column, cdrtime, contains the time stamp of the last
modification. You must add these columns before you can use time-stamp or
user-defined routine conflict resolution.

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:

■ Do not appear when you issue the statement


SELECT * from tablename
■ Do not appear in DB-Access when you ask for information about the
columns of the table
■ Are not included in the number of columns (ncols) in the systables
system catalog table entry for tablename

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 how to use this option, refer to the IBM Informix
Dynamic Server Enterprise Replication Guide.

SQL Statements 2-235


CREATE TABLE

Storage Options
Use the storage-option portion of CREATE TABLE to specify the storage space
and the size of the extents for the table.

Storage Options Back to Options


p. 2-235

EXTENT SIZE
IN dbspace IDS Options
p. 2-251
XPS dbslice PUT Clause
p. 2-249
IDS extspace

FRAGMENT BY Clause
p. 2-238

Element Purpose Restrictions Syntax


dbslice Dbslice to store the table Must already exist. Identifier, p. 4-189
dbspace Dbspace to store the table Must already exist. Identifier, p. 4-189
extspace Name declared in the onspaces command to Must already exist. See documentation for your
a storage area outside the database server access method.

If you use the “USING Access-Method Clause” on page 2-252 to specify an


access method, that method must support the storage space.

You can specify a dbspace for the table that is different from the storage
location for the database, or you can 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-249.

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-57. ♦

2-236 IBM Informix Guide to SQL: Syntax


CREATE TABLE

Using the IN Clause


Use the IN clause to specify a storage space for a table. The storage space that
you specify must already exist.

Storing Data in a dbspace


You can use the IN clause to isolate a table. For example, if the history
database is in the dbs1 dbspace, but you want the family data placed in a
separate dbspace called famdata, use the following statements:
CREATE DATABASE history IN dbs1

CREATE TABLE family


(
id_num SERIAL(101) UNIQUE,
name CHAR(40),
nickname CHAR(20),
mother CHAR(40),
father CHAR(40)
)
IN famdata

For more information about how to store and manage your tables in separate
dbspaces, see your Administrator’s Guide.

XPS Storing Data in a dbslice


If you are using Extended Parallel Server, the IN dbslice clause allows you to
fragment a table across a group of dbspaces that share the same naming
convention. The database server fragments the table by round-robin in the
dbspaces that make up the dbslice at the time the table is created.

To fragment a table across a dbslice, you can use either the IN dbslice syntax
or the FRAGMENT BY ROUND ROBIN IN dbslice syntax.

IDS Storing Data in an extspace


In general, use the extspace storage option in conjunction with the “USING
Access-Method Clause” on page 2-252. For more information, refer to the
user documentation for your custom-access method.

SQL Statements 2-237


CREATE TABLE

FRAGMENT BY Clause
Use the FRAGMENT BY clause to create fragmented tables and specify their
distribution scheme .

FRAGMENT BY Back to Storage Options


Clause for Tables p. 2-236

FRAGMENT BY ROUND ROBIN XPS IN dbslice


IDS
,
WITH ROWIDS
, IN dbspace

EXPRESSION expression IN dbspace

XPS IDS , REMAINDER IN dbspace

HASH USING opclass , ,


, ( column ) IN dbspace
HYBRID ( column ) EXPRESSION
IN dbslice
,
expression IN dbspace , REMAINDER IN dbspace

dbslice expression dbslice


, ,
RANGE
Method Clause ( dbspace ) ( dbspace )
p. 2-244

Element Purpose Restrictions Syntax


column Column to which to apply the Must be a column within the table. Identifier,
fragmentation strategy p. 4-189
dbslice, Dbslice or dbspace to store the The dbslice must be defined. You can specify Identifier,
dbspace table fragment no more than 2,048 dbspaces (but at least 2). p. 4-189
expression Expression that defines a table Columns can be from the current table only, Expression,
fragment using a range, hash, or and data values can be from only a single row. p. 4-67
arbitrary rule Value returned must be Boolean (true or false).
opclass No default operator class Must be defined and must be associated with Identifier,
a B-tree index. p. 4-189

2-238 IBM Informix Guide to SQL: Syntax


CREATE TABLE

When you fragment a table, the IN keyword introduces the storage space
where a table fragment is to be stored.

IDS Using the WITH ROWIDS Option


Nonfragmented tables contain a hidden column called rowid, but by default,
fragmented tables have no rowid column. You can use the WITH ROWIDS
keywords to add the rowid column to a fragmented table. Each row is
automatically assigned a unique rowid value that remains stable for the life
of the row, and that the database server can use to find the physical location
of the row. Each row requires an additional 4 bytes to store the rowid.

Important: This is a deprecated feature. Use primary keys as an access method rather
than the rowid column.

You cannot use the WITH ROWIDS clause with typed tables.

Fragmenting by ROUND ROBIN


In a round-robin distribution scheme, specify at least two dbspaces where
you want the fragments to be placed. As records are inserted into the table,
they are placed in the first available dbspace. The database server balances
the load between the specified dbspaces as you insert records and distributes
the rows in such a way that the fragments always maintain approximately
the same number of rows. In this distribution scheme, the database server
must scan all fragments when it searches for a row.

XPS With Extended Parallel Server, you can specify 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-237. ♦

IDS Use the PUT clause to specify round-robin fragmentation for smart large
objects. For more information, see the “PUT Clause” on page 2-249. ♦

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.

SQL Statements 2-239


CREATE TABLE

To fragment a table by expression, specify one of the following rules:

■ Range rule
A range rule specifies fragment expressions that use a range to spec-
ify which rows are placed in a fragment, as the next 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 pre-
defined 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: See the note about the DBCENTURY environment variable and date values
in fragment expressions in the section “Logging Options” on page 2-215.

IDS The USING Opclass Option


With the USING option, you can specify a nondefault operator class for the
fragmentation strategy. The secondary-access method of the chosen operator
class must have a B-tree index structure.

In the following example, the abs_btree_ops operator class specifies several


user-defined strategy functions that order integers based on their absolute
values:
CREATE OPCLASS abs_btree_ops FOR btree
STRATEGIES (abs_lt, abs_lte, abs_eq, abs_gte, abs_gt)
SUPPORT (abs_cmp)

For the fragmentation strategy, you can specify the abs_btree_ops operator
class in the USING clause and use its strategy functions to fragment the table,
as follows:
FRAGMENT BY EXPRESSION USING abs_btree_ops
(abs_lt(x,345)) IN dbsp1,
(abs_gte(x,345) AND abs_lte(x,500)) IN dbsp2,
(abs_gt(x,500)) IN dbsp3

For information on how to create and extend an operator class, see


IBM Informix User-Defined Routines and Data Types Developer’s Guide.

2-240 IBM Informix Guide to SQL: Syntax


CREATE TABLE

IDS User-Defined Functions in Fragment Expressions


For rows that include user-defined data types, you can use comparison
conditions or user-defined functions to define the range rules. In the
following example, comparison conditions define the range rules for the
long1 column, which contains an opaque data type:
FRAGMENT BY EXPRESSION
long1 < '3001' IN dbsp1,
long1 BETWEEN '3001' AND '6000' IN dbsp2,
long1 > '6000' IN dbsp3

An implicit, user-defined cast converts 3001 and 6000 to the opaque type.

Alternatively, you can use user-defined functions to define the range rules for
the opaque data type of the long1 column:
FRAGMENT BY EXPRESSION
(lessthan(long1,'3001')) IN dbsp1,
(greaterthanorequal(long1,'3001') AND
lessthanorequal(long,'6000')) IN dbsp2,
(greaterthan(long1,'6000')) IN dbsp3

Explicit user-defined functions require parentheses around the entire


fragment expression before the IN clause, as the previous example shows.

User-defined functions in a fragment expression can be written in SPL or in


the C or Java language. These functions must satisfy four requirements:

■ They must evaluate to a Boolean value.


■ They must be nonvariant.
■ They must reside within the same database as the table.
■ They must not generate OUT parameters.

For information on how to create user-defined functions for fragment expres-


sions, refer to IBM Informix User-Defined Routines and Data Types Developer’s
Guide.

Using the REMAINDER Keyword


Use the REMAINDER keyword to specify the storage space in which to store
valid values that fall outside the specified expression or expressions.

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.

SQL Statements 2-241


CREATE TABLE

XPS Fragmenting by HASH


A hash-distribution scheme distributes the rows as you insert them, so that
the fragments maintain approximately the same number of rows. In this
distribution scheme, the database server can eliminate fragments when it
searches for a row because the hash is known internally. For example, if you
have a large database, as in a data-warehousing environment, you can
fragment your tables across disks that belong to different coservers. If you
expect to perform many queries that scan most of the data, a system-defined
hash-distribution scheme can balance the I/O processing. The following
example uses eight coservers with one dbspace defined on each coserver.
CREATE TABLE customer
(
cust_id integer,
descr char(45),
level char(15),
sale_type char(10),
channel char(30),
corp char(45),
cust char(45),
vert_mkt char(30),
state_prov char(20),
country char(15),
org_cust_id char(20)
)
FRAGMENT BY HASH (cust_id) IN
customer1_spc,
customer2_spc,
customer3_spc,
customer4_spc,
customer5_spc,
customer6_spc,
customer7_spc,
customer8_spc
EXTENT SIZE 20 NEXT SIZE 16

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.

Serial Columns in HASH-Distribution Schemes


If you base table fragmentation on a SERIAL or SERIAL8 column, only a hash-
distribution scheme is valid. In addition, the serial column must be the only
column in the hashing key. (These restrictions apply only to table distribu-
tions. Fragmentation schemes for indexes that are based on SERIAL or SERIAL8
columns are not subject to these restrictions.)

2-242 IBM Informix Guide to SQL: Syntax


CREATE TABLE

The following excerpt is from a CREATE TABLE statement:


CREATE TABLE customer
(
cust_id serial,
. . .
)
FRAGMENT BY HASH (cust_id) IN customer1_spc, customer2_spc

You might notice a difference between serial-column values in fragmented


and nonfragmented tables. The database server assigns serial values round-
robin across fragments, so a fragment might contain values from noncon-
tiguous ranges. For example, if there are two fragments, the first serial value
is placed in the first fragment, the second serial value is placed in the second
fragment, the third value is placed in the first fragment, and so on.

XPS Fragmenting by HYBRID


The HYBRID clause allows you to apply two distribution schemes to the same
table. You can use a combination of hash- and expression-distribution
schemes or a combination of range-distribution schemes on a table. This
section discusses the hash and expression form of hybrid fragmentation. For
details of range fragmentation, see “RANGE Method Clause” on page 2-244.

In hybrid fragmentation, the EXPRESSION clause determines the base


fragmentation strategy of the table, associating an expression with a set of
dbspaces (dbspace, dbslice, or dbspacelist format) for data storage. The hash
column(s) determines the dbspace within the specified set of dbspaces.

When you specify a dbslice, the database server fragments the table across
the dbspaces that make up the dbslice. Similarly, if you specify a dbspace list,
the database server fragments the table across the dbspaces in that list. In the
next example, 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

For more information on an expression-based distribution scheme, see


“Fragmenting by EXPRESSION” on page 2-239.

SQL Statements 2-243


CREATE TABLE

XPS RANGE Method Clause


You can use a range-fragmentation method as a convenient alternative to
fragmenting by the EXPRESSION or HYBRID clauses. This provides a method
to implicitly and uniformly distribute data whose fragmentation column
values are dense or naturally uniform.

In a range-fragmented table, each dbspace stores a contiguous, completely


bound and non-overlapping range of integer values over one or two
columns. In other words, the database server implicitly clusters rows within
the fragments, based on the range of the values in the fragmentation column.

RANGE Method Back to FRAGMENT BY Clause


Clause p. 2-238
,
Range
RANGE ( column Definition ) IN dbspace
p. 2-245
dbslice REMAINDER IN dbspace

Range Range IN
HYBRID ( RANGE ( column Definition )) RANGE ( column ) Clause
p. 2-245 p. 2-245

Range Range IN
HYBRID ( RANGE ( column )) ( column Definition ) Clause
RANGE p. 2-245 p. 2-245

Element Purpose Restrictions Syntax


column Column on which to apply the Must be in the current table and must be of Identifier,
fragmentation strategy data type INT or SMALL INT. p. 4-189
dbslice Dbslice that contains the dbspaces Must exist when you execute the statement. Identifier,
where the table fragments reside p.4-189
dbspace Dbspace that contains the table Must exist when you execute the statement. Identifier,
fragment The maximum number of dbspaces is 2048. p. 4-189

For hybrid strategies with two range definitions, the second column must be
different column name from the first. For hybrid strategies with exactly one
range definition, both occurrences of column must specify the same column.

If you list more than one dbslice, including a remainder dbslice, each dbslice
must contain the same number of dbspaces. Unless you are specifying the
dbspace in the REMAINDER option, you must specify at least two dbspaces.

2-244 IBM Informix Guide to SQL: Syntax


CREATE TABLE

Range Definition
Use the range definition to specify the minimum and maximum values of the
entire range.

Range Back to RANGE Method Clause


Definition p. 2-244

max_val

MIN min_val MAX

Element Purpose Restrictions Syntax


max_val Maximum value in the Must be an INT or SMALLINT greater than Literal Number,
range or equal to the min_val if min_val is supplied. p. 4-216
min_val Minimum value in the Must be an INT or SMALLINT less than or Literal Number,
range; the default is 0. equal to max_val. p. 4-216

You do not need to specify a minimum value. The minimum and maximum
values define the exact range of values to allocate for each storage space.

Range IN Clause
Use the IN clause to specify the storage spaces in which to distribute the data.

Range IN Back to RANGE Method Clause


Clause p. 2-244
,

IN dbslice
, REMAINDER IN dbslice
( dbspace ) ,
( dbspace )

Element Purpose Restrictions Syntax


dbslice Dbslice that contains the dbspaces to store table fragments Must exist. Identifier, p.4-189
dbspace Dbspace to store the table fragment Must exist. Identifier, p. 4-189

SQL Statements 2-245


CREATE TABLE

If you specify more than one dbslice, including a remainder dbslice, each
dbslice must contain the same number of dbspaces.

Unless you are specifying the dbspace in the REMAINDER option, the
minimum number of dbspaces that you can specify is two. The maximum
number of dbspaces that you can specify is 2,048.

When you use a range-fragmentation method, the number of integer 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 -- 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.

Using the REMAINDER Keyword


Use the REMAINDER keyword to specify the storage space in which to store
valid values that fall outside the specified expression or expressions.

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 the table after it is created:
■ You cannot change the fragmentation strategy (ALTER FRAGMENT).
■ You cannot rename the columns of the table (RENAME COLUMN).
■ You cannot alter the table in any way except to change the table type
or to change the lock mode.

That is, the Usage-TYPE options and the Lock Mode clause are the only valid
options of ALTER TABLE for a table that has range fragmentation.

2-246 IBM Informix Guide to SQL: Syntax


CREATE TABLE

Examples
The following examples illustrate range fragmentation in its simple and
hybrid forms.

Simple Range-Fragmentation Strategy


The following example shows a simple range-fragmentation strategy:
CREATE TABLE Tab1 (Col1 INT...)
FRAGMENT BY RANGE (Col1 MIN 100 MAX 200)
IN db1, db2, db3, db4

In this example, the database server fragments the table according to the
following allocations.

Storage Space Holds Values Storage Space Holds Values

db1 100 <= Col1 < 125 db3 150 <= Col1 < 175

db2 125 <= Col1 < 150 db4 175 <= Col1 < 200

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

As the examples show, the range-fragmentation example requires much less


coding to achieve the same results. The same is true for the hybrid-range
fragmentation compared to hybrid-expression fragmentation methods.

Column-Major-Range Allocation
The following example demonstrates the syntax for column-major-range
allocation, a hybrid-range fragmentation strategy:
CREATE TABLE tab2 (col2 INT, colx char (5))
FRAGMENT BY HYBRID
( RANGE (col2 MIN 100 MAX 220))
RANGE (col2)
IN dbsl1, dbsl2, dbsl3

SQL Statements 2-247


CREATE TABLE

This type of fragmentation creates a distribution across dbslices and provides


a further subdivision within each dbslice (across the dbspaces in the dbslice)
such that when a query specifies a value for col1 (for example, WHERE col1
= 127), the query uniquely identifies a dbspace. To take advantage of the
additional subdivision, you must specify more than one dbslice.

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

This fragmentation strategy is the counterpart to the column-major-range


allocation. The advantages and restrictions are equivalent.

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 fragmentation 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.

2-248 IBM Informix Guide to SQL: Syntax


CREATE TABLE

IDS PUT Clause


Use the PUT clause to specify the storage spaces and characteristics for each
column that will contain smart large objects.

PUT Clause Back to Storage Options


p. 2-236
,
,
PUT column IN ( sbspace )

,
( )
EXTENT SIZE kbytes

NO LOG

LOG

HIGH INTEG

NO KEEP ACCESS TIME

KEEP ACCESS TIME

Element Purpose Restrictions Syntax


column Column to store in sbspace Must contain a user-defined, complex, Identifier, p. 4-189
BLOB, or CLOB data type.
kbytes Number of kilobytes to allocate Must be an integer value. Literal Number,
for the extent size p. 4-216
sbspace Name of an area of storage Must exist. Identifier, p. 4-189

The column cannot be in the form column.field. That is, the smart large object
that you are storing cannot be one field of a ROW type.
A smart large object is contained in a single sbspace. The SBSPACENAME
configuration parameter specifies the system default in which smart large
objects are created unless you specify another area.

SQL Statements 2-249


CREATE TABLE

Specifying more than one sbspace 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 syscolattribs system catalog table
contains one row for each sbspace that you specify in the PUT clause.

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 “Alternative to Full Logging” on page 2-251.

Six storage options are available to store BLOB and CLOB data:

Option Purpose

EXTENT SIZE Specifies how many kilobytes in a smart-large-object extent.


The database server might round the EXTENT SIZE up so that the
extents are multiples of the sbspace page size.

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.

KEEP ACCESS Records, in the smart-large-object metadata, the system time


TIME when the smart large object was last read or written.

LOG Follows the logging procedure used with the current database log
for the corresponding smart large object. This option can generate
large amounts of log traffic and increase the risk of filling the
logical log. (See also “Alternative to Full Logging” on page 2-251.)

NO KEEP Does not record the system time when the smart large object was
ACCESS TIME last read or written. This provides better performance than the
KEEP ACCESS TIME option, and is the default tracking behavior.

NO LOG Turns off logging. This option is the default behavior.

If a user-defined or complex data 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.

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-57.

2-250 IBM Informix Guide to SQL: Syntax


CREATE TABLE

Alternative to Full Logging


Instead of full logging, you can turn off logging when you load the smart
large object initially and then turn logging back on once the object is loaded.

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 statement creates the greek table. Data values for the table are
fragmented into the dbs1 and dbs2 dbspaces. The PUT clause assigns the
smart-large-object data in the gamma and delta columns to the sb1 and sb2
sbspaces, respectively. The TEXT data values in the eps column are assigned
to the blb1 blobspace.
CREATE TABLE greek
(alpha INTEGER,
beta VARCHAR(150),
gamma CLOB,
delta BLOB,
eps TEXT IN blb1)
FRAGMENT BY EXPRESSION
alpha <= 5 IN dbs1, alpha > 5 IN dbs2
PUT gamma IN (sb1), delta IN (sb2)

EXTENT SIZE Options


The EXTENT SIZE options can define the size of extents assigned to the table.

EXTENT SIZE Options Back to Storage Options


p. 2-236

EXTENT SIZE first_kilobytes NEXT SIZE next_kilobytes

Element Purpose Restrictions Syntax


first_kilobytes Length in kilobytes of the first Must return a positive number; Expression, p.4-67
extent for the table; default is 16. maximum is the chunk size.
next_kilobytes Length in kilobytes of each Must return a positive number; Expression, p.4-67
subsequent extent; default is 16. maximum is the chunk size.

SQL Statements 2-251


CREATE TABLE

The minimum length of first_kilobytes (and of next_kilobytes) is four times the


disk-page size on your syst