100% found this document useful (1 vote)
249 views1,324 pages

SQL Syntax

syntax

Uploaded by

poopz
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 (1 vote)
249 views1,324 pages

SQL Syntax

syntax

Uploaded by

poopz
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

Informix Guide to SQL

Syntax

Informix Extended Parallel Server, Version 8.3


Informix Dynamic Server.2000, Version 9.2

December 1999
Part No. 000-6527
Published by Informix Press Informix Corporation
4100 Bohannon Drive
Menlo Park, CA 94025-1032

© 1999 Informix Corporation. All rights reserved. The following are trademarks of Informix Corporation
or its affiliates, one or more of which may be registered in the United States or other jurisdictions:

Answers OnLineTM; C-ISAM; Client SDKTM; DataBlade; Data DirectorTM; Decision FrontierTM;
Dynamic Scalable ArchitectureTM; Dynamic ServerTM; Dynamic ServerTM, Developer EditionTM;
Dynamic ServerTM with Advanced Decision Support OptionTM; Dynamic ServerTM with Extended
Parallel OptionTM; Dynamic ServerTM with MetaCube; Dynamic ServerTM with Universal Data OptionTM;
Dynamic ServerTM with Web Integration OptionTM; Dynamic ServerTM, Workgroup EditionTM;
Dynamic Virtual MachineTM; Extended Parallel ServerTM; FormationTM; Formation ArchitectTM;
Formation Flow EngineTM; Gold Mine Data Access; IIF.2000TM; [Link]; [Link]; Illustra; Informix;
Informix 4GL; Informix InquireSM; Informix Internet Foundation.2000TM; InformixLink;
Informix Red Brick Decision ServerTM; Informix Session ProxyTM; Informix VistaTM; InfoShelfTM;
InterforumTM; I-SpyTM; MediazationTM; MetaCube; NewEraTM; ON-BarTM; OnLine Dynamic ServerTM;
OnLine/Secure Dynamic ServerTM; OpenCase; OrcaTM; PaVERTM; Red Brick and Design;
Red Brick Data MineTM; Red Brick Mine BuilderTM; Red Brick DecisionscapeTM; Red Brick ReadyTM;
Red Brick Systems; Regency Support; Rely on Red BrickSM; RISQL; Solution DesignSM; STARindexTM;
STARjoinTM; SuperView; TARGETindexTM; TARGETjoinTM; The Data Warehouse Company;
The one with the smartest data [Link]; The world is being digitized. We’re indexing [Link];
Universal Data Warehouse BlueprintTM; Universal Database ComponentsTM; Universal Web ConnectTM;
ViewPoint; VisionaryTM; Web Integration SuiteTM. The Informix logo is registered with the United States
Patent and Trademark Office. The DataBlade logo is registered with the United States Patent and
Trademark Office.

Documentation Team: Linda Briscoe, Evelyn Eldridge, Kathy Schaefer Francis, Mary Kraemer,
Barbara Nomiyama, Tom Noronha, Elaina Von Haas, Richelle White

GOVERNMENT LICENSE RIGHTS

Software and documentation acquired by or for the US Government are provided with rights as follows:
(1) if for civilian agency use, with rights as restricted by vendor’s standard license, as prescribed in FAR 12.212;
(2) if for Dept. of Defense use, with rights as restricted by vendor’s standard license, unless superseded by a
negotiated vendor license, as prescribed in DFARS 227.7202. Any whole or partial reproduction of software or
documentation marked with this legend must reproduce this legend.

ii 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 . . . . . . . . . . . . . . . . . . . . 6
New Features in Version 8.3 . . . . . . . . . . . . . 6
New Features in Version 9.2 . . . . . . . . . . . . . 8
Documentation Conventions . . . . . . . . . . . . . . 10
Typographical Conventions . . . . . . . . . . . . . 11
Icon Conventions . . . . . . . . . . . . . . . . . 12
Syntax Conventions . . . . . . . . . . . . . . . . 14
Sample-Code Conventions . . . . . . . . . . . . . . 19
Additional Documentation . . . . . . . . . . . . . . . 19
On-Line Manuals . . . . . . . . . . . . . . . . . 20
Printed Manuals . . . . . . . . . . . . . . . . . 20
On-Line Help . . . . . . . . . . . . . . . . . . 20
Error Message Documentation . . . . . . . . . . . . 20
Documentation Notes, Release Notes, Machine Notes . . . . 21
Related Reading . . . . . . . . . . . . . . . . . 22
Compliance with Industry Standards . . . . . . . . . . . 22
Informix Welcomes Your Comments . . . . . . . . . . . . 23

Chapter 1 Overview of SQL Syntax


In This Chapter . . . . . . . . . . . . . . . . . . . 1-3
How to Enter SQL Statements . . . . . . . . . . . . . . 1-4
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-5
ALLOCATE COLLECTION . . . . . . . . . . . . . 2-6
ALLOCATE DESCRIPTOR . . . . . . . . . . . . . 2-8
ALLOCATE ROW . . . . . . . . . . . . . . . . 2-10
ALTER FRAGMENT . . . . . . . . . . . . . . . 2-12
ALTER FUNCTION . . . . . . . . . . . . . . . . 2-41
ALTER INDEX . . . . . . . . . . . . . . . . . 2-44
ALTER PROCEDURE . . . . . . . . . . . . . . . 2-48
ALTER ROUTINE . . . . . . . . . . . . . . . . 2-51
ALTER TABLE . . . . . . . . . . . . . . . . . 2-55
BEGIN WORK. . . . . . . . . . . . . . . . . . 2-91
CLOSE . . . . . . . . . . . . . . . . . . . . 2-94
CLOSE DATABASE . . . . . . . . . . . . . . . . 2-98
COMMIT WORK. . . . . . . . . . . . . . . . . 2-100
CONNECT . . . . . . . . . . . . . . . . . . . 2-103
CREATE AGGREGATE . . . . . . . . . . . . . . 2-115
CREATE CAST . . . . . . . . . . . . . . . . . 2-119
CREATE DATABASE . . . . . . . . . . . . . . . 2-124
CREATE DISTINCT TYPE . . . . . . . . . . . . . 2-127
CREATE EXTERNAL TABLE . . . . . . . . . . . . 2-131
CREATE FUNCTION . . . . . . . . . . . . . . . 2-146
CREATE FUNCTION FROM. . . . . . . . . . . . . 2-155
CREATE INDEX . . . . . . . . . . . . . . . . . 2-157
CREATE OPAQUE TYPE . . . . . . . . . . . . . . 2-186
CREATE OPCLASS . . . . . . . . . . . . . . . . 2-193
CREATE PROCEDURE . . . . . . . . . . . . . . 2-199
CREATE PROCEDURE FROM . . . . . . . . . . . . 2-209
CREATE ROLE . . . . . . . . . . . . . . . . . 2-212
CREATE ROUTINE FROM . . . . . . . . . . . . . 2-214
CREATE ROW TYPE . . . . . . . . . . . . . . . 2-216
CREATE SCHEMA . . . . . . . . . . . . . . . . 2-222
CREATE SYNONYM . . . . . . . . . . . . . . . 2-226
CREATE TABLE . . . . . . . . . . . . . . . . . 2-230
CREATE Temporary TABLE . . . . . . . . . . . . . 2-286
CREATE TRIGGER . . . . . . . . . . . . . . . . 2-296
CREATE VIEW . . . . . . . . . . . . . . . . . 2-334
DATABASE. . . . . . . . . . . . . . . . . . . 2-341
DEALLOCATE COLLECTION . . . . . . . . . . . . 2-343
DEALLOCATE DESCRIPTOR . . . . . . . . . . . . 2-345
DEALLOCATE ROW . . . . . . . . . . . . . . . 2-347
DECLARE . . . . . . . . . . . . . . . . . . . 2-349
DELETE . . . . . . . . . . . . . . . . . . . . 2-373
iv Informix Guide to SQL: Syntax
DESCRIBE . . . . . . . . . . . . . . . . . . 2-382
DISCONNECT . . . . . . . . . . . . . . . . . 2-389
DROP AGGREGATE . . . . . . . . . . . . . . . 2-393
DROP CAST . . . . . . . . . . . . . . . . . . 2-395
DROP DATABASE. . . . . . . . . . . . . . . . 2-397
DROP FUNCTION . . . . . . . . . . . . . . . 2-399
DROP INDEX . . . . . . . . . . . . . . . . . 2-401
DROP OPCLASS . . . . . . . . . . . . . . . . 2-403
DROP PROCEDURE . . . . . . . . . . . . . . . 2-404
DROP ROLE . . . . . . . . . . . . . . . . . . 2-407
DROP ROUTINE . . . . . . . . . . . . . . . . 2-408
DROP ROW TYPE . . . . . . . . . . . . . . . . 2-410
DROP SYNONYM. . . . . . . . . . . . . . . . 2-412
DROP TABLE . . . . . . . . . . . . . . . . . 2-413
DROP TRIGGER . . . . . . . . . . . . . . . . 2-417
DROP TYPE . . . . . . . . . . . . . . . . . . 2-418
DROP VIEW . . . . . . . . . . . . . . . . . . 2-420
EXECUTE. . . . . . . . . . . . . . . . . . . 2-422
EXECUTE FUNCTION . . . . . . . . . . . . . . 2-434
EXECUTE IMMEDIATE . . . . . . . . . . . . . . 2-441
EXECUTE PROCEDURE . . . . . . . . . . . . . 2-444
FETCH. . . . . . . . . . . . . . . . . . . . 2-455
FLUSH . . . . . . . . . . . . . . . . . . . . 2-469
FREE . . . . . . . . . . . . . . . . . . . . 2-472
GET DESCRIPTOR . . . . . . . . . . . . . . . 2-475
GET DIAGNOSTICS . . . . . . . . . . . . . . . 2-483
GRANT . . . . . . . . . . . . . . . . . . . 2-500
GRANT FRAGMENT . . . . . . . . . . . . . . 2-523
INFO . . . . . . . . . . . . . . . . . . . . 2-532
INSERT . . . . . . . . . . . . . . . . . . . 2-535
LOAD . . . . . . . . . . . . . . . . . . . . 2-553
LOCK TABLE . . . . . . . . . . . . . . . . . 2-563
OPEN . . . . . . . . . . . . . . . . . . . . 2-566
OUTPUT . . . . . . . . . . . . . . . . . . . 2-577
PREPARE . . . . . . . . . . . . . . . . . . . 2-579
PUT . . . . . . . . . . . . . . . . . . . . . 2-593
RENAME COLUMN . . . . . . . . . . . . . . . 2-604
RENAME DATABASE . . . . . . . . . . . . . . 2-606
RENAME TABLE . . . . . . . . . . . . . . . . 2-607
REVOKE . . . . . . . . . . . . . . . . . . . 2-610
REVOKE FRAGMENT . . . . . . . . . . . . . . 2-628
ROLLBACK WORK . . . . . . . . . . . . . . . 2-632

Table of Contents v
SELECT . . . . . . . . . . . . . . . . . . . . 2-634
SET AUTOFREE . . . . . . . . . . . . . . . . . 2-691
SET CONNECTION. . . . . . . . . . . . . . . . 2-694
SET Database Object Mode . . . . . . . . . . . . . 2-700
SET DATASKIP . . . . . . . . . . . . . . . . . 2-709
SET DEBUG FILE TO . . . . . . . . . . . . . . . 2-712
SET DEFERRED_PREPARE . . . . . . . . . . . . . 2-715
SET DESCRIPTOR . . . . . . . . . . . . . . . . 2-719
SET EXPLAIN . . . . . . . . . . . . . . . . . . 2-730
SET ISOLATION . . . . . . . . . . . . . . . . . 2-736
SET LOCK MODE . . . . . . . . . . . . . . . . 2-742
SET LOG . . . . . . . . . . . . . . . . . . . 2-745
SET OPTIMIZATION . . . . . . . . . . . . . . . 2-747
SET PDQPRIORITY . . . . . . . . . . . . . . . . 2-751
SET PLOAD FILE . . . . . . . . . . . . . . . . 2-755
SET Residency. . . . . . . . . . . . . . . . . . 2-756
SET ROLE . . . . . . . . . . . . . . . . . . . 2-758
SET SCHEDULE LEVEL . . . . . . . . . . . . . . 2-760
SET SESSION AUTHORIZATION . . . . . . . . . . . 2-761
SET STATEMENT CACHE . . . . . . . . . . . . . 2-764
SET TRANSACTION . . . . . . . . . . . . . . . 2-768
SET Transaction Mode . . . . . . . . . . . . . . . 2-774
START VIOLATIONS TABLE . . . . . . . . . . . . 2-778
STOP VIOLATIONS TABLE . . . . . . . . . . . . . 2-800
TRUNCATE . . . . . . . . . . . . . . . . . . 2-802
UNLOAD . . . . . . . . . . . . . . . . . . . 2-805
UNLOCK TABLE . . . . . . . . . . . . . . . . 2-813
UPDATE . . . . . . . . . . . . . . . . . . . 2-815
UPDATE STATISTICS . . . . . . . . . . . . . . . 2-835
WHENEVER . . . . . . . . . . . . . . . . . . 2-848

Chapter 3 SPL Statements


In This Chapter . . . . . . . . . . . . . . . . . . . 3-3
CALL . . . . . . . . . . . . . . . . . . . . . 3-4
CASE . . . . . . . . . . . . . . . . . . . . . 3-7
CONTINUE . . . . . . . . . . . . . . . . . . 3-10
DEFINE . . . . . . . . . . . . . . . . . . . . 3-11
EXIT . . . . . . . . . . . . . . . . . . . . . 3-24
FOR . . . . . . . . . . . . . . . . . . . . . 3-26
FOREACH . . . . . . . . . . . . . . . . . . . 3-30
IF . . . . . . . . . . . . . . . . . . . . . . 3-37
LET . . . . . . . . . . . . . . . . . . . . . 3-41

vi Informix Guide to SQL: Syntax


ON EXCEPTION . . . . . . . . . . . . . . . . 3-45
RAISE EXCEPTION . . . . . . . . . . . . . . . 3-50
RETURN . . . . . . . . . . . . . . . . . . . 3-52
SYSTEM . . . . . . . . . . . . . . . . . . . 3-55
TRACE . . . . . . . . . . . . . . . . . . . 3-58
WHILE. . . . . . . . . . . . . . . . . . . . 3-62

Chapter 4 Segments
In This Chapter . . . . . . . . . . . . . . . . . . 4-3
Argument. . . . . . . . . . . . . . . . . . . 4-6
Collection Derived Table . . . . . . . . . . . . . 4-9
Condition . . . . . . . . . . . . . . . . . . 4-27
Database Name . . . . . . . . . . . . . . . . . 4-47
Database Object Name . . . . . . . . . . . . . . 4-50
Data Type . . . . . . . . . . . . . . . . . . . 4-53
DATETIME Field Qualifier . . . . . . . . . . . . . 4-71
Expression . . . . . . . . . . . . . . . . . . 4-73
External Routine Reference . . . . . . . . . . . . . 4-202
Identifier . . . . . . . . . . . . . . . . . . . 4-205
INTERVAL Field Qualifier . . . . . . . . . . . . . 4-223
Jar Name . . . . . . . . . . . . . . . . . . . 4-226
Literal Collection . . . . . . . . . . . . . . . . 4-227
Literal DATETIME. . . . . . . . . . . . . . . . 4-231
Literal INTERVAL . . . . . . . . . . . . . . . . 4-234
Literal Number . . . . . . . . . . . . . . . . . 4-237
Literal Row . . . . . . . . . . . . . . . . . . 4-239
Optimizer Directives . . . . . . . . . . . . . . . 4-244
Owner Name . . . . . . . . . . . . . . . . . 4-257
Quoted String . . . . . . . . . . . . . . . . . 4-260
Relational Operator . . . . . . . . . . . . . . . 4-265
Return Clause . . . . . . . . . . . . . . . . . 4-270
Routine Modifier . . . . . . . . . . . . . . . . 4-274
Routine Parameter List . . . . . . . . . . . . . . 4-286
Shared-Object Filename . . . . . . . . . . . . . . 4-292
Specific Name . . . . . . . . . . . . . . . . . 4-296
Statement Block. . . . . . . . . . . . . . . . . 4-298

Appendix A Reserved Words for Dynamic Server 2000

Appendix B Reserved Words for Extended Parallel Server

Index

Table of Contents vii


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 . . . . . . . . . . . . . . . . . . . . . 6
New Features in Version 8.3 . . . . . . . . . . . . . . 6
Performance Enhancements . . . . . . . . . . . . . 6
New SQL Functionality . . . . . . . . . . . . . . 6
Version 8.3 Features from Version 7.30 . . . . . . . . . 7
New Features in Version 9.2 . . . . . . . . . . . . . . 8
Extensibility Enhancements . . . . . . . . . . . . . 8
Performance Improvements . . . . . . . . . . . . . 9
Special Features . . . . . . . . . . . . . . . . . 9
Version 9.2 Features from Dynamic Server 7.30 . . . . . . 9
Documentation Conventions . . . . . . . . . . . . . . . 10
Typographical Conventions . . . . . . . . . . . . . . 11
Icon Conventions . . . . . . . . . . . . . . . . . . 12
Comment Icons . . . . . . . . . . . . . . . . . 12
Feature, Product, and Platform Icons . . . . . . . . . . 12
Compliance Icons . . . . . . . . . . . . . . . . 14
Syntax Conventions . . . . . . . . . . . . . . . . . 14
Elements That Can Appear on the Path . . . . . . . . . 15
How to Read a Syntax Diagram . . . . . . . . . . . . 18
Sample-Code Conventions . . . . . . . . . . . . . . . 19
Additional Documentation . . . . . . . . . . . . . . . . 19
On-Line Manuals . . . . . . . . . . . . . . . . . . 20
Printed Manuals . . . . . . . . . . . . . . . . . . 20
On-Line Help . . . . . . . . . . . . . . . . . . . 20
Error Message Documentation . . . . . . . . . . . . . 20
Documentation Notes, Release Notes, Machine Notes . . . . . 21
Related Reading . . . . . . . . . . . . . . . . . . 22

Compliance with Industry Standards. . . . . . . . . . . . . 22


Informix Welcomes Your Comments . . . . . . . . . . . . . 23

2 Informix Guide to SQL: Syntax


In This Introduction
This Introduction provides an overview of the information in this manual
and describes the conventions it uses.

About This Manual


This manual contains all the syntax descriptions for structured query
language (SQL) and Stored Procedure Language (SPL) statements for Version
9.2 of Informix Dynamic Server 2000 and Version 8.3 of Informix Extended
Parallel Server.

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


the Informix Guide to SQL: Tutorial, and the Informix Guide to Database Design
and Implementation. The Informix Guide to SQL: Reference provides reference
information for aspects of SQL other than the language statements. The
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
Informix Guide to Database Design and Implementation shows how to use SQL to
implement and manage your 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 manual 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:

■ Informix Extended Parallel Server, Version 8.3


■ Informix Dynamic Server 2000, Version 9.2

Assumptions About Your Locale


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 NT environments. This locale
supports U.S. English format conventions for dates, times, and currency, and
also supports the ISO 8859-1 or Microsoft 1252 code set, which includes the
ASCII code set plus many 8-bit characters such as é, è, and ñ.

If you plan to use nondefault characters in your data or your SQL identifiers,
or if you want to conform to the nondefault collation rules of character data,
you need to specify the appropriate nondefault locale.

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


other considerations related to GLS locales, see the Informix Guide to GLS
Functionality.

4 Informix Guide to SQL: Syntax


Demonstration Databases

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

■ The stores_demo database illustrates a relational schema with infor-


mation about a fictitious wholesale sporting-goods distributor.
Many examples in 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 Informix Guide to Database Design and
Implementation. ♦
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 DB-Access User’s Manual. For descriptions of the databases
and their contents, see the 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.

Introduction 5
New Features

New Features
For a comprehensive list of new database server features, see the release
notes. This section lists new features relevant to this manual.

New Features in Version 8.3


This manual describes new features in Version 8.3 of Extended Parallel
Server. The features fall into the following areas:
■ Performance enhancements
■ New SQL functionality
■ Version 8.3 features from Dynamic Server 7.30

Performance Enhancements
This manual describes the following performance enhancements to
Version 8.3 of 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.3 of
Extended Parallel Server:
■ CASE statement in Stored Procedure Language (SPL)
■ Creating a table with RANGE fragmentation
■ DELETE…USING statement to delete rows based on a table join
■ Globally detached indexes
■ Load and unload simple large objects to external tables

6 Informix Guide to SQL: Syntax


New Features in Version 8.3

■ MIDDLE function
■ Referential integrity for globally detached indexes
■ TRUNCATE statement

Version 8.3 Features from Version 7.30


This manual describes the following features from Version 7.3 of Dynamic
Server in Version 8.3 of 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 functions for string
manipulation
■ 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

Introduction 7
New Features in Version 9.2

New Features in Version 9.2


This manual describes new features in Version 9.2 of Dynamic Server. The
features fall into the following areas:

■ Extensibility enhancements
■ Performance improvements
■ Special features
■ Version 9.2 features from Version 7.30 of Dynamic Server

Extensibility Enhancements
This manual describes the following extensibility enhancements to
Version 9.2 of Dynamic Server:

■ General enhancements to SQL:


❑ Embedded newline characters in quoted strings
❑ Nested dot expressions for row types
■ Triggers on SELECT statements
■ Enhancements to smart large objects:
❑ Round-robin fragmentation for smart large objects
❑ ALTER TABLE for smart large objects
■ Enhancements to collections:
❑ Collection constructors that use arbitrary expression elements
❑ Collection-derived tables
❑ Collection subqueries
■ Enhancements to row types:
❑ Serial types in row types
❑ GRANT, REVOKE UNDER on row types
■ Enhancements to user-defined routines (UDRs):
❑ GRANT, REVOKE on UDR external languages
❑ ALTER FUNCTION, PROCEDURE, ROUTINE statements
❑ User-defined aggregates

8 Informix Guide to SQL: Syntax


New Features in Version 9.2

Performance Improvements
This manual describes the following performance improvements to
Version 9.2 of Dynamic Server:

■ For SQL:
❑ Parallel statement-local variables (SLVs)
❑ SQL statement cache
■ For UDRs:
❑ Expensive-function optimization
❑ Parallel UDRs
❑ User-defined statistics routines

Special Features
This manual describes the following special features of Version 9.2 of
Dynamic Server:

■ Long identifiers:
❑ 128-character identifier
❑ 32-character user names
■ Ability to retain update locks

Version 9.2 Features from Dynamic Server 7.30


This manual also describes features first released in Version 7.30. These
features fall into the following areas:

■ Reliability, availability, and serviceability:


ALTER FRAGMENT ATTACH, DETACH enhancements
■ Performance:
❑ Optimizer directives
❑ Select first n rows
❑ SET OPTIMIZATION statement enhancements
❑ Memory-resident tables

Introduction 9
Documentation Conventions

■ Application migration:
❑ UPPER, LOWER, and INITCAP functions for case-insensitive
search (for built-in types)
❑ REPLACE, SUBSTR, LPAD, and RPAD functions for string manip-
ulation (for built-in types)
❑ UNION operator in CREATE VIEW statement
❑ CASE expression
❑ NVL and DECODE functions
❑ TO_CHAR and TO_DATE date-conversion functions (for built-in
types)
❑ EXECUTE PROCEDURE syntax to update triggering columns
❑ New arguments to the dbinfo() function to obtain the hostname
and version of the database server

Documentation Conventions
This section describes the conventions that this manual uses. These
conventions make it easier to gather information from this and other volumes
in the documentation set.

The following conventions are discussed:

■ Typographical conventions
■ Icon conventions
■ Syntax conventions
■ Sample-code conventions

10 Informix Guide to SQL: Syntax


Typographical Conventions

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 one or more product- or


platform-specific paragraphs.

➞ 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 11
Icon Conventions

Icon Conventions
Throughout the documentation, you will find text that is identified by several
different types of icons. This section describes these icons.

Comment Icons
Comment icons identify three types of information, as the following table
describes. This information always appears in italics.

Icon 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 Informix ESQL/C

(1 of 2)

12 Informix Guide to SQL: Syntax


Icon Conventions

Icon Description

Ext
Identifies information that is specific to external routines,
that is, UDRs written in both C and Java.

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

IDS
Identifies information that is specific to Informix Dynamic
Server 2000

Java
Identifies information that is specific to UDRs written in
Java

SQLE
Identifies information that is specific to SQL Editor, which
is a component of Informix Enterprise Command Center
for Dynamic Server

UNIX
Identifies information that is specific to UNIX platforms

WIN NT
Identifies information that is specific to the Windows NT
environment

XPS
Identifies information or syntax that is specific to Informix
Extended Parallel Server
(2 of 2)
These icons can apply to an entire section or to one or more paragraphs
within a section. If an icon appears next to a section heading, the information
that applies to the indicated feature, product, or platform ends at the next
heading at the same or higher level. A ♦ symbol indicates the end of feature-,
product-, or platform-specific information that appears in one or more
paragraphs within a section.

Introduction 13
Syntax Conventions

Compliance Icons
Compliance icons indicate paragraphs that provide guidelines for complying
with a standard.

Icon Description

ANSI
Identifies information that is specific to an ANSI-compliant
database

X/O
Identifies functionality that conforms to X/Open

+
Identifies information or syntax that is an Informix
extension to ANSI SQL-92 entry-level standard SQL

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 LOG

BUFFERED

Each syntax diagram begins at the upper-left corner and ends at the upper-
right corner with a vertical terminator. Between these points, any path that
does not stop or reverse direction describes a possible form of the statement.

14 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.
ADD Clause

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.

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 a syntax diagram:


(1 of 3)

Introduction 15
Syntax Conventions

Element Description

This path is valid only for C user-defined routines


C
(UDRs).

DB This path is valid only for DB-Access.

This path is valid only for Informix ESQL/C.


E/C

This path is valid only for external routines, that is,


Ext
UDRs written in C and Java.

This path is recommended only if you use a nonde-


GLS
fault locale.

This path is valid only for UDRs written in Java.


Java

This path is valid only for Dynamic Server.


IDS

This path is valid only if you are using Informix Stored


SPL
Procedure Language (SPL).

This path is valid only for Extended Parallel Server.


XPS

This path is an Informix extension to ANSI SQL-92


+
entry-level standard SQL. If you initiate Informix
extension checking and include this syntax branch,
you receive a warning. If you have set the
DBANSIWARN environment variable at compile time,
or have used the -ansi compile flag, you receive
warnings at compile time. If you have DBANSIWARN
set at runtime, or if you compiled with the -ansi flag,
warning flags are set in the sqlwarn structure. The
Informix extension warnings tend to be conservative.
Sometimes the warnings appear even when a syntax
path conforms to the ANSI standard.
(2 of 3)

16 Informix Guide to SQL: Syntax


Syntax Conventions

Element Description

ALL
A shaded option is the default action.

Syntax within a pair of arrows is a subdiagram.

The vertical line 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.)

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

, A gate ( 3 ) on a path indicates that you can only use


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

Introduction 17
Syntax Conventions

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

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

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.

18 Informix Guide to SQL: Syntax


Sample-Code Conventions

Sample-Code Conventions
Examples of SQL code occur throughout this manual. Except where noted,
the code is not specific to any single Informix application development tool.
If only SQL statements are listed in the example, they are not delimited by
semicolons. For instance, you might see the code in the following example:
CONNECT TO stores_demo
...

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.

Tip: Ellipsis points in a code example indicate that more code would be added in a
full application, but it is not necessary to show it to describe the concept being
discussed.

For detailed directions on using SQL statements for a particular application


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

Additional Documentation
For additional information, you might want to refer to the following types of
documentation:
■ On-line manuals
■ Printed manuals
■ On-line help
■ Error message documentation
■ Documentation notes, release notes, and machine notes
■ Related reading

Introduction 19
On-Line Manuals

On-Line Manuals
An Answers OnLine CD that contains Informix manuals in electronic format
is provided with your Informix products. You can install the documentation
or access it directly from the CD. For information about how to install, read,
and print on-line manuals, see the installation insert that accompanies
Answers OnLine.

Informix on-line manuals are also available on the following Web site:
[Link]/answers

Printed Manuals
To order printed manuals, call 1-800-331-1763 or send email to
moreinfo@[Link]. Please provide the following information when
you place your order:

■ The documentation that you need


■ The quantity that you need
■ Your name, address, and telephone number

WIN NT On-Line Help


Informix provides on-line help with each graphical user interface (GUI) that
displays information about those interfaces and the functions that they
perform. Use the help facilities that each GUI provides to display the on-line
help.

Error Message Documentation


Informix software products provide ASCII files that contain all of the
Informix error messages and their corrective actions.

20 Informix Guide to SQL: Syntax


Documentation Notes, Release Notes, Machine Notes

UNIX To read error messages and corrective actions on UNIX, use one of the
following utilities.

Utility Description

finderr Displays error messages on line

rofferr Formats error messages for printing


WIN NT To read error messages and corrective actions in Windows environments, use
the Informix Find Error utility. To display this utility, choose
Start➞Programs➞Informix from the Task Bar. ♦
Instructions for using the preceding utilities are available in Answers
OnLine. Answers OnLine also provides a listing of error messages and
corrective actions in HTML format.

Documentation Notes, Release Notes, Machine Notes


In addition to printed documentation, the following sections describe the on-
line files that supplement the information in this manual. Please examine
these files before you begin using your database server. They contain vital
information about application and performance issues.

UNIX On UNIX platforms, the following on-line files appear in the


$INFORMIXDIR/release/en_us/0333 directory. Replace x.y in the filenames
with the version number of your database server.

On-Line File Purpose

SQLDOC_x.y The documentation-notes file for your version of this manual


describes topics that are not covered in the manual or that were
modified since publication.

SERVERS_x.y The release-notes file describes feature differences from earlier


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

IDS_9.2 or The machine-notes file describes any special actions that you
XPS_x.y must take to configure and use Informix products on your
computer. Machine notes are named for the product described.

Introduction 21
Related Reading

WIN NT The following items appear in the Informix folder. To display this folder,
choose Start➞Programs➞Informix from the Task Bar.

Program Group Item Description

Documentation Notes This item includes additions or corrections to manuals,


along 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 Informix products and how these differ-
ences might affect current products. This file also
contains information about any known problems and
their workarounds.

Machine notes do not apply to Windows environments. ♦

Related Reading
For a list of publications that provide an introduction to database servers and
operating-system platforms, refer to your Getting Started manual.

Compliance with Industry Standards


The American National Standards Institute (ANSI) has established a set of
industry standards for SQL. 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.

22 Informix Guide to SQL: Syntax


Informix Welcomes Your Comments

Informix Welcomes Your Comments


Let us know what you like or dislike about our manuals. To help us with
future versions of our manuals, we want to know about any corrections or
clarifications that you would find useful. Include the following information:

■ The name and version of the manual that you are using
■ Any comments that you have about the manual
■ Your name, address, and phone number

Send electronic mail to us at the following address:

doc@[Link]

The doc alias is reserved exclusively for reporting errors and omissions in our
documentation.

We appreciate your suggestions.

Introduction 23
Chapter

Overview of SQL Syntax


1
In This Chapter . . . . . . . . . . . . . . . . . . . . 1-3
How to Enter SQL Statements . . . . . . . . . . . . . . . 1-4
How to Enter SQL Comments . . . . . . . . . . . . . . . 1-6
Categories of SQL Statements . . . . . . . . . . . . . . . 1-9
ANSI Compliance and Extensions . . . . . . . . . . . . . 1-13
1-2 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 Starting Page Scope

“How to Enter 1-4 This section shows how to use the


SQL Statements” statement diagrams and descriptions to
enter SQL statements correctly.

“How to Enter 1-6 This section shows how to enter


SQL Comments” comments for SQL statements.

“Categories of SQL 1-9 This section lists SQL statements by


Statements” functional category.

“ANSI 1-13 This section lists SQL statements by


Compliance and degree of ANSI compliance.
Extensions”

Overview of SQL Syntax 1-3


How to Enter SQL Statements

How to Enter SQL Statements


The purpose of the statement descriptions in this manual is to help you to
enter SQL statements successfully. Each statement description includes the
following information:

■ A brief introduction that explains the purpose of the statement


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

If a statement consists of multiple clauses, the statement description provides


the same set of information for each clause.

Each statement description concludes with references to related information


in this manual and 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 14 of the Introduction. This section is the
key to understanding the syntax diagrams in the statement descriptions.

The Syntax Conventions section explains the elements that can appear in a
syntax diagram and the paths that connect the elements to each other. This
section also includes a sample syntax diagram that illustrates the major
elements of all syntax diagrams. The narrative that follows the sample
diagram shows how to read the diagram in order to enter the statement
successfully.

1-4 Informix Guide to SQL: Syntax


How to Enter SQL Statements

When a syntax diagram within a statement description includes input


parameters, the syntax diagram is followed by a syntax table that shows how
to enter the parameters without generating errors. Each syntax table includes
the following columns:

■ The Elements column lists the name of each parameter as it appears


in the syntax diagram.
■ The Purpose column briefly states the purpose of the parameter. If
the parameter has a default value, it is listed in this column.
■ The Restrictions column summarizes the restrictions on the
parameter, such as acceptable ranges of values.
■ The Syntax column points to the SQL segment that gives the detailed
syntax for the parameter.

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 particular 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 “Sample-Code Conventions” on page 19 of the Introduction.

Overview of SQL Syntax 1-5


How to Enter SQL Comments

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

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

The following table shows the SQL comment symbols that you can enter in
your code. A Y in a column signifies that you can use the symbol with the
product or database type named in the column heading. An N in a column
signifies that you cannot use the symbol with the product or database type
that the column heading names.

1-6 Informix Guide to SQL: Syntax


How to Enter SQL Comments

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

double Y Y Y Y Y The double dash precedes the


dash comment. The double dash can
(--) comment only a single line. To
comment more than one line, you must
put the double dash at the beginning of
each comment line.

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


({}) precedes the comment, and the }
follows the comment. You can use
braces for single-line comments or for
multiple-line comments. Comments
cannot be nested.

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

■ The double dash (--) complies with the ANSI SQL standard.
■ Braces ({}) are an Informix extension to the standard.

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


ter 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 Informix Guide to SQL: Tutorial. For
information on how to create and modify command files with the SQL editor
or a system editor in DB-Access, see the DB-Access User’s Manual. ♦

SPL You can use either comment symbol in any line of an SPL routine. See the
discussion of how to comment and document an SPL routine in the Informix
Guide to SQL: Tutorial. ♦

Overview of SQL Syntax 1-7


How to Enter SQL Comments

E/C
In ESQL/C, you can use the double dash (--) to comment SQL statements. For
further information on the use of SQL comment symbols and language-
specific comment symbols in ESQL/C programs, see the Informix ESQL/C
Programmer’s Manual. ♦

Examples of SQL Comment Symbols


Some simple examples can help to illustrate the different ways to use the SQL
comment symbols.

Examples of the Double-Dash Symbol


The following example shows the use of the double dash (--) to comment an
SQL statement. In this example, the comment appears on the same line as the
statement.
SELECT * FROM customer -- Selects all columns and rows

In the following example, the user enters the same SQL statement and the
same comment as in the preceding example, but the user places the comment
on a line by itself:
SELECT * FROM customer
-- Selects all columns and rows

In the following example, the user enters the same SQL statement as in the
preceding example but now enters a multiple-line comment:
SELECT * FROM customer
-- Selects all columns and rows
-- from the customer table

DB Examples of the Braces Symbols


SPL The following example shows the use of braces ({}) to comment an SQL
statement. In this example, the comment appears on the same line as the
statement.
SELECT * FROM customer {Selects all columns and rows}

1-8 Informix Guide to SQL: Syntax


Categories of SQL Statements

In the following example, the user enters the same SQL statement and the
same comment as in the preceding example but places the comment on a line
by itself:
SELECT * FROM customer
{Selects all columns and rows}

In the following example, the user enters the same SQL statement as in the
preceding example but enters a multiple-line comment:
SELECT * FROM customer
{Selects all columns and rows
from the customer table}

GLS Non-ASCII Characters in SQL Comments


You can enter non-ASCII characters (including multibyte characters) in SQL
comments if your locale supports a code set with the non-ASCII characters.
For further information on the GLS aspects of SQL comments, see the Informix
Guide to GLS Functionality.

Categories of SQL Statements


SQL statements are divided into the following categories:

■ Data definition statements


■ Data manipulation statements
■ Cursor manipulation statements
■ Cursor optimization statements
■ Dynamic management statements
■ Data access statements
■ Data integrity statements
■ Optimization statements
■ Routine Definition statements
■ Auxiliary statements
■ Client/server connection statements
■ Optical subsystem statements

The specific statements for each category are as follows.

Overview of SQL Syntax 1-9


Categories of SQL Statements

Data Definition Statements


ALTER FRAGMENT CREATE TEMPORARY TABLE
ALTER FUNCTION CREATE TRIGGER
ALTER INDEX CREATE VIEW
ALTER PROCEDURE DATABASE
ALTER ROUTINE DROP AGGREGATE
ALTER TABLE DROP CAST
CLOSE DATABASE DROP DATABASE
CREATE AGGREGATE DROP INDEX
CREATE CAST DROP PROCEDURE
CREATE DATABASE DROP ROLE
CREATE DISTINCT TYPE DROP ROW TYPE
CREATE EXTERNAL TABLE DROP SYNONYM
CREATE INDEX DROP TABLE
CREATE OPAQUE TYPE DROP TRIGGER
CREATE PROCEDURE DROP VIEW
CREATE PROCEDURE FROM RENAME COLUMN
CREATE ROLE RENAME DATABASE
CREATE ROW TYPE RENAME TABLE
CREATE SCHEMA TRUNCATE
CREATE SYNONYM
CREATE TABLE

Data Manipulation Statements


DELETE SELECT
INSERT UNLOAD
LOAD UPDATE

Cursor Manipulation Statements


CLOSE FREE
DECLARE OPEN
FETCH PUT
FLUSH SET AUTOFREE

1-10 Informix Guide to SQL: Syntax


Categories of SQL Statements

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 PREPARE
DEALLOCATE ROW SET DEFERRED_PREPARE
DESCRIBE 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

Optimization Statements
SET EXPLAIN SET SCHEDULE LEVEL
SET OPTIMIZATION SET STATEMENT CACHE
SET PDQPRIORITY UPDATE STATISTICS
SET RESIDENCY

Overview of SQL Syntax 1-11


Categories of SQL Statements

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 DATASKIP
OUTPUT WHENEVER
GET DIAGNOSTICS

Client/Server Connection Statements


CONNECT SET CONNECTION
DISCONNECT

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 “Guide to the Optical
Subsystem.”

1-12 Informix Guide to SQL: Syntax


ANSI Compliance and Extensions

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 SET SESSION AUTHORIZATION
COMMIT WORK SET TRANSACTION
ROLLBACK WORK

ANSI-Compliant Statements with Informix Extensions


CREATE SCHEMA AUTHORIZATION GRANT
CREATE TABLE INSERT
CREATE TEMPORARY TABLE OPEN
CREATE VIEW SELECT
DECLARE SET CONNECTION
DELETE UPDATE
EXECUTE WHENEVER
FETCH

Overview of SQL Syntax 1-13


ANSI Compliance and Extensions

Statements That Are Extensions to the ANSI Standard


ALLOCATE DESCRIPTOR GRANT FRAGMENT
ALTER FRAGMENT INFO
ALTER FUNCTION LOAD
ALTER INDEX LOCK TABLE
ALTER OPTICAL CLUSTER OUTPUT
ALTER PROCEDURE PREPARE
ALTER ROUTINE PUT
ALTER TABLE RELEASE
BEGIN WORK RENAME COLUMN
CLOSE DATABASE RENAME DATABASE
CONNECT RENAME TABLE
CREATE AGGREGATE RESERVE
CREATE DATABASE REVOKE
CREATE EXTERNAL TABLE REVOKE FRAGMENT
CREATE INDEX SET AUTOFREE
CREATE OPTICAL CLUSTER SET DATABASE OBJECT MODE
CREATE PROCEDURE SET DATASKIP
CREATE PROCEDURE FROM SET DEBUG FILE TO
CREATE ROLE SET DEFERRED_PREPARE
CREATE SYNONYM SET DESCRIPTOR
CREATE TRIGGER SET EXPLAIN
DATABASE SET ISOLATION
DEALLOCATE DESCRIPTOR SET LOCK MODE
DESCRIBE SET LOG
DISCONNECT SET MOUNTING TIMEOUT
DROP AGGREGATE SET OPTIMIZATION
DROP DATABASE SET PDQPRIORITY
DROP INDEX SET PLOAD FILE
DROP OPTICAL CLUSTER SET RESIDENCY
DROP PROCEDURE SET ROLE
DROP ROLE SET SCHEDULE LEVEL
DROP SYNONYM SET STATEMENT CACHE
DROP TABLE SET TRANSACTION
DROP TRIGGER SET TRANSACTION MODE
DROP VIEW START VIOLATIONS TABLE
EXECUTE IMMEDIATE STOP VIOLATIONS TABLE
EXECUTE PROCEDURE TRUNCATE
FLUSH UNLOAD
FREE UNLOCK TABLE
GET DESCRIPTOR UPDATE STATISTICS
GET DIAGNOSTICS

1-14 Informix Guide to SQL: Syntax


Chapter

SQL Statements
2
In This Chapter . . . . . . . . . . . . . . . . . . . . 2-5
ALLOCATE COLLECTION . . . . . . . . . . . . . . 2-6
ALLOCATE DESCRIPTOR . . . . . . . . . . . . . . . 2-8
ALLOCATE ROW . . . . . . . . . . . . . . . . . . 2-10
ALTER FRAGMENT . . . . . . . . . . . . . . . . . 2-12
ALTER FUNCTION . . . . . . . . . . . . . . . . . 2-41
ALTER INDEX . . . . . . . . . . . . . . . . . . . 2-44
ALTER PROCEDURE . . . . . . . . . . . . . . . . 2-48
ALTER ROUTINE . . . . . . . . . . . . . . . . . . 2-51
ALTER TABLE . . . . . . . . . . . . . . . . . . . 2-55
BEGIN WORK . . . . . . . . . . . . . . . . . . . 2-91
CLOSE. . . . . . . . . . . . . . . . . . . . . . 2-94
CLOSE DATABASE . . . . . . . . . . . . . . . . . 2-98
COMMIT WORK . . . . . . . . . . . . . . . . . . 2-100
CONNECT . . . . . . . . . . . . . . . . . . . . 2-103
CREATE AGGREGATE . . . . . . . . . . . . . . . . 2-115
CREATE CAST . . . . . . . . . . . . . . . . . . . 2-119
CREATE DATABASE. . . . . . . . . . . . . . . . . 2-124
CREATE DISTINCT TYPE . . . . . . . . . . . . . . . 2-127
CREATE EXTERNAL TABLE . . . . . . . . . . . . . . 2-131
CREATE FUNCTION . . . . . . . . . . . . . . . . 2-146
CREATE FUNCTION FROM . . . . . . . . . . . . . . 2-155
CREATE INDEX . . . . . . . . . . . . . . . . . . 2-157
CREATE OPAQUE TYPE . . . . . . . . . . . . . . . 2-186
CREATE OPCLASS . . . . . . . . . . . . . . . . . 2-193
CREATE PROCEDURE . . . . . . . . . . . . . . . . 2-199
CREATE PROCEDURE FROM . . . . . . . . . . . . . 2-209
CREATE ROLE . . . . . . . . . . . . . . . . . . . 2-212
CREATE ROUTINE FROM . . . . . . . . . . . . . . . 2-214
CREATE ROW TYPE . . . . . . . . . . . . . . . . . 2-216
CREATE SCHEMA . . . . . . . . . . . . . . . . . 2-222
CREATE SYNONYM . . . . . . . . . . . . . . . . . 2-226
CREATE TABLE . . . . . . . . . . . . . . . . . . 2-230
CREATE Temporary TABLE . . . . . . . . . . . . . . 2-286
CREATE TRIGGER . . . . . . . . . . . . . . . . . 2-296
CREATE VIEW . . . . . . . . . . . . . . . . . . . 2-334
DATABASE . . . . . . . . . . . . . . . . . . . . 2-341
DEALLOCATE COLLECTION . . . . . . . . . . . . . 2-343
DEALLOCATE DESCRIPTOR . . . . . . . . . . . . . . 2-345
DEALLOCATE ROW . . . . . . . . . . . . . . . . . 2-347
DECLARE . . . . . . . . . . . . . . . . . . . . 2-349
DELETE . . . . . . . . . . . . . . . . . . . . . 2-373
DESCRIBE . . . . . . . . . . . . . . . . . . . . 2-382
DISCONNECT . . . . . . . . . . . . . . . . . . . 2-389
DROP AGGREGATE . . . . . . . . . . . . . . . . . 2-393
DROP CAST . . . . . . . . . . . . . . . . . . . . 2-395
DROP DATABASE. . . . . . . . . . . . . . . . . . 2-397
DROP FUNCTION . . . . . . . . . . . . . . . . . 2-399
DROP INDEX . . . . . . . . . . . . . . . . . . . 2-401
DROP OPCLASS . . . . . . . . . . . . . . . . . . 2-403
DROP PROCEDURE . . . . . . . . . . . . . . . . . 2-404
DROP ROLE . . . . . . . . . . . . . . . . . . . . 2-407
DROP ROUTINE . . . . . . . . . . . . . . . . . . 2-408
DROP ROW TYPE . . . . . . . . . . . . . . . . . . 2-410
DROP SYNONYM . . . . . . . . . . . . . . . . . . 2-412
DROP TABLE . . . . . . . . . . . . . . . . . . . 2-413
DROP TRIGGER . . . . . . . . . . . . . . . . . . 2-417
DROP TYPE . . . . . . . . . . . . . . . . . . . . 2-418
DROP VIEW . . . . . . . . . . . . . . . . . . . . 2-420
EXECUTE . . . . . . . . . . . . . . . . . . . . . 2-422
EXECUTE FUNCTION . . . . . . . . . . . . . . . . 2-434
EXECUTE IMMEDIATE . . . . . . . . . . . . . . . . 2-441
EXECUTE PROCEDURE . . . . . . . . . . . . . . . 2-444

2-2 Informix Guide to SQL: Syntax


FETCH . . . . . . . . . . . . . . . . . . . . . . 2-455
FLUSH . . . . . . . . . . . . . . . . . . . . . . 2-469
FREE . . . . . . . . . . . . . . . . . . . . . . . 2-472
GET DESCRIPTOR . . . . . . . . . . . . . . . . . . 2-475
GET DIAGNOSTICS . . . . . . . . . . . . . . . . . 2-483
GRANT . . . . . . . . . . . . . . . . . . . . . . 2-500
GRANT FRAGMENT . . . . . . . . . . . . . . . . . 2-523
INFO . . . . . . . . . . . . . . . . . . . . . . . 2-532
INSERT . . . . . . . . . . . . . . . . . . . . . . 2-535
LOAD . . . . . . . . . . . . . . . . . . . . . . 2-553
LOCK TABLE . . . . . . . . . . . . . . . . . . . . 2-563
OPEN. . . . . . . . . . . . . . . . . . . . . . . 2-566
OUTPUT . . . . . . . . . . . . . . . . . . . . . 2-577
PREPARE . . . . . . . . . . . . . . . . . . . . . 2-579
PUT . . . . . . . . . . . . . . . . . . . . . . . 2-593
RENAME COLUMN . . . . . . . . . . . . . . . . . 2-604
RENAME DATABASE . . . . . . . . . . . . . . . . . 2-606
RENAME TABLE. . . . . . . . . . . . . . . . . . . 2-607
REVOKE . . . . . . . . . . . . . . . . . . . . . 2-610
REVOKE FRAGMENT . . . . . . . . . . . . . . . . . 2-628
ROLLBACK WORK . . . . . . . . . . . . . . . . . . 2-632
SELECT . . . . . . . . . . . . . . . . . . . . . . 2-634
SET AUTOFREE . . . . . . . . . . . . . . . . . . . 2-691
SET CONNECTION. . . . . . . . . . . . . . . . . . 2-694
SET Database Object Mode . . . . . . . . . . . . . . . 2-700
SET DATASKIP . . . . . . . . . . . . . . . . . . . 2-709
SET DEBUG FILE TO . . . . . . . . . . . . . . . . . 2-712
SET DEFERRED_PREPARE . . . . . . . . . . . . . . . 2-715
SET DESCRIPTOR . . . . . . . . . . . . . . . . . . 2-719
SET EXPLAIN . . . . . . . . . . . . . . . . . . . . 2-730
SET ISOLATION . . . . . . . . . . . . . . . . . . . 2-736
SET LOCK MODE . . . . . . . . . . . . . . . . . . 2-742
SET LOG . . . . . . . . . . . . . . . . . . . . . 2-745
SET OPTIMIZATION . . . . . . . . . . . . . . . . . 2-747
SET PDQPRIORITY . . . . . . . . . . . . . . . . . . 2-751
SET PLOAD FILE . . . . . . . . . . . . . . . . . . 2-755

SQL Statements 2-3


SET Residency . . . . . . . . . . . . . . . . . . . 2-756
SET ROLE. . . . . . . . . . . . . . . . . . . . . 2-758
SET SCHEDULE LEVEL . . . . . . . . . . . . . . . . . . 2-760
SET SESSION AUTHORIZATION . . . . . . . . . . . . 2-761
SET STATEMENT CACHE . . . . . . . . . . . . . . . 2-764
SET TRANSACTION . . . . . . . . . . . . . . . . . 2-768
SET Transaction Mode . . . . . . . . . . . . . . . . 2-774
START VIOLATIONS TABLE . . . . . . . . . . . . . . 2-778
STOP VIOLATIONS TABLE . . . . . . . . . . . . . . 2-800
TRUNCATE . . . . . . . . . . . . . . . . . . . . 2-802
UNLOAD . . . . . . . . . . . . . . . . . . . . . 2-805
UNLOCK TABLE . . . . . . . . . . . . . . . . . . 2-813
UPDATE . . . . . . . . . . . . . . . . . . . . . 2-815
UPDATE STATISTICS . . . . . . . . . . . . . . . . 2-835
WHENEVER. . . . . . . . . . . . . . . . . . . . 2-848

2-4 Informix Guide to SQL: Syntax


In This Chapter
This chapter gives comprehensive reference descriptions of SQL statements.
The statement descriptions appear in alphabetical order. For an explanation
of the structure of statement descriptions, see Chapter 1, “Overview of SQL
Syntax.”

SQL Statements 2-5


ALLOCATE COLLECTION

+ ALLOCATE COLLECTION
IDS
Use the ALLOCATE COLLECTION statement to allocate memory for a
E/C collection variable.

Use this statement with ESQL/C.

Syntax

ALLOCATE COLLECTION variable

Element Purpose Restrictions Syntax


variable Name that identifies a typed or The variable must be the name Name must conform
untyped collection variable for of an unallocated ESQL/C to language-specific
which to allocate memory collection host variable. rules for variable
names.

Usage
The ALLOCATE COLLECTION statement allocates memory for a variable that
stores collection data. To create a collection variable for an ESQL/C program,
perform the following steps:

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 ([Link]) 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. Once you free the collection variable with the DEALLOCATE
COLLECTION statement, you can reuse the collection variable.

2-6 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, see the Informix ESQL/C


Programmer’s Manual.

SQL Statements 2-7


ALLOCATE DESCRIPTOR

+ ALLOCATE DESCRIPTOR
E/C
Use the ALLOCATE DESCRIPTOR statement to allocate memory for a system-
descriptor area. This statement creates a place in memory to hold information
that a DESCRIBE statement obtains or to hold information about the WHERE
clause of a statement.

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. Quoted String,
system-descriptor area String must represent the name p. 4-260
of an unallocated system-
descriptor area.
descriptor_var Host-variable name that Variable must contain the name Name must conform
identifies a system-descriptor of an unallocated system- to language-specific
area descriptor area. rules for variable
names.
items Number of item descriptors in Value must be unsigned Literal Number,
the system-descriptor area INTEGER greater than zero. p. 4-237
The default value is 100.
items_var Host variable that contains the Data type must be INTEGER or Name must conform
number of items SMALLINT. to language-specific
rules for variable
names.

2-8 Informix Guide to SQL: Syntax


ALLOCATE DESCRIPTOR

Usage
The ALLOCATE DESCRIPTOR statement creates a system-descriptor area. A
system-descriptor area contains one or more fields called item descriptors.
Each item descriptor holds a data value that the database server can receive
or send. The item descriptors also contain information about the data such as
type, length, scale, precision, and nullability.
If the name that you assign to a system-descriptor area matches the name of
an existing system-descriptor area, the database server returns an error. If
you free the descriptor with the DEALLOCATE DESCRIPTOR statement, you
can reuse the descriptor.
A system-descriptor area holds information that a DESCRIBE...USING SQL
DESCRIPTOR statement obtains or it holds information about the WHERE
clause of a dynamically executed statement.

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


ESQL/C Programmer’s Manual.

SQL Statements 2-9


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 that identifies a typed or The variable must be an unallo- Name must conform
untyped row variable for which cated ESQL/C row host to language-specific
to allocate memory variable. rules for variable
names.

Usage
The ALLOCATE ROW statement allocates memory for a variable that stores
row-type data. To create a row variable, perform the following steps in your
ESQL/C program:

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 ([Link]) 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-10 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 types, see the Informix ESQL/C Programmer’s


Manual.

SQL Statements 2-11


ALTER FRAGMENT

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

Syntax

ATTACH
ALTER FRAGMENT ON TABLE surviving_table Clause
p. 2-15

IDS DETACH
Clause
p. 2-25
INDEX surviving_index
INIT
Clause
p. 2-27
IDS

ADD
Clause
p. 2-35

DROP
Clause
p. 2-37

MODIFY
Clause
p. 2-38

Element Purpose Restrictions Syntax


surviving_index Index on which you execute the The index must exist at the time Database Object
ALTER FRAGMENT statement you execute the statement. Name, p. 4-50
surviving_table Table on which you execute the The table must exist at the time Database Object
ALTER FRAGMENT statement you execute the statement. Name, p. 4-50
For more information, see
“Restrictions on When You Can
Use the ALTER FRAGMENT
Statement” on page 2-14.

2-12 Informix Guide to SQL: Syntax


ALTER FRAGMENT

Usage
The clauses of the ALTER FRAGMENT statement let you perform the
following tasks.

Clause Purpose

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

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.

The ALTER FRAGMENT statement applies only to table or index fragments


that are located at the current site (or cluster, for Extended Parallel Server).
No remote information is accessed or updated.

Warning: This statement can cause indexes to be dropped and rebuilt. Before under-
taking alter operations, check corresponding sections in your “Performance Guide”
to review effects and strategies

General Privileges
You must have the Alter or the DBA privilege to change the fragmentation
strategy of a table. You must have the Index or the DBA privilege to alter the
fragmentation strategy of an index.

SQL Statements 2-13


ALTER FRAGMENT

Restrictions on When You Can Use the ALTER FRAGMENT Statement


You cannot use the ALTER FRAGMENT statement on a temporary table, an
external table, or a view.

If your table or index is not already fragmented, the only clauses available to
you are INIT and ATTACH.

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

XPS You cannot use the ALTER FRAGMENT statement on a generalized-key (GK)
index. Also, you cannot use the ALTER FRAGMENT statement on any table
that has a dependent GK index defined on it. In addition, you cannot use this
statement on a table that has range fragmentation.

If the surviving_table has hash fragmentation, the only clauses available are
ATTACH and INIT. ♦

How Is the ALTER FRAGMENT Statement Executed?


If your database uses logging, the ALTER FRAGMENT statement 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).

Making More 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 at 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
Backup and Restore Guide.

2-14 Informix Guide to SQL: Syntax


ALTER FRAGMENT

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.

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

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

ATTACH Back to ALTER FRAGMENT


Clause p. 2-12

,
ATTACH 1 surviving_table

consumed_table

AS expression

BEFORE dbspace

AFTER

1 AS REMAINDER

SQL Statements 2-15


ALTER FRAGMENT

Element Purpose Restrictions Syntax


consumed_table Table which loses its identity The table must exist at the time Database Object
and becomes part of the you execute the statement. Name, p. 4-50
surviving table The table cannot contain serial
columns.
The table cannot contain unique,
referential, or primary-key
constraints.
The table must be nonfrag-
mented (IDS only).
See also, “General Restrictions
for the ATTACH Clause” on
page 2-17.
dbspace Dbspace that specifies where The dbspace must exist at the Identifier, p. 4-205
the consumed table expression time you execute the statement.
occurs in the fragmentation list
With a hybrid-fragmented
table, dbspace identifies a set of
dbspaces (XPS only). See
“Altering Hybrid-Fragmented
Tables” on page 2-19.
expression Expression that defines which The expression element can Condition, p. 4-27,
rows are stored in a fragment contain only columns from the and Expression,
current table and only data p. 4-73
values from a single row.
No subqueries, user-defined
routines, aggregates, or refer-
ences to the fields of a row-type
column are allowed. In addition,
the current, date and/or time
built-in functions are not
allowed.
surviving_table Table that survives the The table must exist at the time Database Object
execution of ALTER FRAGMENT you execute the statement. Name, p. 4-50
The table cannot contain any
constraints.
See also, “General Restrictions
for the ATTACH Clause” on
page 2-17.

2-16 Informix Guide to SQL: Syntax


ALTER FRAGMENT

The ATTACH clause allows you to perform the following tasks:

■ Create 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-18.)
■ Attach one or more tables to a fragmented table
(See “Attaching a Table to a Fragmented Table” on page 2-19.)

Privileges
You must be the DBA or the owner of the tables that are involved to use the
ATTACH clause.

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 be identical in


structure to the surviving table; that is, all column definitions must match.
The number, names, data types, and relative position of the columns must be
identical.

IDS 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 “Usage-Type Options” on page 2-231.

You cannot use the ATTACH clause in certain situations. The attach operation
fails:

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

SQL Statements 2-17


ALTER FRAGMENT

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

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

2-18 Informix Guide to SQL: Syntax


ALTER FRAGMENT

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

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

If you know the name of the dbslice, but not any of the dbspaces that it
comprises, you can name the first dbspace in the dbslice by adding .1 to the
name of the dbslice. For example, if the dbslice were named dbsl1, you could
specify dbsl1.1.

SQL Statements 2-19


ALTER FRAGMENT

What Happens?
After the attach executes, all consumed tables no longer exist. Any
constraints (CHECK or NOT NULL) that were on the consumed tables also no
longer exist.

You must reference the records that were in the consumed tables through the
surviving table.

What Happens to Indexes?


In a logging database, when the attach executes, the database server extends
any attached index on the surviving table according to the new fragmen-
tation strategy of the surviving table. All rows in the consumed table are
subject to these automatically 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.

IDS In a nonlogging database, when the attach executes, the database server does
not extend indexes on the surviving table according to the new fragmen-
tation strategy of the surviving table. To extend the fragmentation strategy of
an attached index according to the new fragmentations strategy of the
surviving table, you must drop the index and recreate it on the surviving
table. ♦

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

2-20 Informix Guide to SQL: Syntax


ALTER FRAGMENT

XPS In Extended Parallel Server, BYTE and TEXT columns are stored in separate
fragments that are created for that purpose. If a table includes a BYTE or TEXT
column, the database server creates a separate, additional fragment in the
same dbspace as each regular table fragment. BYTE or TEXT columns are
stored in the separate fragment that is associated with the regular table
fragment where a given row resides.

When an attach occurs, BYTE and TEXT fragments of the consumed table
become part of the surviving table and continue to be associated with the
same rows and data fragments as they were before the attach. ♦

What Happens to Triggers?


When you attach tables, any triggers that are defined on the consumed table
no longer exist, and all rows in the consumed table are subject to the triggers
that are defined in the surviving table. That is, triggers on the surviving table
survive the ATTACH, but triggers on the consumed table are dropped.

No triggers are activated with the ATTACH clause, but subsequent data-
manipulation operations on the new rows can activate triggers.

What Happens to Views?


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

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.
However, when you attach two or more nonfragmented tables, the distri-
bution scheme can either be based on expression or round-robin.

SQL Statements 2-21


ALTER FRAGMENT

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.

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

2-22 Informix Guide to SQL: Syntax


ALTER FRAGMENT

Examples
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;

When you examine the sysfragments system catalog table after you alter the
fragment, you see that table cur_acct is fragmented by expression into three
dbspaces. For additional information about the sysfragments system catalog
table, see the Informix Guide to SQL: Reference.

SQL Statements 2-23


ALTER FRAGMENT

In addition to simple range rules, you can use the ATTACH clause to fragment
by expression with hash or arbitrary rules. For a discussion of all types of
expressions in an expression-based distribution scheme, see “FRAGMENT
BY Clause for Tables” on page 2-30.

Warning: When you specify a date value in a fragment expression, make sure to
specify 4 digits instead of 2 digits for the year. When you specify a 4-digit year, the
DBCENTURY environment variable has no effect on the distribution scheme. When
you specify a 2-digit year, the DBCENTURY environment variable can affect the
distribution scheme and can produce unpredictable results. For more information on
the DBCENTURY environment variable, see the “Informix Guide to SQL: Reference.”

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 for a new month is originally loaded from an external source. The
data is distributed evenly across the name coservers on which the sales_info
table is defined, using a system-defined hash function on the same column:
CREATE TABLE jan_97 (order_num int, sale_date date, ...)
FRAGMENT BY HASH (order_num) IN sales_slice_9701
INSERT INTO jan_97 SELECT (...) FROM ...

Once the data is loaded, you can attach the new table to sales_info. You can
issue the following ALTER FRAGMENT statement to attach the new table:
ALTER FRAGMENT ON TABLE sales_info ATTACH jan_97
AS sale_date >= '01/01/1997' AND sale_date < '02/01/1997'

2-24 Informix Guide to SQL: Syntax


ALTER FRAGMENT

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

DETACH Back to ALTER FRAGMENT


Clause p. 2-12

DETACH dbspace new_table

Element Purpose Restrictions Syntax


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

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

The new table that results from the execution of the DETACH clause does not
inherit any privileges from the original table. Instead this table has the
default privileges for any new table. For further information on default table-
level privileges, see the GRANT statement on “Table-Level Privileges” on
page 2-505.

SQL Statements 2-25


ALTER FRAGMENT

Restrictions
The DETACH clause cannot be applied to a table if that table is the parent of
a referential constraint or if a rowid column is defined on the table.

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

Detach That Results in a Non-fragmented 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 will be 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, you specify the dbslice to be detached by
naming any dbspace in that slice.

2-26 Informix Guide to SQL: Syntax


ALTER FRAGMENT

Consider the sales_info table discussed in the “Hybrid Fragmentation Distri-


bution Scheme” on page 2-24. Once the January 1997 data is available in the
sales_info table, 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.

INIT Clause
The INIT clause allows you to:

■ move a nonfragmented table from one dbspace to another dbspace.


■ convert a fragmented table to a nonfragmented table.
■ fragment an existing table that is not fragmented without redefining
the table.
■ convert an existing 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. ♦
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
exits 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.

SQL Statements 2-27


ALTER FRAGMENT

INIT Back to ALTER FRAGMENT


Clause p. 2-12

FRAGMENT BY
INIT Clause for Tables
p. 2-30
IDS WITH ROWIDS
FRAGMENT BY
IDS Clause for Indexes
p. 2-33

IN dbspace

XPS

IN dbslice

Element Purpose Restrictions Syntax


dbslice Dbslice that contains the The dbslice must exist at the Identifier, p. 4-205
fragmented information time you execute the statement.
dbspace Dbspace that contains the The dbspace must exist at the Identifier, p. 4-205
fragmented information time you execute the statement.

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

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

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

2-28 Informix Guide to SQL: Syntax


ALTER FRAGMENT

IDS WITH ROWIDS Option


Nonfragmented tables contain a pseudocolumn called the rowid column.
Fragmented tables do not contain this column unless it is explicitly created.

Use the WITH ROWIDS option to add a new column called the rowid column.
The database server assigns a unique number to each row that remains stable
for the existence of the row. The database server creates an index that it uses
to find the physical location of the row. Each row contains an additional
4 bytes to store the rowid column after you add the WITH ROWIDS option.
Important: Informix recommends that you use primary keys, rather than the rowid
column, as an access method.

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 (that is, to rid the table of any fragmentation strategy),
all attached indexes become nonfragmented indexes. In addition, constraints
that do not use existing user indexes (detached indexes) become nonfrag-
mented indexes. All newly nonfragmented indexes exist in the same dbspace
as the new nonfragmented table.

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


nonfragmented table, the fragmentation strategy of detached indexes (and
constraints that use detached indexes) is not affected.

SQL Statements 2-29


ALTER FRAGMENT

FRAGMENT BY Clause for Tables


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

FRAGMENT BY Back to INIT Clause


Clause for Tables p. 2-27

,
FRAGMENT BY ROUND ROBIN IN dbspace , dbspace

XPS
IN dbslice
,
EXPRESSION expression IN dbspace , expression IN dbspace

REMAINDER

XPS
, ,
HASH ( column ) IN dbspace , dbspace

IN dbslice
,
HYBRID ( column )

,
EXPRESSION expression IN dbslice , expression IN dbslice

REMAINDER

dbspace dbspace
, ,
( dbspace ) ( dbspace )

2-30 Informix Guide to SQL: Syntax


ALTER FRAGMENT

Element Purpose Restrictions Syntax


column Name of the column or columns The column must exist. Identifier, p. 4-205
on which you want to apply the
fragmentation strategy
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
dbslice Dbslice that contains the table The dbslice must be defined. Identifier, p. 4-205
fragment
dbspace Dbspace that contains the table You must specify at least two Identifier, p. 4-205
fragment dbspaces. You can specify a
maximum of 2,048 dbspaces.
expression Expression that defines a table Each fragment expression can Condition, p. 4-27,
fragment using a range, hash, or contain only columns from the and
arbitrary rule current table and only data Expression, p. 4-73
values from a single row.
No subqueries, user-defined
routines, aggregates, or refer-
ences to the fields of a row-type
column are allowed. In
addition, the current, date
and/or time built-in functions
are not allowed.

For more information on the available fragmentation strategies, see the


“FRAGMENT BY Clause” on page 2-259.

SQL Statements 2-31


ALTER FRAGMENT

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 >= 0in 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


You can use the INIT clause to define a fragmentation strategy on a
nonfragmented table. It does not matter whether the table was created with
a storage option.

IDS When you use the INIT clause to fragment an existing nonfragmented table,
all indexes on the table become fragmented in the same way as the table. ♦

XPS When you use the INIT clause to fragment an existing nonfragmented table,
indexes retain their existing fragmentation strategy.

The following example shows the original table definition as well as how to
use the ALTER FRAGMENT statement to fragment the table:
CREATE TABLE balances (col1 int, col2 int) IN dbsp1;

ALTER FRAGMENT ON TABLE balances INIT


FRAGMENT BY EXPRESSION
col1 <= 500 IN dbsp1,
col1 > 500 and col1 <=1000 IN dbsp2,
REMAINDER IN dbsp3;

2-32 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. 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.

Use the FRAGMENT BY clause for indexes to define the expression-based


distribution scheme.

FRAGMENT BY Back to INIT Clause


Clause for Indexes p. 2-27
,
FRAGMENT BY EXPRESSION expression IN dbspace , expression IN dbspace
, REMAINDER IN dbspace

Element Purpose Restrictions Syntax


dbspace Dbspace that contains the You must specify at least two Identifier, p. 4-205
fragmented information dbspaces. You can specify a
maximum of 2,048 dbspaces.
expression Expression that defines an index Each fragment expression can Condition, p. 4-27,
fragment by using a range, hash, contain only columns from the and
or arbitrary rule current table and only data values Expression, p. 4-73
from a single row.
No subqueries, user-defined
routines, aggregates, or references
to the fields of a row-type column
are allowed. In addition, the
current, date and/or time built-in
functions are not allowed.

SQL Statements 2-33


ALTER FRAGMENT

Fragmenting Unique and System Indexes


You can fragment unique indexes only if the table uses an expression-based
distribution scheme. The columns that are 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, you can use the INIT clause on the index to detach it from the table
fragmentation strategy and fragment it separately.

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.

2-34 Informix Guide to SQL: Syntax


ALTER FRAGMENT

IDS ADD Clause


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

ADD Back to ALTER FRAGMENT


Clause p. 2-12

ADD new_dbspace

expression IN new_dbspace

BEFORE existing_dbspace

AFTER

REMAINDER IN new_dbspace

Element Purpose Restrictions Syntax


existing_dbspace Name of a dbspace in an The dbspace must exist at the Identifier, p. 4-205
existing fragmentation list time you execute the statement.
expression Expression that defines the The expression can contain Condition, p. 4-27,
added fragment only columns from the current and
table and only data values from Expression, p. 4-73
a single row.
No subqueries, user-defined
routines, aggregates, or refer-
ences to the fields of a row-type
column are allowed. In
addition, the current, date
and/or time built-in functions
are not allowed.
new_dbspace Name of dbspace to be added to The dbspace must exist at the Identifier, p. 4-205
the fragmentation scheme time you execute the statement.

SQL Statements 2-35


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 title)
FRAGMENT BY ROUND ROBIN in dbsp1, dbsp4;

To add another dbspace, use the ADD clause, as shown in the following
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 shuffle records from some 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 following example shows the original expression
definition:
.
.
.
FRAGMENT BY EXPRESSION
c1 < 100 IN dbsp1,
c1 >= 100 and c1 < 200 IN dbsp2,
REMAINDER IN dbsp3;

If you want to add another fragment to the fragmentation list and have this
fragment hold rows between 200 and 300, use the following ALTER
FRAGMENT statement:

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.

2-36 Informix Guide to SQL: Syntax


ALTER FRAGMENT

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.

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 may 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-12

DROP dbspace

Element Purpose Restrictions Syntax


dbspace Name of the dbspace that The dbspace must exist at the Identifier, p. 4-205
contains the dropped fragment time you 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.

SQL Statements 2-37


ALTER FRAGMENT

When you drop a fragment from a dbspace, the underlying dbspace is not
affected. Only the fragment data within that dbspace is affected. When you
drop a fragment all the records located in the fragment move to another
fragment. The destination fragment might not have enough space for the
additional records. When this happens, follow one of the procedures that are
listed in “Making More Space” on page 2-14 to increase your space, and retry
the procedure.

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

,
MODIFY mod_dbspace TO expression IN new_dbspace

1 REMAINDER IN new_dbspace

2-38 Informix Guide to SQL: Syntax


ALTER FRAGMENT

Element Purpose Restrictions Syntax


expression Modified range, hash, or The fragment expression can Condition, p. 4-27,
arbitrary expression contain only columns from the and
current table and only data Expression, p. 4-73
values from a single row.
No subqueries, user-defined
routines, aggregates, or refer-
ences to the fields of a row-type
column are allowed. In
addition, the current, date
and/or time built-in functions
are not allowed.
mod_ dbspace Modified dbspace The dbspace must exist when Identifier, p. 4-205
you execute the statement.
new_dbspace Dbspace that contains the The dbspace must exist when Identifier, p. 4-205
modified information you execute the statement.

General Usage
When you use the MODIFY clause, the underlying dbspaces are not affected.
Only the fragment data within the dbspaces is affected.

You cannot change a REMAINDER fragment into a nonremainder fragment if


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

Changing the Expression in an Existing Dbspace


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.

The following example shows how to use the MODIFY clause to change an
existing expression:
ALTER FRAGMENT ON TABLE cust_acct
MODIFY dbsp1 to acct_num < 65 IN dbsp1

SQL Statements 2-39


ALTER FRAGMENT

Moving an Expression from One Dbspace to Another


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.

The following example shows how to use the MODIFY clause to move an
expression from one dbspace to another:
ALTER FRAGMENT ON TABLE cust_acct
MODIFY dbsp1 to acct_num < 35 in dbsp2

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

Changing the Expression and Moving it to a New Dbspace


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

What Happens to Indexes?


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 Informix Guide to


Database Design and Implementation.

For information on how to maximize performance when you make fragment


modifications, see your Performance Guide.

2-40 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

Routine
ALTER FUNCTION function WITH ( ADD Modifier )
p. 4-274
MODIFY
,
DROP
parameter_type

Ext Shared-
SPECIFIC FUNCTION Specific Name Object
p. 4-296 MODIFY EXTERNAL NAME Filename
p. 4-292

Element Purpose Restrictions Syntax


function Name of the user-defined The function must exist (that is, be Database Object
function to modify registered) in the database. Name, p. 4-50
If the name does not uniquely
identify a function, you must enter
one or more appropriate values for
parameter_type.
parameter_type Data type of the parameter The data type (or list of data types) Identifier, p. 4-205
must be the same types (and
specified in the same order) as those
specified in the CREATE
FUNCTION statement when the
function was created.

SQL Statements 2-41


ALTER FUNCTION

Usage
The ALTER FUNCTION statement allows you to modify a user-defined
function to tune its performance. With this statement you can modify charac-
teristics that control how the function executes. You can also add or replace
related UDRs that provide alternatives for the optimizer, which can improve
performance.

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

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

Keywords That Introduce Modifications


Use the following keywords to introduce the items in the user-defined
function that you want to modify.

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 Introduces a new location for the executable file


NAME
(for external functions only)

WITH Introduces all modifications

2-42 Informix Guide to SQL: Syntax


ALTER FUNCTION

If the routine modifier is a Boolean value, MODIFY sets the value to be T (that
is, it is the equivalent of using the keyword ADD to add the routine modifier).
For example, both of the following statements alter the func1 function so that
it can be executed in parallel in the context of a parallelizable data query
statement.
ALTER FUNCTION func1 WITH (MODIFY PARALLELIZABLE)

ALTER FUNCTION func1 WITH (ADD PARALLELIZABLE)

For a related example, see “Altering Routine Modifiers Example” on


page 2-54.

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

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

For a discussion of how to create and use external routines, see Extending
Informix Dynamic Server 2000.

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

SQL Statements 2-43


ALTER INDEX

+
ALTER INDEX
Use the ALTER INDEX statement to put the data in a table in the order of an
existing index or to release an index from the clustering attribute.

Syntax

ALTER INDEX index IDS TO CLUSTER

NOT
XPS

LOCK MODE COARSE

NORMAL

Element Purpose Restrictions Syntax


index Name of the index to alter The index must exist. Database Object Name, p. 4-50

Usage
The ALTER INDEX statement works only on indexes that are created with the
CREATE INDEX statement; it does not affect constraints that are created with
the CREATE TABLE statement.
You cannot alter the index of a temporary table.

2-44 Informix Guide to SQL: Syntax


ALTER INDEX

TO CLUSTER Option
The TO CLUSTER option causes the rows in the physical table to reorder in the
indexed order.

The following example shows how you can use the ALTER INDEX TO
CLUSTER statement to order the rows in the orders table physically. The
CREATE INDEX statement creates an index on the customer_num column of
the table. Then the ALTER INDEX statement causes the physical ordering of
the rows.
CREATE INDEX ix_cust ON orders (customer_num);

ALTER INDEX ix_cust TO CLUSTER;

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, the table 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. ♦

SQL Statements 2-45


ALTER INDEX

TO NOT CLUSTER Option


The NOT 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 NOT 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.

XPS LOCK MODE Options


Use the lock modes to specify the locking granularity of the index.

When you use the coarse-lock mode, index-level locks are acquired on the
index instead of item-level or page-level locks. This mode reduces the
number of lock calls on an index.

Use the coarse-lock mode when you know the index is not going to change,
that is, when read-only operations are performed on the index.

Use the coarse-lock mode to have the database server place item-level or
page-level locks on the index as necessary. Use this mode when the index gets
updated frequently.

2-46 Informix Guide to SQL: Syntax


ALTER INDEX

When the database server executes the command to change the lock mode to
coarse, it acquires an exclusive lock on the table for the duration of the
command. Any transactions that are currently using a lock of finer granu-
larity must complete before the database server switches to the coarse-lock
mode.

Related Information
Related statements: CREATE INDEX and CREATE TABLE
For a discussion of the performance implications of clustered indexes, see
your Performance Guide.

SQL Statements 2-47


ALTER PROCEDURE

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

Syntax
,

Routine
ALTER PROCEDURE procedure WITH ( ADD Modifier )
p. 4-274
MODIFY
,
DROP
parameter_type

Shared-
SPECIFIC PROCEDURE Specific Name Object
p. 4-296 MODIFY EXTERNAL NAME Filename
p. 4-292

Element Purpose Restrictions Syntax


parameter_type Data type of the parameter The data type (or list of data types) Identifier, p. 4-205
must be the same types (and specified
in the same order) as those specified
in the CREATE PROCEDURE statement
when the procedure was created.
procedure Name of the external The procedure must exist (that is, be Database Object
procedure to modify registered) in the database. Name, p. 4-50
If the name does not uniquely identify
a procedure, you must enter one or
more appropriate values for
parameter_type.

2-48 Informix Guide to SQL: Syntax


ALTER PROCEDURE

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

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

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

Keywords That Introduce Modifications


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 Introduces a new location for the executable file


NAME
(for external routines only)

WITH Introduces all modifications

SQL Statements 2-49


ALTER PROCEDURE

If the routine modifier is a Boolean value, MODIFY sets the value to be T (that
is, it is the equivalent of using the keyword ADD to add the routine modifier).
For example, both of the following statements alter the proc1 procedure so
that it can be executed in parallel in the context of a parallelizable data query
statement.
ALTER PROCEDURE proc1 WITH (MODIFY PARALLELIZABLE)

ALTER PROCEDURE proc1 WITH (ADD PARALLELIZABLE)

For a related example, see “Altering Routine Modifiers Example” on


page 2-54.

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

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

For a discussion of how to create and use external routines, see Extending
Informix Dynamic Server 2000.

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

2-50 Informix Guide to SQL: Syntax


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
,

Routine
ALTER ROUTINE routine WITH ( ADD Modifier )
p. 4-274
MODIFY
,
DROP
parameter_type

EXT Shared-
SPECIFIC ROUTINE Specific Name Object
p. 4-296 MODIFY EXTERNAL NAME Filename
p. 4-292

Element Purpose Restrictions Syntax


parameter_type Data type of the parameter The data type (or list of data Identifier, p. 4-205
types) must be the same types
(and specified in the same order)
as those specified when the UDR
was created.
routine Name of the UDR to modify The UDR must exist (that is, be Database Object
registered) in the database. Name, p. 4-50
If the name does not uniquely
identify a UDR, you must enter
one or more appropriate values
for parameter_type.

SQL Statements 2-51


ALTER ROUTINE

Usage
The ALTER ROUTINE statement allows you to modify a previously-defined
UDR to tune its performance. With this statement you can modify character-
istics that control how the UDR executes. You can also add or replace related
UDRs that provide alternatives for the optimizer, which can improve
performance.

This statement is useful when you do not know whether a UDR is a user-
defined function or a user-defined procedure. When you use this statement,
the database server alters the appropriate user-defined procedure or user-
defined function.

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

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

Restrictions
When you use this statement, the type of UDR cannot be ambiguous. The
UDR that you specify must refer to either a user-defined function or a user-
defined procedure. If either of the following conditions exist, the database
server returns an error:

■ The name (and parameters) that you specify apply to both a user-
defined procedure and a user-defined function
■ The specific name that you specify applies to both a user-defined
function and a user-defined procedure

2-52 Informix Guide to SQL: Syntax


ALTER ROUTINE

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 Introduces a new location for the executable file


NAME
(for external UDRs only)

WITH Introduces all modifications

If the routine modifier is a Boolean value, MODIFY sets the value to be T (that
is, it is the equivalent of using the keyword ADD to add the routine modifier).
For example, both of the following statements alter the func1 UDR so that it
can be executed in parallel in the context of a parallelizable data query
statement.
ALTER ROUTINE func1 WITH (MODIFY PARALLELIZABLE)

ALTER ROUTINE func1 WITH (ADD PARALLELIZABLE)

SQL Statements 2-53


ALTER ROUTINE

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
)

Note also, that because the name func1 is not unique to the database, the data
type parameters are specified so that the routine signature would be unique.
If this function had a Specific Name, for example, raise_sal, specified when it
was created, you could identify the function with the following first line:
ALTER SPECIFIC ROUTINE raise_sal

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

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

For a discussion of how to create and use external routines, see Extending
Informix Dynamic Server 2000.

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

2-54 Informix Guide to SQL: Syntax


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-57
synonym
Usage-TYPE Options
XPS p. 2-87

Typed-Table Options
IDS p. 2-89

Element Purpose Restrictions Syntax


synonym Name of the synonym for the The synonym and the table to Database Object
table to alter which the synonym points must Name, p. 4-50
exist.
table Name of the table to alter The table must exist. Database Object
Name, p. 4-50

Usage
Altering a table on which a view depends might invalidate the view.

Warning: The clauses available with this statement have varying performance impli-
cations. Before you undertake alter operations, check corresponding sections in your
“Performance Guide” to review effects and strategies.

Restrictions
You cannot alter a temporary table. You also cannot alter a violations or
diagnostics table. In addition, you cannot add, drop, or modify a column if
the table that contains the column has violations and diagnostics tables
associated with it.

SQL Statements 2-55


ALTER TABLE

XPS If a table has range fragmentation, the parts of this statement that you can use
are the Usage-TYPE options, and the Lock-Mode clause. All other operations
return an error.

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

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

■ You must have the DBA privilege on the database where the table
resides.
■ You must own the table.
■ You must have the Alter privilege on the specified table and the
Resource privilege on the database where the table resides.
■ To add a referential constraint, you must have the DBA or References
privilege on either the referenced columns or the referenced table.
■ To drop a constraint, you must have the DBA privilege or be the
owner of the constraint. If you are the owner of the constraint but not
the owner of the table, you must have Alter privilege on the specified
table. You do not need the References privilege to drop a constraint.

2-56 Informix Guide to SQL: Syntax


ALTER TABLE

Basic-Table Options
With the ALTER TABLE statement, you can perform basic alter operations
such as adding, modifying, or dropping columns and constraints, and
changing the extent size and locking granularity of a table. The database
server performs the alter operations in the order that you specify. If any of the
actions fails, the entire operation is cancelled.

Basic Table Options Back to ALTER TABLE


p. 2-55
,

ADD Clause
p. 2-59

DROP Clause
p. 2-69

MODIFY Clause
p. 2-72

ADD CONSTRAINT Clause


p. 2-80

DROP CONSTRAINT Clause


p. 2-83

MODIFY NEXT SIZE Clause


1 p. 2-84

LOCK MODE Clause


1 p. 2-85

IDS ADD TYPE Clause


1 p. 2-86

IDS PUT Clause


p. 2-78

IDS ADD ROWIDS

DROP ROWIDS

ADD CRCOLS

DROP CRCOLS

SQL Statements 2-57


ALTER TABLE

IDS You can also associate a table with a named-row type or specify a new storage
space to store large-object data.

In addition, you can add or drop rowid columns and shadow columns that
for Enterprise Replication. However, you cannot specify these options in
conjunction with any other alterations. ♦

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. Informix recommends 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


Administrator’s Reference.

IDS Using the DROP ROWIDS Keywords


Use the DROP ROWIDS keywords to 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


Use the ADD CRCOLS keywords to create the shadow columns, cdrserver and
cdrtime, that Enterprise Replication uses for conflict resolution. You must
add these columns before you can use time-stamp or UDR conflict resolution.

2-58 Informix Guide to SQL: Syntax


ALTER TABLE

For more information, refer to “Using the WITH CRCOLS Option” on


page 2-255 and to the Guide to Informix Enterprise Replication.

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

ADD New Column

,
( New Column )

New Column

Data Type
new_column p. 4-53
Single-Column BEFORE column
DEFAULT
Clause Constraint
p. 2-60 Format
p. 2-62

Element Purpose Restrictions Syntax


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

SQL Statements 2-59


ALTER TABLE

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

Using the BEFORE Option


Use the BEFORE option to specify the column before which a new column or
list of columns is to be added.

If you do not include the BEFORE option, the database server adds the new
column or list of columns to the end of the table definition by default.

In the following example, the BEFORE option directs the database server to
add the item_weight column before the total_price column:
ALTER TABLE items
ADD (item_weight DECIMAL(6,2) NOT NULL
BEFORE total_price)

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

2-60 Informix Guide to SQL: Syntax


ALTER TABLE

DEFAULT Back to ADD Clause p. 2-59


Clause Back to MODIFY Clause p. 2-72

DEFAULT literal

NULL

USER
+

CURRENT

DATETIME
Field Qualifier
p. 4-71

TODAY

SITENAME

DBSERVERNAME

Element Purpose Restrictions Syntax


literal Literal term that defines alpha or Term must be appropriate type Expression, p. 4-73
numeric constant characters to for the column.
use as the default value for the See “Using a Literal as a Default
column Value” on page 2-235.

You cannot place a default on 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.

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

SQL Statements 2-61


ALTER TABLE

Example of a Literal Default Value


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.

Single-Column Constraint Format


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

Single-Column Back to ADD Clause


Constraint Format p. 2-59

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

CHECK
Clause
p. 2-68

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


the table contains data. However, in the case of a unique constraint, 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.

2-62 Informix Guide to SQL: Syntax


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. However, if the
existing index allows duplicates, 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 these types of columns. You can place a check
constraint on a BYTE or TEXT column. However, you can check only for IS
NULL, IS NOT NULL, or LENGTH.

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, no additional
restrictions exist; that is, 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)

SQL Statements 2-63


ALTER TABLE

Constraint Definition
IDS Use the Constraint Definition portion of the ALTER TABLE statement to assign
a name to a constraint and to set the mode of the constraint to disabled,
enabled, or filtering. ♦

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

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


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

CONSTRAINT constraint IDS

DISABLED

ENABLED

FILTERING

WITH ERROR

WITHOUT ERROR

Element Purpose Restrictions Syntax


constraint Name assigned to the constraint None. Identifier, p. 4-205

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


Constraint-Mode Option” on page 2-249.

REFERENCES Clause
The REFERENCES clause allows you to place a foreign-key reference on a
column. The referenced column can be in the same table as the referencing
column, or the referenced column can be in a different table in the same
database.

2-64 Informix Guide to SQL: Syntax


ALTER TABLE

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


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

REFERENCES table
, +
( column ) ON DELETE CASCADE

Element Purpose Restrictions Syntax


column Referenced column or set of See “Restrictions on the Refer- Identifier, p. 4-205
columns in the referenced table enced Column” on page 2-66.
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 refer-
encing table, there is no default.
table Name of the referenced table The referenced table can be the Database Object
same table as the referencing Name, p. 4-50
table, or it can be a different
table. The referenced and refer-
encing tables must reside in the
same database.

SQL Statements 2-65


ALTER TABLE

Restrictions on Referential Constraints


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

Restrictions on the Referenced Column


You must observe the following restrictions on the column variable (the refer-
enced 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 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.
■ 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-66 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 to specify whether 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 principal advantage to the cascading deletes feature is
that it allows you to reduce the quantity of SQL statements you need to
perform delete actions.

For example, in the stores_demo database, the stock table contains the
stock_num column as a primary key. The catalog table refers to the
stock_num column as a foreign key. The following ALTER TABLE statements
drop an existing foreign-key constraint (without cascading delete) and add a
new constraint that specifies cascading deletes:
ALTER TABLE catalog DROP CONSTRAINT aa

ALTER TABLE catalog ADD CONSTRAINT


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

SQL Statements 2-67


ALTER TABLE

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

Restrictions
If a table has a trigger with a DELETE trigger event, you cannot define a
cascading-delete referential constraint on that table. You receive an error
when you attempt to add a referential constraint that specifies ON DELETE
CASCADE to a table that has a delete trigger.

For information about syntax restrictions and locking implications when you
delete rows from tables that have cascading deletes, see “Considerations
When Tables Have Cascading Deletes” on page 2-375.

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 a table in a database with transactions, and you are using
transactions).

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


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

( Condition )
CHECK p. 4-27

2-68 Informix Guide to SQL: Syntax


ALTER TABLE

During an insert or update, if a row evaluates to false for any check constraint
defined on a table, the database server returns an error. The database server
does not return an error if a row evaluates to null for a check constraint. In
some cases, you might wish to use both a check constraint and a NOT NULL
constraint.

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

You cannot create check constraints for columns across tables. When you are
using the ADD or MODIFY clause, the check constraint cannot depend upon
values in other columns of the same table. The following example adds a new
column, unit_price, to the items table and includes a check constraint that
ensures that the entered value is greater than 0:
ALTER TABLE items
ADD (unit_price MONEY (6,2) CHECK (unit_price > 0) )

To create a constraint that checks values in more than one column, use the
ADD CONSTRAINT clause. The following example builds a constraint on the
column that was added in the previous example. The check constraint now
spans two columns in the table.
ALTER TABLE items ADD CONSTRAINT
CHECK (unit_price < total_price)

DROP Clause
Use the DROP clause to drop one or more columns from a table.

DROP Back to Basic Table Options


Clause p. 2-57

DROP column
,
( column )

SQL Statements 2-69


ALTER TABLE

Element Purpose Restrictions Syntax


column Name of the column that you The column must already exist Identifier, p. 4-205
want to drop in the table.
If the column is referenced in a
fragment expression, it cannot
be dropped. If the column is the
last column in the table, it
cannot be dropped.

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 placed on that column are dropped,
as described in the following list:

■ All single-column constraints are dropped.


■ All referential constraints that reference the column are dropped.
■ 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.

2-70 Informix Guide to SQL: Syntax


ALTER TABLE

How Dropping a Column Affects Triggers


In general, when you drop a column from a table, the triggers based on that
table remain unchanged. However, if the column that you drop appears in
the action clause of a trigger, you can 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 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-296.

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

The database server does not automatically drop the column because you can
change the order of columns in a table by dropping a column and then
adding a new column with the same name. In this case, views based on the
altered table continue to work. However, they retain their original sequence
of columns.

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

SQL Statements 2-71


ALTER TABLE

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 of a column and the length of
a character column, to add or change the default value for a column, and to
allow or disallow nulls in a column.

MODIFY Back to Basic Table Options


Clause p. 2-57

MODIFY Modify Column


Clause
,
( Modify Column )
Clause

Modify Column
Clause

column Data Type


p. 4-53
DEFAULT Single-Column
Clause Constraint Format
p. 2-60 p. 2-62

Element Purpose Restrictions Syntax


column Name of the column that you The column must already exist Identifier, p. 4-205
want to modify in the table.
The data type of the column
cannot be a collection data type.

2-72 Informix Guide to SQL: Syntax


ALTER TABLE

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

IDS You cannot change the data type of a column to be a collection type or a row
type. ♦

When you modify a column, all attributes previously associated with that
column (that is, default value, single-column check constraint, or referential
constraint) are dropped. When you want certain attributes of the column to
remain, such as PRIMARY KEY, you must re-specify those attributes. For
example, if you are changing the data type of an existing column, quantity,
to SMALLINT, and you want to keep the default value (in this case, 1) and
non-null attributes for that column, you can issue the following ALTER TABLE
statement:
ALTER TABLE items
MODIFY (quantity SMALLINT DEFAULT 1 NOT NULL)

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


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 example, a column is
part of a multiple-column primary-key constraint. This primary key is refer-
enced by foreign keys in two other tables. When this column is modified, the
multiple-column primary-key constraint is not dropped, but the referential
constraints placed on it by the two other tables are dropped.

SQL Statements 2-73


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. However, you cannot use the MODIFY clause 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. However, you can set the next value 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-543.

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;

2-74 Informix Guide to SQL: Syntax


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 next serial 8 numbers to 75, you can enter the
following command:
ALTER TABLE child3tab
MODIFY (s serial(75), s8 serial8(75))

When the ALTER TABLE statement executes, the database server updates
corresponding serial columns in the child1, child2, and child3 tables.

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. The NOT NULL keywords create a not-null constraint on the
column.

SQL Statements 2-75


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,
you can 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
DISABLED keyword in the MODIFY clause.
2. Start a violations and diagnostics table for the target table with the
START VIOLATIONS TABLE statement.
3. Issue a SET 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.

2-76 Informix Guide to SQL: Syntax


ALTER TABLE

6. After you fix all the nonconforming rows in the target table, issue the
SET statement again to switch the disabled constraint to the enabled
mode.
This time the constraint is enabled, and no integrity-violation error
message is returned because all rows in the target table now satisfy
the new constraint.

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. However, 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 recreate the trigger.

SQL Statements 2-77


ALTER TABLE

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.

IDS PUT Clause


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

PUT Clause Back to Basic Table Options


p. 2-57

,
PUT column IN ( sbspace )

,
( )
EXTENT SIZE kilobytes

LOG

NO LOG

HIGH INTEG

KEEP ACCESS TIME

NO KEEP ACCESS TIME

2-78 Informix Guide to SQL: Syntax


ALTER TABLE

Element Purpose Restrictions Syntax


column Name of the column to store in Column must contain a user- Identifier, p. 4-205
the specified sbspace defined type, complex type,
BLOB, or CLOB data type.
The column cannot be in the
form [Link]. That is, the
smart large object that you are
storing cannot be one field of a
row type.
kilobytes Number of kilobytes to allocate The number must be an integer Literal Number,
for the extent size value. p. 4-237
sbspace Name of an area of storage used The sbspace must exist. Identifier, p. 4-205
for smart large objects

When you modify the storage characteristics of an existing column, all


attributes previously 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.

When you modify the storage characteristics of a column that holds smart
large objects, the database server does not alter smart large objects that
already exist. The database server applies the new storage characteristics to
only those smart large objects that are inserted after the ALTER TABLE
statement takes effect.

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-273. For a discussion of large-object characteristics, refer to “Large-
Object Data Types” on page 4-62.

SQL Statements 2-79


ALTER TABLE

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

Multiple-Column
ADD CONSTRAINT Constraint Format
p. 2-81

( Multiple-Column )
Constraint Format
p. 2-81

For example, to add a unique constraint to the fname and lname columns of
the customer table, use the following statement:
ALTER TABLE customer
ADD CONSTRAINT UNIQUE (lname, fname)

To name the constraint, change the preceding statement, as the following


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

When you do not provide a constraint name, the database server provides
one. You can find the name of the constraint in the sysconstraints system
catalog table. For more information about the sysconstraints system catalog
table, see the Informix Guide to SQL: Reference.

2-80 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.

Table-Level Back to ADD CONSTRAINT Clause


Constraint Definition p. 2-80
,

UNIQUE ( column )
+ +

DISTINCT Constraint Definition


p. 2-64
PRIMARY KEY ,
( ) REFERENCES
FOREIGN KEY column Clause
p. 2-64

CHECK
Clause
p. 2-68

Element Purpose Restrictions Syntax


column Name of the column or columns The maximum number of col- Identifier, p. 4-237
on which the constraint is placed umns is 16, and the total length
of the list of columns cannot ex-
ceed 255 bytes.

A constraint that involves multiple columns 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 assign a name to the constraint and set its mode by means of
“Constraint Definition” on page 2-64.

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.

SQL Statements 2-81


ALTER TABLE

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


columns, 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.
You must drop the existing index before adding the primary-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.

Adding a Referential Constraint


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.

Privileges Required for Adding Constraints


When 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 and receive an error message because existing rows would violate the
constraint, you can follow a procedure to add the constraint successfully. See
“Adding a Constraint When Existing Rows Violate the Constraint” on
page 2-76.

2-82 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-57

DROP CONSTRAINT constraint


,
( constraint )

Element Purpose Restrictions Syntax


constraint Name of the constraint that you The constraint must exist. Database Object
want to drop Name, p. 4-50

To drop an existing constraint, specify the DROP CONSTRAINT keywords and


the name of the constraint. The following statement is an example of
dropping a constraint:
ALTER TABLE manufact DROP CONSTRAINT con_name

If a constraint name is not 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-83


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


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

MODIFY NEXT SIZE kilobytes

Element Purpose Restrictions Syntax


kilobytes Length in kilobytes that you The minimum length is four Expression, p. 4-73
want to assign for the next times the disk-page size on your
extent for this table system. 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.

If you want to specify an extent size of 32 kilobytes, use a statement such as


the one in the following example:
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.

Changing the Size of Existing Extents


To change the size of existing extents, you must unload all of 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 optimizing extents, see your Administrator’s Guide.

2-84 Informix Guide to SQL: Syntax


ALTER TABLE

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

LOCK MODE ( PAGE )


ROW

XPS TABLE

The following table describes the locking-granularity options available.

Locking
Granularity Option Purpose

ROW Obtains and releases one lock per row.


Row-level locking provides the highest level of concurrency.
However, if you are using many rows at one time, the lock-
management overhead can become significant. You can also
exceed the maximum number of locks available, depending on
the configuration of your database-server.

PAGE Obtains and releases one lock on a whole page of rows.


This is the default locking granularity.
Page-level locking is especially useful when you know that the
rows are grouped into pages in the same order that you are
using to process all the rows. For example, if you are processing
the contents of a table in the same order as its cluster index,
page locking is especially appropriate.

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 the table
Multiple read-only transactions can still access the table.

SQL Statements 2-85


ALTER TABLE

IDS ADD TYPE Clause


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

ADD TYPE Back to Basic Table Options


Clause p. 2-57

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 Data Type, p. 4-53
added to the table must match the column types of the
table.

When you use the ADD TYPE clause, you assign a named-row type to a table
whose columns match the fields of the row type.

You cannot add a type to a fragmented table that has rowids.

You cannot combine the ADD TYPE clause with any clause that changes the
structure of the table. That is, you cannot use an ADD, DROP, or MODIFY
clause in the same statement as the ADD TYPE clause.

Tip: To change the data type of a column, use the MODIFY clause. The ADD TYPE
clause does not allow you to change column data types.

When you add a named-row type to a table, be sure that:

■ the type already exists.


■ the fields in the named-row type match the column types in the table.

You must have the Usage privilege to add a type to a table.

2-86 Informix Guide to SQL: Syntax


ALTER TABLE

XPS Usage-TYPE Options


In Extended Parallel Server, use the Usage-TYPE options to specify that the
table have particular characteristics that can improve various bulk operations
on it.

Usage TYPE Options Back to ALTER TABLE


p. 2-55

TYPE ( RAW )
STATIC

OPERATIONAL

STANDARD

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

A table can have any of the following usage characteristics.

Option Purpose

RAW Non-logging table that cannot have indexes or referential


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

SQL Statements 2-87


ALTER TABLE

Option Purpose

STATIC Non-logging table that can contain index and referential


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

OPERATIONAL Logging table that uses light appends and cannot be


restored from archive
Use this type on tables that are refreshed frequently
because light appends allow the quick addition of many
rows.

STANDARD Logging table that allows rollback, recovery, and resto-


ration from archives
This type is the default.
Use this type for all the recovery and constraints function-
ality that you want on your OLTP databases.

For a more detailed description, refer to your Administrator’s Guide.

Restrictions on the Usage-TYPE Options


The usage-TYPE options have the following restrictions:

■ You cannot change the usage type if the table has a dependent GK
index.
■ You must perform a level-0 archive before the usage type of a table
can be altered to STANDARD from any other type.
■ If you want to change the usage type of a table to RAW, you must
drop all indexes on the table before you do so.
■ If you have triggers defined on the table, you cannot change the
usage type to RAW or STATIC.
That is, raw and static tables do not support triggers.
■ You cannot use this clause with SCRATCH or TEMP tables.
That is, you cannot change any of these types of tables to either a
SCRATCH or TEMP table. Similarly, you cannot change a SCRATCH or
TEMP table to any of these types of tables.

2-88 Informix Guide to SQL: Syntax


ALTER TABLE

IDS Typed Tables Options


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

Typed-Table Back to ALTER TABLE


Options p. 2-55

ADD CONSTRAINT Clause


p. 2-80

DROP CONSTRAINT Clause


p. 2-83
1 DROP TYPE

MODIFY NEXT SIZE Clause


1 p. 2-84

1 LOCK MODE Clause


p. 2-85

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.

SQL Statements 2-89


ALTER TABLE

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

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

For information on how to maximize performance when you make table


modifications, see your Performance Guide.

2-90 Informix Guide to SQL: Syntax


BEGIN WORK

+
BEGIN WORK
Use the BEGIN WORK statement to start a transaction (a sequence of database
operations that the COMMIT WORK or ROLLBACK WORK statement
terminates). Use the BEGIN WORK WITHOUT REPLICATION statement to start
a transaction that does not replicate to other database servers.

Syntax

BEGIN

WORK

IDS
WORK WITHOUT REPLICATION
E/C

Usage
Each row that an UPDATE, DELETE, or INSERT statement affects during a
transaction is locked and remains locked throughout the transaction. A trans-
action that contains many such statements or that contains statements
affecting many rows can exceed the limits that your operating system or the
database server configuration imposes on the maximum number of simulta-
neous locks. If no other user is accessing the table, you can avoid locking
limits and reduce locking overhead by locking the table with the LOCK TABLE
statement after you begin the transaction. Like other locks, this table lock is
released when the transaction terminates. The example of a transaction on
“Example of BEGIN WORK” on page 2-93 includes a LOCK TABLE statement.

Important: You can issue the BEGIN WORK statement only if a transaction is not in
progress. If you issue a BEGIN WORK statement while you are in a transaction, the
database server returns an error.

E/C In ESQL/C, if you use the BEGIN WORK statement within a UDR called by a
WHENEVER statement, specify WHENEVER SQLERROR CONTINUE and
WHENEVER SQLWARNING CONTINUE before the ROLLBACK WORK
statement. These statements prevent the program from looping if the
ROLLBACK WORK statement encounters an error or a warning. ♦

SQL Statements 2-91


BEGIN WORK

WORK Keyword
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. A warning is generated if you use a BEGIN
WORK statement immediately after one of the following statements:

■ DATABASE
■ COMMIT WORK
■ CREATE DATABASE
■ ROLLBACK WORK

An error is generated if you use a BEGIN WORK statement after any other
statement.

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 the BEGIN WORK WITHOUT REPLICATION statement as a


stand-alone embedded statement within 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 the BEGIN WORK WITHOUT REPLICATION statement in a
single step.

2-92 Informix Guide to SQL: Syntax


BEGIN WORK

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

For more information about data replication, see the Guide to Informix
Enterprise Replication.

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). The database server must perform this
sequence of operations either completely or not at all. The database server
guarantees that all the statements are completely and perfectly committed to
disk, or the database is restored to the same state as before the transaction
began.
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;

Related Information
Related statements: COMMIT WORK, ROLLBACK WORK

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

SQL Statements 2-93


CLOSE

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

Use this statement with ESQL/C.

Syntax

CLOSE cursor_id

cursor_id_var

Element Purpose Restrictions Syntax


cursor_id Name of the cursor to close The DECLARE statement must Identifier, p. 4-205
have previously declared the
cursor.
cursor_id_var Host variable that holds the Host variable must be a Name must conform
value of cursor_id character data type. The cursor to language-specific
must be declared. In ANSI- rules for variable
compliant databases, before you names.
can close a cursor, the cursor
must be open.

Usage
Closing a cursor makes the cursor unusable for any statements except OPEN
or FREE and releases resources that the database server had allocated to the
cursor. A CLOSE statement treats a cursor that is associated with an INSERT
statement differently than one that is associated with a SELECT or EXECUTE
FUNCTION (or EXECUTE PROCEDURE) statement.

You can close a cursor that was never opened or that has already been closed.
No action is taken in these cases.

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


close a cursor that was not open. ♦

2-94 Informix Guide to SQL: Syntax


CLOSE

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. 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, [Link][2], in the sqlca structure. For
information on using SQLERRD to count the total number of rows that were
inserted, see “Error Checking” on page 2-601.

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

When SQLCODE is zero, the row buffer space is released, and the cursor is
closed; that is, you cannot execute a PUT or FLUSH statement that names the
cursor until you reopen it.
Tip: When you encounter an SQLCODE error, a corresponding SQLSTATE error
value also exists. For information about how to get the message text, check the GET
DIAGNOSTICS statement.

SQL Statements 2-95


CLOSE

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.

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 the following
sections: “Fetching From a Collection Cursor” on page 2-466 and “Inserting
into a Collection Cursor” on page 2-599.

Using End of Transaction to Close a Cursor


The COMMIT WORK and ROLLBACK WORK statements close all cursors
except those that are declared with 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-349.

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


must issue a CLOSE statement. ♦

2-96 Informix Guide to SQL: Syntax


CLOSE

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

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


Tutorial.

For a more advanced discussion of cursors, see the Informix ESQL/C


Programmer’s Manual.

SQL Statements 2-97


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
This statement is valid only if an explicit connection existed before
you issued the CLOSE DATABASE statement.

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

If your database has transactions, and if you have started a transaction, you
must issue a COMMIT WORK statement before you use the CLOSE DATABASE
statement.

The following example shows how to use the CLOSE DATABASE statement to
drop the current database:
DATABASE stores_demo
.
.
.
CLOSE DATABASE
DROP DATABASE stores_demo

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


statement PREPARE operation.

2-98 Informix Guide to SQL: Syntax


CLOSE DATABASE

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, declared cursors are no
longer valid. You must re-declare any cursors that you want to use. ♦

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

SQL Statements 2-99


COMMIT WORK

COMMIT WORK
Use the COMMIT WORK statement to commit all modifications made to the
database from the beginning of a transaction. This statement informs the
database server that you reached the end of a series of statements that must
succeed as a single unit. The database server takes the required steps to make
sure that all modifications made by the transaction are completed correctly
and committed to disk.

Syntax

COMMIT

WORK

Usage
Use the COMMIT WORK statement when you are sure you want to keep
changes that are made to the database from the beginning of a transaction.
Use the COMMIT WORK statement only at the end of a multistatement
operation.

The COMMIT WORK statement releases all row and table locks.

E/C In ESQL/C, the COMMIT WORK statement closes all open cursors except those
declared with hold. ♦

WORK Keyword
The WORK keyword is optional in a COMMIT WORK statement. The following
two statements are equivalent:
COMMIT;

COMMIT WORK;

2-100 Informix Guide to SQL: Syntax


COMMIT WORK

Example
The following example shows a transaction bounded by BEGIN WORK and
COMMIT WORK statements. In this example, the user first deletes the row
from the call_type table where the value of the call_code column is O. The
user then inserts a new row in the call_type table where the value of the
call_code column is S. The database server guarantees that both operations
succeed or else neither succeeds.
BEGIN WORK;
DELETE FROM call_type WHERE call_code = 'O';
INSERT INTO call_type VALUES ('S', 'order status');
COMMIT WORK;

Issuing COMMIT WORK in a Database That Is Not ANSI


Compliant
In a database that is not ANSI compliant, 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 the modifications to the database that the
transaction made.

However, if you do not issue a BEGIN WORK statement, the database server
executes each statement within its own transaction. These single-statement
transactions do not require either a BEGIN WORK statement or a COMMIT
WORK statement.

ANSI Issuing COMMIT WORK in an ANSI-Compliant Database


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

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

SQL Statements 2-101


COMMIT WORK

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

For a discussion of concepts related to transactions, see the Informix Guide to


SQL: Tutorial.

2-102 Informix Guide to SQL: Syntax


CONNECT

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

Syntax

Database
CONNECT TO Environment
p. 2-108
E/C E/C

USER
AS ' connection ' Clause
E/C
p. 2-112
AS connection_var

DEFAULT

WITH CONCURRENT TRANSACTION

Element Purpose Restrictions Syntax


connection Quoted string that assigns a Each connection name must be Quoted String,
name to the connection unique. p. 4-260
connection_var Host variable that holds the Variable must be a fixed-length Name must conform
value of connection character data type. to language-specific
rules for variable
names.

Usage
The CONNECT statement connects an application to a database environment.
The database environment can be a database, a database server, or a database
and a database server. If the application successfully connects to the specified
database environment, the connection becomes the current connection for
the application. SQL statements fail if no current connection exists between an
application and a database server. If you specify a database name, the
database server opens the [Link] cannot use the CONNECT statement
in a PREPARE statement.

SQL Statements 2-103


CONNECT

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.

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

WIN NT On Windows NT, the local connection mechanism is named pipes. Multiple
connections to the local server from one client can exist. ♦

Only one connection is current at any time; other connections are dormant.
The application cannot interact with a database through a dormant
connection. When an application establishes a new connection, that
connection becomes current, and the previous current transaction becomes
dormant. You can make a dormant connection current with the SET
CONNECTION statement. For more information, see “SET CONNECTION”
on page 2-694.

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 using the USER clause to specify an alternate user name
when the CONNECT statement connects to a database server on a remote
host, see “USER Clause” on page 2-112.

2-104 Informix Guide to SQL: Syntax


CONNECT

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.

The value of a connection name is case sensitive.

Connection Context
Each connection encompasses a set of information that is called the connection
context. The connection context includes the name of the current user, the
information that the database environment associates with this name, and
information on the state of the connection (such as whether an active trans-
action is associated with the connection). The connection context is saved
when an application becomes dormant, and this context is restored when the
application becomes current again. (For more information on dormant
connections, see “Making a Dormant Connection the Current Connection”
on page 2-695.)

DEFAULT Option
Use the DEFAULT option to request a connection to a default database server,
called a default connection. The default database server can be either local or
remote. To designate the default database server, set its name in the
environment variable INFORMIXSERVER. This form of the CONNECT
statement does not open a database.

If you select the DEFAULT option for the CONNECT statement, you must use
the DATABASE statement or the CREATE DATABASE statement to open or
create a database in the default database environment.

SQL Statements 2-105


CONNECT

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 “Locating the Database” on
page 2-110.

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
specified by the INFORMIXSERVER environment variable. This default
allows the application to refer to the implicit connection if additional explicit
connections are made, because the implicit connection does not have an
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
command because the implicit connection is considered to be the default
connection.

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


new database on the current database server.

2-106 Informix Guide to SQL: Syntax


CONNECT

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 [Link] 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.

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'

SQL Statements 2-107


CONNECT

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

Database Environment

Database Back to CONNECT p. 2-103


Environment Back to SET CONNECTION p. 2-694

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

2-108 Informix Guide to SQL: Syntax


CONNECT

Element Purpose Restrictions Syntax


db_var Host variable that contains a Variable must be a fixed-length Variable name must
value representing a database character data type. The value conform to language-
environment stored in this host variable must specific rules for
have one of the database- variable names.
environment formats listed in
the syntax diagram.
dbname Name of the database to which The specified database must Identifier, p. 4-205
a connection is made already exist.
dbservername Name of the database server to The specified database server Identifier, p. 4-205
which a connection is made must exist.
You cannot put a space between
the @ symbol and
dbservername.

Using Quote Marks in the Database Environment


If the DELIMIDENT environment variable is set, the quote marks in the
database environment must be single. If the DELIMIDENT environment
variable is not set, surrounding quotes can be single or double.

Restrictions on the dbservername Parameter


When the dbservername parameter appears in the specification of a database
environment, you must observe the following restrictions.

UNIX On UNIX, the database server that you specify in dbservername must match
the name of a database server in the sqlhosts file. ♦

WIN NT On Windows NT, the database server that you specify in dbservername must
match the name of a database server in the sqlhosts subkey in the registry.
Informix recommends that you use the setnet32 utility to update the
registry. ♦

SQL Statements 2-109


CONNECT

Specifying the Database Environment


Using the options in the syntax diagram, you can specify either a server and
a database, a database server only, or a database only.

Specifying a Database Server Only


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

Specifying a Database Only


The dbname option establishes a connection to the default database server or
to another database server in the DBPATH variable. It also locates and opens
the named [Link] same is true of the db_var option if it specifies only a
database name. For the order in which an application connects to different
database servers to locate a database, see “Locating the Database” on
page 2-110.

Locating the Database


How a database is located and opened depends on whether you specify a
database server name in the database environment expression.

Database Server and Database Specified


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

If the database server that you specify is not on-line, you receive an error.

2-110 Informix Guide to SQL: Syntax


CONNECT

Only Database Specified


If you specify only a database in your CONNECT statement, the application
obtains the name of a database server 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 shows:
setenv INFORMIXSERVER srvA
setenv DBPATH //srvB://srvC

WIN NT On Windows NT, choose Start➞Programs➞Informix➞setnet32 from the


Task Bar and set the INFORMIXSERVER and DBPATH environment variables,
as the following example shows:
set INFORMIXSERVER = srvA
set DBPATH = //srvA://srvB://srvC

The resulting DBPATH that your application uses is shown in the following
example:
//srvA://srvB://srvC

The application first establishes a connection to the database server specified


by INFORMIXSERVER. The database server uses parameters that are
specified 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 on-line, the application connects to the next database
server in DBPATH. In the previous example, that server would be srvB.

UNIX If a directory in DBPATH is an NFS-mounted directory, it is expanded to


contain the host name of the NFS computer and the complete pathname of the
directory on the NFS host. In this case, the host name must be listed in your
sqlhosts file as a dbservername, and an sqlexecd daemon must be running
on the NFS host. ♦

SQL Statements 2-111


CONNECT

USER Clause
The USER clause specifies information that is used to determine whether the
application can access the target computer when the CONNECT statement
connects to the database server on a remote host. Subsequent to the
CONNECT statement, all database operations on the remote host use the
specified user name.

USER Back to CONNECT


Clause p. 2-103

USER 'user _id ' USING validation_var

user_id_var

Element Purpose Restrictions Syntax


user_id Quoted string that is a valid The specified login name must Quoted String,
login name for the application be a valid login name. p. 4-260
For additional restrictions see
“Restrictions on the User
Identifier Parameter” on
page 2-113.
user_id_var Host variable that holds the Variable must be a fixed-length Name must conform
value of user_id character data type. to language-specific
The login name stored in this rules for variable
variable is subject to the same names.
restrictions as user_id.
validation_var Host variable that holds the Variable must be a fixed-length Name must conform
valid password for the login character data type. to language-specific
name specified in user_id or The password stored in this rules for variable
user_id_var variable must be a valid names.
password.
For additional restrictions see
“Restrictions on the Validation
Variable Parameter” on
page 2-113.

2-112 Informix Guide to SQL: Syntax


CONNECT

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

WIN NT On Windows NT, 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. ♦

WIN NT On Windows NT, the login name you specify in user_id must be a valid login
name and must exist in User Manager. If the application connects to a remote
server, the login name must exist in the domain of both the client and the
server. ♦

Rejection of the Connection


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.

SQL Statements 2-113


CONNECT

E/C In compliance with the X/Open specification for the CONNECT statement, the
ESQL/C preprocessor allows a CONNECT statement that has a USER clause
X/O without the USING validation_var phrase. However, if the validation_var is not
present, the database server rejects the connection at runtime. ♦

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 Informix 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/[Link] file. On Windows NT,
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.

2-114 Informix Guide to SQL: Syntax


CREATE AGGREGATE

+ CREATE AGGREGATE
IDS
Use the CREATE AGGREGATE statement to create a new aggregate function.
User-defined aggregates extend the functionality of the database server
because they can perform any kind of aggregate computation that the user
wants to implement.

Syntax

CREATE AGGREGATE aggregate WITH ( Modifiers )

Owner Name
p. 4-257

Modifiers

INIT = init_func

ITER = iter_func

COMBINE = comb_func

FINAL = final_func

HANDLESNULLS

Element Purpose Restrictions Syntax


aggregate Name of the new aggregate The name cannot be the same as Identifier, p. 4-205
the name of any built-in
aggregate or the name of any
UDR.
comb_func Function that merges one partial You must specify the combine Database Object
result into the other and returns function both for parallel queries Name, p. 4-50
the updated partial result and for sequential queries.
(1 of 2)

SQL Statements 2-115


CREATE AGGREGATE

Element Purpose Restrictions Syntax


final_func Function that converts a partial If the final function is omitted, Database Object
result into the result type the database server returns the Name, p. 4-50
final result of the iterator
function.
init_func Function that initializes the data The initialization function must Database Object
structures required for the be able to handle null Name, p. 4-50
aggregate computation arguments.
iter_func Function that merges a single You must specify a value for the Database Object
value with a partial result and iterator function. If the initial- Name, p. 4-50
returns the updated partial ization function is omitted, the
result iterator function must be able to
handle null arguments.
(2 of 2)

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 declare all the support
functions to handle null values as well.

2-116 Informix Guide to SQL: Syntax


CREATE AGGREGATE

Extending the Functionality of Aggregates


The database server provides two ways to extend the functionality of aggre-
gates. You use the CREATE AGGREGATE statement only for the second
method.

■ Extensions of built-in aggregates


A built-in aggregate is an aggregate that the database server
provides, such as COUNT, SUM, or AVG. These aggregates work only
with built-in data types. You can extend these aggregates to work
with extended data types. To extend a built-in aggregate, you must
create user-defined routines that overload the binary operators for
that aggregate. For further information on extending built-in aggre-
gates, see the Extending Informix Dynamic Server 2000 manual.
■ Creation of user-defined aggregates
A user-defined aggregate is an aggregate that you define to perform
an aggregate computation that is not provided by the database
server. You can use user-defined aggregates with built-in data types,
extended data types, or both. To create a user-defined aggregate, you
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

Example of Creating a User-Defined Aggregate


In the following example, you create 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.

SQL Statements 2-117


CREATE AGGREGATE

Keyword Support Function Purpose

INIT average_init Allocates and initializes an extended


data type that stores 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 using the INIT and
ITER support functions to compute each piece sequentially. Then the
database server uses the COMBINE function to combine the partial results
from all the pieces into a single result value. Whether an aggregate is parallel
is an optimization decision that is transparent to the user.

Related Information
Related statements: DROP AGGREGATE
For information about how to invoke a user-defined aggregate, see the
discussion of user-defined aggregates in the Expression segment.

For a description of the sysaggregates system catalog table that holds infor-
mation about user-defined aggregates, see the Informix Guide to SQL:
Reference.

For a discussion of user-defined aggregates, see Extending Informix Dynamic


Server 2000.

2-118 Informix Guide to SQL: Syntax


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 CAST ( source_type AS target_type )


IMPLICIT WITH function

EXPLICIT

Element Purpose Restrictions Syntax


function Name of the user-defined func- See “WITH Clause” on Database Object
tion that you register to imple- page 2-122. Name, p. 4-50
ment the cast
source_type Data type to be converted The type must exist in the Data Type, p. 4-53
database at the time the cast is
registered.
Either the source_type or the
target_type, but not both, can be a
built-in type.
Neither type can be a distinct
type of the other.
The type cannot be a collection
data type.
target_type Data type that results from the The type must exist in the Data Type, p. 4-53
conversion database at the time the cast is
registered.
Either the source_type or the
target_type, but not both, can be a
built-in type.
Neither type can be a distinct
type of the other.
The type cannot be a collection
data type.

SQL Statements 2-119


CREATE CAST

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 a 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. However, to create a cast to or from an opaque type, distinct type,
or named-row type requires the Usage privilege on that type.

The CREATE CAST statement registers a cast in the syscasts system catalog
table. For more information on syscasts, see the chapter on system catalog
tables in the Informix Guide to SQL: Reference.

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.

2-120 Informix Guide to SQL: Syntax


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

The following SELECT statement explicitly invokes this explicit cast in its
WHERE clause to compare the bond_rate column (of type rate_of_return) to
the initial_APR column (of type percent):
SELECT bond_rate FROM bond
WHERE bond_rate::percent > initial_APR

Implicit Casts
The database server invokes built-in casts to convert from one built-in data
type to another built-in type that is not directly substitutable. For example,
the database server performs conversion of a character type such as CHAR to
a numeric type such as INTEGER through a built-in cast.

An implicit cast is a cast that the database server can invoke automatically
when it encounters data types that cannot be compared with built-in casts.
This type of cast enables the database server to automatically handle conver-
sions between other data types.

To define an implicit cast, specify the IMPLICIT keyword in the CREATE CAST
statement. For example, the following CREATE CAST statement specifies that
the database server should automatically use the prcnt_to_char() function
when it needs to convert from the CHAR data type to a distinct data type,
percent:
CREATE IMPLICIT CAST (CHAR AS percent WITH prcnt_to_char)

SQL Statements 2-121


CREATE CAST

This cast provides the database server with only the ability to automatically
convert from the CHAR data type to percent. For the database server to
convert from percent to CHAR, you need to define another implicit cast, as
follows:
CREATE IMPLICIT CAST (percent AS CHAR WITH char_to_prcnt)

The database server would automatically invoke 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-121.

When a built-in cast does not exist for conversion between data types, you
can create user-defined casts to make the necessary conversion.

WITH Clause
The WITH clause of the CREATE CAST statement specifies the name of the
user-defined function to invoke to perform the cast. This function is called
the cast function. You must specify a function name unless the source data type
and the target data type have identical representations. Two data types have
identical representations when the following conditions are met:

■ 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
Execute privilege on the cast function.

2-122 Informix Guide to SQL: Syntax


CREATE CAST

Related Information
Related statements: CREATE FUNCTION, CREATE DISTINCT TYPE, CREATE
OPAQUE TYPE, CREATE ROW TYPE and DROP CAST

For more information about data types, casting, and conversion, see the Data
Types segment in this manual and the Informix Guide to SQL: Reference.

For examples that show how to create and use casts, see the Informix Guide to
SQL: Tutorial.

SQL Statements 2-123


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 of the database to create The database name must be Database Name,
unique on the server. p. 4-47
dbspace Name of the dbspace where you The dbspace must already exist. Identifier, p. 4-205
want to store the data for this
database; default is the root
dbspace

Usage
This statement is an extension to ANSI-standard syntax. The ANSI standard
does not provide any syntax for the construction of a database, that is how a
database comes into existence.

The database that you create 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 have access to it. The database
remains inaccessible to other users until you, as DBA, grant database privi-
leges. For information on how to grant database privileges, see “GRANT” on
page 2-500.

2-124 Informix Guide to SQL: Syntax


CREATE DATABASE

E/C In ESQL/C, the CREATE DATABASE statement cannot appear in a


multistatement PREPARE operation. ♦

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

Logging Options
The logging options of the CREATE DATABASE statement determine the type
of logging that is done for the database.

In the event of a failure, the database server uses the log to re-create all
committed transactions in your database.

If you do not specify the WITH LOG option, you cannot use transactions or
the statements that are associated with databases that have logging (BEGIN
WORK, COMMIT WORK, ROLLBACK WORK, SET LOG, and SET ISOLATION).

XPS If you are using Extended Parallel Server, the CREATE DATABASE statement
always creates a database with unbuffered logging. The database server
ignores any logging specifications included in a CREATE DATABASE
statement. ♦

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 Informix Guide to Database
Design and Implementation.)

SQL Statements 2-125


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 set apart from databases that are not ANSI-
compliant by the following features:
■ All statements are automatically contained in transactions.
All databases use unbuffered logging.
■ Owner-naming is enforced.
You must use the owner name when you refer to each table, view,
synonym, index, or constraint unless you are the owner.
■ For databases, the default isolation level is repeatable read.
■ Default privileges on objects differ from those in databases that are
not ANSI-compliant.
Users do not receive PUBLIC privilege to tables and synonyms by
default.

Other slight differences exist between databases that are ANSI-compliant and
those that are not. These differences are noted as appropriate with the related
SQL statement. For a detailed discussion of the differences between ANSI-
compliant databases and databases that are not ANSI-compliant, see the
Informix Guide to Database Design and Implementation.

Creating an ANSI-compliant database does not mean that you get ANSI
warnings when you run the database. You must use the -ansi flag or the
DBANSIWARN environment variable to receive warnings.

For additional information about -ansi and DBANSIWARN, see the Informix
Guide to SQL: Reference.

Related Information
Related statements: CLOSE DATABASE, CONNECT, DATABASE, DROP
DATABASE

For discussions of how to create a database and of ANSI-compliant databases,


see the Informix Guide to Database Design and Implementation.

2-126 Informix Guide to SQL: Syntax


CREATE DISTINCT TYPE

+ CREATE DISTINCT TYPE


IDS
Use the CREATE DISTINCT TYPE statement to create a new distinct type. A
distinct type is a data type based on a built-in type or an existing opaque type,
a named-row type, or another distinct type. Distinct types are strongly typed.
Although the distinct type has the same physical representation as data of its
source type, the two types cannot be compared without an explicit cast from
one type to the other.

Syntax

CREATE DISTINCT TYPE distinct_type AS source_type

Element Purpose Restrictions Syntax


distinct_ type Name of the new data type In an ANSI-compliant database, Data Type, p. 4-53
the combination of the owner
and data type must be unique
within the database. In a
database that is not ANSI
compliant, the name of the data
type must be unique within the
database.
source_type Name of an existing data type on The type must be either a built- Data Type, p. 4-53
which the new type is based in type or a type created with the
CREATE DISTINCT TYPE, CREATE
OPAQUE TYPE, or CREATE ROW
TYPE statement.

Usage
To create a distinct type in a database, you must have the Resource privilege.
Any user with the Resource privilege can create a distinct type from one of
the built-in data types, which are owned by user informix.

Important: You cannot create a distinct type on the SERIAL or SERIAL8 data type.

SQL Statements 2-127


CREATE DISTINCT 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 type or have the Usage privilege
on the type.

Once a distinct type is defined, only the type owner and the DBA can use it.
The owner of the type can grant other users the Usage privilege on the type.

A distinct type has the same storage structure as its source [Link]
following statement creates the distinct type birthday, based on the built-in
data type, DATE:
CREATE DISTINCT TYPE birthday AS DATE

Dynamic Server uses the same storage method for the distinct type as it does
for the source type of the distinct type. However, a distinct type and its source
type cannot be compared in an operation unless one type is explicitly cast to
the other type.

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 type privileges that might have been granted. For
more information on system catalog tables, see the 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

2-128 Informix Guide to SQL: Syntax


CREATE DISTINCT TYPE

Because the two types have the same representation (the same length and
alignment), no support functions are required to implement the casts.

You can create an implicit cast between a distinct type and its source type.
However, to create an implicit cast, you must first drop the default explicit
cast between the distinct type and its source type.

All support functions and casts that are defined on the source type can be
used on the distinct type. However, casts and support functions that are
defined on the distinct type are not available to the source type.

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.

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;

SQL Statements 2-129


CREATE DISTINCT TYPE

Related Information
Related statements: CREATE CAST, CREATE FUNCTION, CREATE OPAQUE
TYPE, CREATE ROW TYPE, DROP TYPE and DROP ROW TYPE

For information and examples that show how to use and cast distinct types,
see the Informix Guide to SQL: Tutorial.

For more information on when you might create a distinct type, see Extending
Informix Dynamic Server 2000.

2-130 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 so you can use that external source to load and
unload data for your database.

Syntax

Column DATAFILES
CREATE EXTERNAL TABLE table Definition USING ( Clause )
p. 2-132 p.2-137

Table , , Table
Options Options
p. 2-139 p. 2-139

Element Purpose Restrictions Syntax


table Name of the external table that The name must be different from Database Object
describes the external data any existing table, view, or Name, p. 4-50
synonym name in the current
database.

Usage
After you create a table with the CREATE EXTERNAL TABLE statement, you
can move data to and from the external source with an INSERT INTO...SELECT
statement.

SQL Statements 2-131


CREATE EXTERNAL TABLE

Column Definition

Column Back to CREATE EXTERNAL TABLE


Definition p. 2-131

SAMEAS template

,
Data
column Type
p. 4-53
Default Column-Level
Clause Constraints
p. 2-234 p. 2-136
Data
EXTERNAL Type
p. 4-53

' PACKED( p , s )' NULL 'null_string '

' ZONED( p , s )'


' BINARY( n )'

' TEXT'
' HEX'

Element Purpose Restrictions Syntax


column One column name for each For each column, you must Identifier, p. 4-205
column of the external table specify an Informix data type.
n Number of 8-bit bytes to For FIXED format binary n=2 for 16-bit
represent the integer integers; big-endian byte order. integers;
n=4 for 32-bit
integers
p Precision (total number of digits) For FIXED-format files only. Literal Number,
p. 4-237
s Scale (number of digits after the For FIXED-format files only. Literal Number,
decimal point) p. 4-237
(1 of 2)

2-132 Informix Guide to SQL: Syntax


CREATE EXTERNAL TABLE

Element Purpose Restrictions Syntax


null_string Value that is to be interpreted as For restriction information, refer Quoted String,
a null to “Defining Null Values.” p. 4-260
template Name of a table with the exact You cannot skip columns or put Database Object
column names and definitions data of a different type into any Name, p. 4-50
for your external table column.
(2 of 2)

Using the SAME AS Clause


When you create a table with the SAMEAS keyword, the column names from
the original table are used in the new table. You cannot use indexes in the
external table definition.

You cannot use the SAMEAS keyword for FIXED-format files.

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

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, you 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.

SQL Statements 2-133


CREATE EXTERNAL TABLE

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 that can be interpreted as a null
when the database server loads or unloads data from an external file. You can
define the null_string as a number that will not be used in 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.

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

2-134 Informix Guide to SQL: Syntax


CREATE EXTERNAL TABLE

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

During unloading, the database server escapes delimiters and backslashes


(\). During loading, any character that follows a backslash is taken literally.
Nonprintable characters are directly embedded in the data file if you choose
TEXT format.

User-defined delimiters are limited to one byte each. For information about
delimiters if you are using a multibyte locale, see the Informix Guide to GLS
Functionality.

For more information on BYTE and TEXT data, see your Administrator’s Guide.

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.

SQL Statements 2-135


CREATE EXTERNAL TABLE

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

NOT NULL
CHECK ( Condition )
p. 4-27

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.

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.

2-136 Informix Guide to SQL: Syntax


CREATE EXTERNAL TABLE

Check constraints are defined with search conditions. The search condition
cannot contain subqueries, aggregates, host variables, or SPL routines. In
addition, it cannot include the following built-in functions: CURRENT, USER,
SITENAME, DBSERVERNAME, or TODAY.

When you define a check constraint at the column level, the only column that
the check constraint can check against is the column itself. In other words, the
check constraint cannot depend upon values in other columns of the table.

DATAFILES Clause
The DATAFILES clause names the external files that are opened when you use
external tables.

DATAFILES Back to CREATE EXTERNAL TABLE p. 2-131


Clause Back to INTO EXTERNAL Clause p. 2-683

DATAFILES ( ' DISK : coserver_num : fixed_path ' )

PIPE coserver_group formatted_path

Element Purpose Restrictions Syntax


coserver_group Name of the coserver group that The coserver group must exist. Identifier, p. 4-205
contains the external data
coserver_num Numeric ID of the coserver that The coserver must exist. Literal Number,
contains the external data p. 4-237
fixed_path Pathname for describing the The specified path must exist. The pathname must
input or output files in the conform to the
external table definition conventions of your
operating system.
formatted_path Formatted pathname that uses The specified path must exist. The pathname must
pattern-matching characters conform to the
conventions of your
operating system.

SQL Statements 2-137


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

If you use only some of the available coservers for reading or writing files,
you can designate these coservers as a cogroup using onutil and then use the
cogroup name rather than explicitly naming each coserver and file
separately. Whenever you use all coservers to manage external files, you can
use the predefined coserver_group.

For examples of the DATAFILES clause, see the section, “Examples” on


page 2-144.

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 Purpose

%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) Names multiple files on a single coserver

Important: The formatted pathname option does not support the %o formatting
string.

2-138 Informix Guide to SQL: Syntax


CREATE EXTERNAL TABLE

Table Options
The optional table parameters include additional characteristics that define
the table.

Table Back to CREATE EXTERNAL TABLE


Options p. 2-131
,

FORMAT ' DELIMITED '


INFORMIX
FIXED

CODESET ' ASCII '


EBCDIC

DEFAULT

DELIMITER ' field_delimiter '


RECORDEND ' record_delimiter '
MAXERRORS num_errors

REJECTFILE ' filename '


ESCAPE

EXPRESS

DELUXE

SIZE num_rows

SQL Statements 2-139


CREATE EXTERNAL TABLE

Element Purpose Restrictions Syntax


filename Full directory path and If you do not specify REJECTFILE, Filename must
filename that you want all no reject files are created, and if conform to the
coservers to use as a desti- errors occur, the load task will conventions of your
nation when they write fail. operating system.
conversion error messages
field_delimiter Character to separate fields If you use a non-printing Quoted String,
The default value is the pipe character as a delimiter, you p. 4-260
(|) character. must encode it as the octal repre-
sentation of the ASCII character.
For example, '\006' can
represent CTRL-F.
num_errors Number of errors allowed per If you do not set the MAXERRORS Literal Number,
coserver before the database environment variable, the p. 4-237
server stops the load database server processes all
data regardless of the number of
errors. This parameter is ignored
during an unload task.
num_rows Approximate number of rows None. Literal Number,
contained in the external table p. 4-237
quoted_string ASCII character that represents Only one character is valid. Quoted String,
the escape p. 4-260
record_delimiter Character to separate records If you use a non-printing Quoted String,
If you do not set the character as a delimiter, you p. 4-260
RECORDEND environment must encode it as the octal repre-
variable, the default value is sentation of the ASCII character.
the newline character (\n). For example, '\006' can
represent CTRL-F.

2-140 Informix Guide to SQL: Syntax


CREATE EXTERNAL TABLE

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 that the database server should replace missing


(load only) values in delimited input files with column defaults (if they
are defined) instead of inserting nulls
This option allows input files to be sparsely populated. The
input files do not need to have 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 that causes the database server to load data in
deluxe mode
(load only)
Deluxe mode is required for loading into STANDARD tables.

ESCAPE Directs the database server to recognize ASCII special


characters embedded in ASCII-text-based data files
If you do not specify ESCAPE when you load data, the
database server does not check the character fields in text data
files for embedded special characters.
If you do not specify ESCAPE when you unload data, the
database server does not create embedded hexadecimal
characters in text fields.

EXPRESS Sets a flag that causes the database server to attempt to load
data in express mode
If you request express mode but indexes or unique constraints
exist on the table or the table contains BYTE or TEXT data, or
the target table is not RAW or OPERATIONAL, the load stops
with an error message reporting the problem.

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
(1 of 2)

SQL Statements 2-141


CREATE EXTERNAL TABLE

Keyword Purpose

RECORDEND Specifies the character that separates records in a delimited


text file

REJECTFILE Sets the full pathname for all coservers to the area where reject
files are written for data-conversion errors
If conversion errors occur and you have not specified
REJECTFILE or the reject files cannot be opened, the load job
ends abnormally.
For information on reject-file naming and use of formatting
characters, see “Reject Files” on page 2-142.

SIZE Specifies the approximate number of rows that are contained


in the external table
This option can improve performance if you use the external
table in a join query.
(2 of 2)
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 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 defined on the external table are written to a reject file on the
coserver that performs the conversion. Each coserver manages its own reject
file. The REJECTFILE keyword determines the name given to the reject file on
each coserver.

You can use the formatting characters %c and %n (but not %r) in the filename
format. Use the %c formatting characters to make the filenames unique. For
more information on formatting characters, see the section “Using
Formatting Characters” on page 2-138.

If you perform another load to the same table during the same session, any
earlier reject file of the same name is overwritten.

2-142 Informix Guide to SQL: Syntax


CREATE EXTERNAL TABLE

Reject file entries have the following format:


coserver-number, filename, record, reason-code,
field-name: bad-line

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

The reject file writes the coserver-number, filename, record, field-name and reason-
code in ASCII. The bad line information varies with the type of input file. For
delimited files or fixed-position character files, up to 80 characters of the bad
line are copied directly into the reject file. For Informix internal data files, the
bad line is not placed in the reject file, because you cannot edit the binary
representation in a file. However, coserver-number, filename, record, reason-code,
and field-name are still reported in the reject file so you can isolate the
problem.

The types of errors that cause a row to be rejected are as follows.

Error Text Explanation

CONSTRAINT constraint name This constraint was violated.

CONVERT_ERR Any field encounters a conversion error.

MISSING_DELIMITER No delimiter was found.


(1 of 2)

SQL Statements 2-143


CREATE EXTERNAL TABLE

Error Text Explanation

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.


(2 of 2)

Examples
The examples in this section show how you can name files to use in the
DATAFILES field.

Assume that the database server is running on four nodes, and one file is to
be read from each node. All files have the same name. The DATAFILES item
can then be as follows:
DATAFILES ("DISK:cogroup_all:/work2/[Link]/mytbl")

Now, consider a system with 16 coservers where only three coservers have
tape drives attached (for example, coservers 2, 5, and 9). If you define a
cogroup for these coservers before you run load and unload commands, you
can use the cogroup name rather than a list of individual coservers when you
execute the commands. To set up the cogroup, run onutil.
% onutil
1> create cogroup tape_group
2> from coserver.2, coserver.5, coserver.9;
Cogroup successfully created.

Then define the file locations for named pipes:


DATAFILES ("PIPE:tape_group:/usr/local/TAPE.%c")

The filenames expand as follows:


DATAFILES ("pip[Link]/usr/local/TAPE.2",
"pip[Link]/usr/local/TAPE.5",
"pip[Link]/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/[Link]/mytbl.%r(1..3)",
"DISK:2:/work2/[Link]/mytbl.%r(4..6)")

2-144 Informix Guide to SQL: Syntax


CREATE EXTERNAL TABLE

The expanded list is as follows:


DATAFILES ("disk:1:/work2/[Link]/mytbl.1",
"disk:1:/work2/[Link]/mytbl.2",
"disk:1:/work2/[Link]/mytbl.3",
"disk:2:/work2/[Link]/mytbl.4",
"disk:2:/work2/[Link]/mytbl.5",
"disk:2:/work2/[Link]/mytbl.6")

Related Information
Related statements: INSERT, SELECT, and SET PLOAD FILE

For more information on external tables, refer to your Administrator’s


Reference.

SQL Statements 2-145


CREATE FUNCTION

+ CREATE FUNCTION
IDS
Use the CREATE FUNCTION statement to create a user-defined function. With
this statement, you can register an external function or write and register an
SPL function.

Tip: If you are trying to create a function from text that is in a separate file, use the
CREATE FUNCTION FROM statement.

Syntax

CREATE FUNCTION function ( ) Return


Clause
Routine p. 4-270
DBA Parameter List
p. 4-286

, ;
SPECIFIC Specific
Name WITH ( Routine )
p. 4-296 Modifier
p. 4-274

Statement
SPL Block END FUNCTION
p. 4-298

External Routine
Ext Reference
p. 4-202
END FUNCTION

,
WITH LISTING IN 'pathname '
DOCUMENT Quoted String
p. 4-260

2-146 Informix Guide to SQL: Syntax


CREATE FUNCTION

Element Purpose Restrictions Syntax


function Name of the function to create You must have the appropriate Database Object
language privileges. For more Name, p. 4-50
information, see “GRANT” on
page 2-500.
Also see, “Naming a Function”
on page 2-148.
pathname Pathname to a file in which The specified pathname must Pathname and
compile-time warnings are exist on the computer where the filename must
stored database resides. conform to the
conventions of your
operating system.

Usage
The database server supports user-defined functions written in the following
languages:

■ Stored Procedure Language (SPL functions)


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 the manual uses the terms UDR, function, and
procedure as well as recommended usage, see “Relationship Between
Routines, Functions and Procedures” on page 2-201 and “Using CREATE
PROCEDURE Versus CREATE FUNCTION” on page 2-199, respectively.

The entire length of a CREATE FUNCTION statement must be less than


64 kilobytes. This length is the literal length of the statement, including blank
space 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. ♦

SQL Statements 2-147


CREATE FUNCTION

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

SPL By default, the Usage privilege on SPL is granted to PUBLIC. You must also
have at least the Resource privilege on a database to create an SPL function
within that database. ♦

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 do not use 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:

2-148 Informix Guide to SQL: Syntax


CREATE FUNCTION

■ 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 which uniquely identifies each
user-defined function, see “Routine Overloading and Naming UDRs with a
Routine Signature” on page 4-52.

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, shown in “SPL Functions” on page 2-150:
SELECT data FROM sysprocbody b, sysprocedures p
WHERE [Link] = [Link]
--join between the two catalog tables
AND [Link] = 'update_by_pct'
-- look for procedure named update_by_pct
AND [Link] = 'D'-- want user document;

SQL Statements 2-149


CREATE FUNCTION

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.

UNIX If you specify a filename but not a directory, this listing file is created in your
home directory on the computer where the database resides. If you do not
have a home directory on this computer, the file is created in the root
directory (the directory named “/”). ♦

Windows If you specify a filename but not a directory, this listing file is created in your
current working directory if the database is on the local machine. Otherwise,
the default directory is %INFORMIXDIR%\bin. ♦

SPL SPL Functions


SPL functions are UDRs written in Stored Procedure Language (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.

2-150 Informix Guide to SQL: Syntax


CREATE FUNCTION

SPL functions are parsed, optimized (as far as possible), and stored in the
system catalog tables in executable format. The body of an SPL function is
stored in the sysprocbody system catalog table. Other information about the
function is stored in other system catalog tables, including sysprocedures,
sysprocplan, and sysprocauth. For more information about these system
catalog tables, see the discussion of the system catalog in the Informix Guide
to SQL: Reference.

You must use the END FUNCTION keywords with an SPL function.

Place a semicolon after the clause that immediately precedes the statement
block.

Example of an SPL Function


The following 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 writing SPL functions, see the Informix Guide to SQL:
Tutorial. ♦

SQL Statements 2-151


CREATE FUNCTION

Ext External Functions


External functions are functions you write in an external language that
Dynamic Server supports.

To create a C user-defined function, follow these steps:

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.

To create a user-defined function written in Java, follow these steps:

1. Write a Java static method, which can use the JDBC functions to
interact with the database server.
2. Compile the Java source file and create a jar file (the shared-object file
for Java).
3. Execute the install_jar() procedure with the EXECUTE PROCEDURE
statement to install the jar file in the current database.
4. If the UDR uses user-defined types, create a map between SQL data
types and Java classes.
Use the setUDTExtName() procedure that is explained in
“EXECUTE PROCEDURE” on page 2-444.
5. Register the UDR with the CREATE FUNCTION statement.

Rather than storing the body of an external routine directly in the database,
the database server stores only the pathname of the shared-object file that
contains the compiled version of the routine. When the database server
executes the external routine, the database server invokes the external object
code.

The database server stores information about an external function in several


system catalog tables, including sysprocbody and sysprocauth. For more
information on these system catalog tables, see the Informix Guide to SQL:
Reference.

2-152 Informix Guide to SQL: Syntax


CREATE FUNCTION

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/[Link](basetype1_equal)"
LANGUAGE C
END FUNCTION

Java Example of Registering a User-Defined Function Written in Java


The following CREATE FUNCTION statement registers the user-defined
function, sql_explosive_reaction(). This function is discussed in
“sqlj.install_jar” on page 2-447:
CREATE FUNCTION sql_explosive_reaction(int) RETURNS int
WITH (class="jvp")
EXTERNAL NAME "course_jar:[Link]"
LANGUAGE JAVA

This function returns a single value of type INTEGER. The EXTERNAL NAME
clause specifies that the Java implementation of the sql_explosive_reaction()
function is a method called explosiveReaction(), which resides in the
Chemistry Java class that resides in the course_jar jar file.

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.

SQL Statements 2-153


CREATE FUNCTION

For example, assume that user mike creates the following user-defined
function:
CREATE FUNCTION func1 () RETURNING INT;
CREATE TABLE tab1 (colx INT);
RETURN 1;
END FUNCTION

If user joan now executes function func1, user mike, not user joan, is the
owner of the newly created table tab1.

However, in the case of a DBA-privileged UDR, the user who executes the
UDR—not the UDR owner—owns any database objects created by the UDR,
unless another owner is specified for the database object within the UDR.

For example, assume that user mike creates the following user-defined
function:
CREATE DBA FUNCTION func2 () RETURNING INT;
CREATE TABLE tab2 (coly INT);
RETURN 1;
END FUNCTION

If user joan now executes function func2, user joan, not user mike, is the
owner of the newly created table tab2.

Related Information
Related statements: ALTER FUNCTION, ALTER ROUTINE, CREATE
PROCEDURE, CREATE FUNCTION FROM, DROP FUNCTION, DROP ROUTINE,
GRANT, EXECUTE FUNCTION, PREPARE, REVOKE, and UPDATE STATISTICS

For a discussion on creating and using SPL routines, see the Informix Guide to
SQL: Tutorial.

For a discussion of how to create and use external routines, see Extending
Informix Dynamic Server 2000.

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

For more information on the NODEFDAC environment variable and the


relative system catalog tables (sysprocedures, sysprocplan, sysprocbody
and sysprocauth), see the Informix Guide to SQL: Reference.

2-154 Informix Guide to SQL: Syntax


CREATE FUNCTION FROM

+ CREATE FUNCTION FROM


IDS
Use the CREATE FUNCTION FROM statement to access a user-defined
E/C function. The actual text of the CREATE FUNCTION statement resides in a
separate file.

Syntax

CREATE FUNCTION FROM ' file '


file_var

Element Purpose Restrictions Syntax


file Pathname and filename of the The specified file must exist. Pathname and
file that contains the full text of a The file that you specify can filename must
CREATE FUNCTION statement contain only one CREATE conform to the
The default pathname is the FUNCTION statement. conventions of your
current directory. operating system.

file_var Name of a program variable that The file that is specified in the Name must conform
holds the value of file program variable must exist. to language-specific
The file that you specify can rules for variable
contain only one CREATE names.
FUNCTION statement.

Usage
An ESQL/C program cannot directly create a user-defined function. That is,
it cannot contain the CREATE FUNCTION statement. However, you can create
these functions within an ESQL/C program with the following steps:

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.

SQL Statements 2-155


CREATE FUNCTION FROM

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 (as
in the preceding example), the client application looks for the file in the
current directory.

Important: The ESQL/C preprocessor does not process the contents of the file that you
specify. It just sends the contents to the database server for execution. Therefore, there
is no syntactic check that the file that you specify in CREATE FUNCTION FROM
actually contains a CREATE FUNCTION statement. However, to improve readability
of the code, Informix recommends that you match these two statements.

Related Information
Related statements: CREATE FUNCTION, CREATE PROCEDURE, CREATE
PROCEDURE FROM, and CREATE ROUTINE FROM

2-156 Informix Guide to SQL: Syntax


CREATE INDEX

+
CREATE INDEX
Use the CREATE INDEX statement to create an index for one or more columns
in a table, to specify whether or not it allows only unique values, to cluster
the physical table in the order of the index, and to designate where the index
should be stored.

Syntax

CREATE INDEX index ON table

synonym XPS
Index Type
Options LOCK MODE
p. 2-159 Options
p. 2-181

Index Key
Specification
p. 2-161
IDS FILLFACTOR Storage IDS
Option Options
p. 2-171 p. 2-172 Index
USING
Access XPS Modes
Method p. 2-178
Clause USING BITMAP
p. 2-169

GK SELECT
XPS GK INDEX index ON static ( Clause )
p. 2-183
USING BITMAP

SQL Statements 2-157


CREATE INDEX

Element Purpose Restrictions Syntax


index Name of the index to create The name must be unique Database Object
within the database. Name, p. 4-50
The first byte of the name cannot
be a leading ASCII blank
(hex 20).
synonym Synonym for the name of the The synonym and the table to Database Object
table on which the index is which the synonym points must Name, p. 4-50
created already exist.
(IDS) This table cannot be a
virtual table.
static Name of the table on which a GK The table must exist. It must be a Database Object
index is created static table. Name, p. 4-50
table Name of the table on which the The table must exist. The table Database Object
index is created can be a regular database table Name, p. 4-50
or a temporary table.
(IDS) This table cannot be a
virtual table.

Usage
A secondary access method (sometimes referred to as an index access method) is
a set of database server functions that build, access, and manipulate an index
structure such as a B-tree, R-tree, or an index structure that a DataBlade
module provides. Typically, a secondary access method speeds up the
retrieval of data.

When you issue the CREATE INDEX statement, the table is locked in exclusive
mode. If another process is using the table, the database server cannot
execute the CREATE INDEX statement and returns an error.

XPS If you are using Extended Parallel Server, use the USING BITMAP keywords
to store the list of records in each key of the index as a compressed bitmap.
The storage option is not compatible with a bitmap index because bitmap
indexes must be fragmented in the same way as the table. ♦

2-158 Informix Guide to SQL: Syntax


CREATE INDEX

Index-Type Options
The index-type options let you specify the characteristics of the index.

Index-Type Back to CREATE INDEX


Options p. 2-157

UNIQUE CLUSTER

DISTINCT

UNIQUE or DISTINCT Option


Use the UNIQUE or DISTINCT keywords to require that the column or set of
columns on which the index is based accepts only unique data.

The following example creates a unique index:


CREATE UNIQUE INDEX c_num_ix ON customer (customer_num)

A unique index prevents duplicates 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
accomplishes the same task:
CREATE DISTINCT INDEX c_num_ix ON customer (customer_num)

The index in either example is maintained in ascending order, which is the


default order.

If you do not specify the UNIQUE or DISTINCT keywords in a CREATE INDEX


statement, the database server allows duplicate values in the indexed
column.

SQL Statements 2-159


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. For
more information on creating 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 option to reorder the physical table in the order that the
index designates. The CREATE CLUSTER INDEX statement fails if a CLUSTER
index already exists.
CREATE CLUSTER INDEX c_clust_ix ON customer (zipcode)

This statement creates an index on the customer table that physically orders
the table by zip code.

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.

XPS If you are using Extended Parallel Server, you cannot use the CLUSTER
option on STANDARD tables. In addition, you cannot use the CLUSTER option
and storage options in the same CREATE INDEX statement (see “Storage
Options” on page 2-172). When you create a clustered index the constrid of
any unique or referential constraints on the associated table changes. The
constrid is stored in the sysconstraints system catalog table. ♦

IDS Some secondary access methods (such as R-tree) do not support clustering.
Before you specify CLUSTER for your index, be sure that it uses an access
method that supports clustering. ♦

2-160 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-157

,
( column )
IDS , IDS
ASC
function ( func_col ) op_class DESC

Element Purpose Restrictions Syntax


column Name of the column or You must observe restrictions on the Identifier, p. 4-205
columns used as a key to location of the columns, the maximum
this index number of columns, the total width of
the columns, existing constraints on the
columns, and the number of indexes
allowed on the same columns.
See “Using a Column as the Index Key”
on page 2-163.
function Name of the user-defined This must be a nonvariant function. DataBase Object
function used as a key to The return type of the function cannot Name, p. 4-50
this index be BYTE or TEXT.
You cannot create an index on built-in
algebraic, exponential, log, or hex
functions.
(1 of 2)

SQL Statements 2-161


CREATE INDEX

Element Purpose Restrictions Syntax


func_col Name of the column or See “Using a Column as the Index Key” Identifier, p. 4-205
columns on which the on page 2-163.
user-defined function acts
op_class Operator class associated If you specify a secondary access Identifier, p. 4-205
with this column or method in the USING clause that does
function of the index not have a default operator class, you
must specify an operator class here.
If you use an alternative access method,
and if the access method has a default
operator class, you can omit the
operator class here.
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 information, see “Using an
Operator Class” on page 2-168.
(2 of 2)

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:

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

2-162 Informix Guide to SQL: Syntax


CREATE INDEX

Using a Column as the Index Key


Observe the following restrictions when you specify a column or columns as
the index key:

■ All the columns you specify must exist and must belong to the table
being indexed.
■ The maximum number of columns and the total width of all columns
vary with the database server. See “Creating Composite Indexes” on
page 2-164.
■ You cannot add an ascending index to a column or column list that
already has a unique constraint on it. See “Using the ASC and DESC
Sort-Order Options” on page 2-164.
■ You cannot add a unique index to a column or column list that has a
primary-key constraint on it. The reason is that defining the column
or column list as the primary key causes the database server to create
a unique internal index on the column or column list. So you cannot
create another unique index on this column or column list with the
CREATE INDEX statement.
■ The number of indexes you can create on the same column or same
sequence of columns is restricted. See “Restrictions on the Number
of Indexes on a Single Column” on page 2-167 and “Restrictions on
the Number of Indexes on a Sequence of Columns” on page 2-167.
IDS ■ You cannot create an index on a column that belongs to an external
table.
■ The column you specify cannot be a column whose data type is a
collection. ♦

IDS Using a Function as an Index Key


You can create an index on a user-defined function. You can also create
functional indexes within an SPL routine.

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 returned by the specified


function rather than on the value of a column.

SQL Statements 2-163


CREATE INDEX

For example, the following statement creates a functional index on table


zones using the value returned by the function Area() as the key:
CREATE INDEX zone_func_ind ON zones (Area(length,width));

Creating Composite Indexes


Place columns in a composite index in the order from most-frequently used
to least-frequently used.

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 index 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 CREATE INDEX statement cannot exceed
255 bytes. ♦

XPS
IDS A composite index can have up to 16 key parts. An index key part is either a
table column or the result of a user-defined function on one or more table
columns. A composite index can have any of the following items as an index
key:

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

Using the ASC and DESC Sort-Order Options


Use the ASC option to specify an index that is maintained in ascending order.
The ASC option is the default ordering scheme. Use the DESC option to
specify an index that is maintained in descending order.

You can use these options with B-trees only.

2-164 Informix Guide to SQL: Syntax


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 allowed:
CREATE TABLE customer (
customer_num SERIAL(101) UNIQUE,
fname CHAR(15),
lname CHAR(15),
company CHAR(20),
address1 CHAR(20),
address2 CHAR(20),
city CHAR(15),
state CHAR(2),
zipcode CHAR(5),
phone CHAR(18)
)

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 example places an index sorted in descending
order on the customer_num column. The second CREATE INDEX example
includes the customer_num column as part of a composite index. For more
information on composite indexes, see “Creating Composite Indexes” on
page 2-164.

Bidirectional Traversal of Indexes


When you create an index on a column but do not specify the ASC or DESC
keywords, the database server stores the key values in ascending order by
default.

However, the bidirectional-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.

SQL Statements 2-165


CREATE INDEX

Because of this capability, it does not matter whether you create a single-
column index as an ascending or descending index. Whichever storage order
you choose for an index, the database server can traverse that index in
ascending or descending order when it processes queries.

However, if you create a composite index on a table, the ASC and DESC
keywords might be required. For example, if you want to enter a SELECT
statement whose ORDER BY clause sorts on multiple columns and sorts each
column in a different order and you want to use an index for this query, you
need to create a composite index that corresponds to the ORDER BY columns.

For example, suppose that you want to enter the following query:
SELECT stock_num, manu_code, description, unit_price
FROM stock
ORDER BY manu_code ASC, unit_price DESC

This query sorts first in ascending order by the value of the manu_code
column and then in descending order by the value of the unit_price column.
To use an index for this query, you need to issue a CREATE INDEX statement
that corresponds to the requirements of the ORDER BY clause. For example,
you can enter either of the following statements to create the index:
CREATE INDEX stock_idx1 ON stock
(manu_code ASC, unit_price DESC);

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;

2-166 Informix Guide to SQL: Syntax


CREATE INDEX

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

Restrictions on the Number of Indexes on a Single Column


You can create only one ascending index and one descending index on a
single column.

Because of the bidirectional traversal capability of the database server, you


do not need to create both indexes in practice. You only need to create one of
the indexes. Both of these indexes would achieve exactly the same results for
an ascending or descending sort on the stock_num column.

Restrictions on the Number of Indexes on a Sequence of Columns


You can create multiple indexes on a sequence 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 the following 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

SQL Statements 2-167


CREATE INDEX

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 exactly the same results for sorts in
which the user specifies the same sort direction (ascending or
descending) for both columns. Therefore, you only need to create
one index of this pair.
■ The ix3 and ix4 indexes achieve exactly the same results for sorts in
which the user specifies different sort directions for the two columns
(ascending on the first column and descending on the second column
or vice versa). Therefore, you only need to create one index of this
pair.

For further information on the bidirectional-traversal capability of the


database server, see “Bidirectional Traversal of Indexes” on page 2-165.

IDS Using an Operator Class


An operator class is the set of operators the database server associates with a
secondary access method for query optimization and building the index.

Specify an operator class when you create an index if you have one of the
following situations:

■ A default operator class for the secondary access method does not
exist. For example, some of the user-defined access methods do not
provide a default operator class.
■ You want to use an operator class that is different from the default
operator class that the secondary access method provides.

For more information, see “Default Operator Classes” on page 2-197. The
following CREATE INDEX statement creates a B-tree index on the cust_tab
table that uses the abs_btree_ops operator class for the cust_num key:
CREATE INDEX c_num1_ix ON cust_tab (cust_num abs_btree_ops);

2-168 Informix Guide to SQL: Syntax


CREATE INDEX

IDS USING Access Method Clause


Use the USING clause to specify the secondary access method to use for the
new index.

USING Access Method Back to CREATE INDEX


Clause p. 2-157
,

USING sec_acc_method ( parameter = value )

Element Purpose Restrictions Syntax


parameter Name of the The parameter name must be one of the Quoted String,
secondary access- strings allowed for this secondary access p. 4-260
method parameter method. For more information, refer to the
used with this user documentation for your user-defined
index access method.
sec_acc_method Name of the The access method can be a B-tree, R-tree, or Identifier,
secondary access user-defined access method, such as one that p. 4-205
method used with was defined by a DataBlade module. The
the index you are access method must be a valid access method
creating 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
restriction does not apply to other secondary
access methods.
value Value of the The parameter value must be one of the Quoted String,
specified quoted strings or literal numbers allowed for p. 4-260 or Literal
parameter this secondary access method. Number, p. 4-237

A secondary access method is a set of routines that perform all of the operations
needed to make an index available to a server, such as create, drop, insert,
delete, update, and scan.

SQL Statements 2-169


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
values. The database server implements this secondary access
method and registers it as btree in the system catalog tables of a
database.
■ The R-tree secondary access method is a registered secondary access
method.
An R-tree index is good for searches on multi-dimensional data
(such as box, circle, and so forth). The database server registers
this secondary access method as rtree in the system catalog tables
of a database. For more information on R-tree indexes, see the
Informix R-Tree Index User’s Guide.

Some user-defined access methods are packaged as DataBlades. For more


information about user-defined access methods, refer to your access-method
or DataBlade user guides.
By default, the CREATE INDEX statement 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.

The following example assumes that the database implements the R-tree
index. It creates an R-tree index on the location column that contains an
opaque data type, point.
CREATE INDEX loc_ix ON TABLE emp (location)
USING rtree;
SELECT name FROM emp
WHERE location N_equator_equals point('500, 0');

The sample query has a filter on the location column.

Some DataBlade modules provide indexes that require specific parameters


when you create them.

2-170 Informix Guide to SQL: Syntax


CREATE INDEX

Example of an Index with Parameters


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

FILLFACTOR Option
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-157

FILLFACTOR percent

Element Purpose Restrictions Syntax


percent Percentage of each index page Value must be in the range 1 to Literal Number,
that is filled by index data when 100. p. 4-237
the index is created
The default value is 90.

When the index is created, the database server initially fills only that
percentage of the nodes specified with the FILLFACTOR value.

The FILLFACTOR option takes effect only when you build an index on a table
that contains more than 5,000 rows and uses more than 100 table pages, when
you create an index on a fragmented table, or when you create a fragmented
index on a nonfragmented table.

The FILLFACTOR can also be set as a parameter in the ONCONFIG file. The
FILLFACTOR clause on the CREATE INDEX statement overrides the setting in
the ONCONFIG file.

SQL Statements 2-171


CREATE INDEX

For more information about the ONCONFIG file and the parameters you can
use with ONCONFIG, 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.

Providing a High Percentage Value


If you provide a high percentage value, such as 99, your indexes are com-
pacted, 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 let you specify the distribution scheme of an index. You
can use the IN clause to specify a storage space to hold the entire index, or you
can use the FRAGMENT BY clause to fragment the index across multiple
storage spaces

2-172 Informix Guide to SQL: Syntax


CREATE INDEX

Storage Back to CREATE INDEX


Options p. 2-157

IN dbspace

XPS dbslice
IDS

extspace

FRAGMENT BY
Clause for Indexes
p. 2-175

Element Purpose Restrictions Syntax


dbslice Name of the dbslice that The dbslice must exist when you Identifier, p. 4-205
contains all of the index execute the statement.
fragments
dbspace Name of the dbspace in which The dbspace must exist when Identifier, p. 4-205
you want to place the index you execute the statement.
extspace Name assigned with the The specified extspace must Refer to the user
onspaces command to a storage already exist. documentation for
area outside the database server your custom access
method for more
information.

If you do not use the storage options (that is, if you do not specify a distri-
bution scheme), by default the index inherits the distribution scheme as of
the table on which it is built. Such an index is called an attached index.

An attached index is created in the same dbspace (or dbspaces if the table is
fragmented) as the table on which it is built. If the distribution scheme of a
table changes, all attached indexes start using the new distribution scheme.

SQL Statements 2-173


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

If you are using Extended Parallel Server, you cannot use the CLUSTER
option and storage options in the same CREATE INDEX statement. See
“CLUSTER Option” on page 2-160. ♦

IN Clause
Use the IN clause to specify a storage space to hold the entire index. The
storage space that you specify must already exist.

Storing an Index in a dbspace


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.

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
the table is created.

2-174 Informix Guide to SQL: Syntax


CREATE INDEX

IDS Storing an Index in an extspace


In general, you use this option in conjunction with the “USING Access
Method Clause” on page 2-169. You can also store an index in an sbspace. For
more information, refer to the user documentation for your custom access
method.

FRAGMENT BY Clause for Indexes


Use the FRAGMENT BY clause to fragment an index across multiple dbspaces.

FRAGMENT BY Back to Storage Options


Clause for Indexes p. 2-172
,

FRAGMENT BY EXPRESSION expr IN dbspace , expr IN dbspace

, REMAINDER IN dbspace
XPS

, ,

HASH ( column ) IN dbspace , dbspace

IN dbslice
,
HYBRID ( column )

,
EXPRESSION expr IN dbslice , expr IN dbslice

REMAINDER

dbspace dbspace
, ,
( dbspace ) ( dbspace )

SQL Statements 2-175


CREATE INDEX

Element Purpose Restrictions Syntax


column Name of the column on which All specified columns must be in Identifier, p. 4-205
you want to fragment your the current table.
index If you specify a serial column,
you cannot specify any other
column.
dbslice Name of the dbslice that The dbslice must exist when you Identifier, p. 4-205
contains all of the index execute the statement.
fragments
dbspace Name of the dbspace that will The dbspaces must exist at the Identifier, p. 4-205
contain an index fragment that time you execute the statement.
expr defines You can specify a maximum of
2,048 dbspaces.
expr Expression that defines which Each fragment expression can Expression, p. 4-73,
index keys are stored in a contain only columns from the and Condition,
fragment current table and only data p. 4-27
values 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.
No subqueries, user-defined
routines, aggregates, or refer-
ences to the fields of a row-type
column are allowed. In addition,
no built-in current, date and/or
time functions are allowed.

When you use this clause, you create a detached index.

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 colocality can be guaranteed. If the data tuple and index tuple colocality
does not exist, then the index is a globally detached index. For performance
implications of globally-detached indexes, see your Performance Guide.

2-176 Informix Guide to SQL: Syntax


CREATE INDEX

For more information on the expression, hash, and hybrid distribution


schemes, see “Fragmenting by EXPRESSION” on page 2-262; “Fragmenting
by HASH” on page 2-263; and “Fragmenting by HYBRID” on page 2-264,
respectively in 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.

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 it, the
database server creates the index in the first dbspace that the DBSPACETEMP
environment variable specifies.

For more information on the default storage characteristics of temporary


tables, see “Where Temporary Tables are Stored” on page 2-293.

For more information on the DBSPACETEMP environment variable, see the


Informix Guide to SQL: Reference.

SQL Statements 2-177


CREATE INDEX

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

DISABLED

ENABLED

FILTERING

WITHOUT ERROR

WITH ERROR

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.
(1 of 2)

2-178 Informix Guide to SQL: Syntax


CREATE INDEX

Mode Purpose

FILTERING The database server updates a unique index after insert, delete, and
update operations that modify the base table. (This option is not
available with duplicate indexes.)
The optimizer uses the index during query execution.
If an insert or update operation causes a duplicate key value to be
added to a unique index in filtering mode, the statement continues
processing, but the bad row is written to the violations table
associated with the base table. Diagnostic information about the
unique-index violation is written to the diagnostics table associated
with the base table.
(2 of 2)
If you specify filtering for a unique index, you can also specify one of the
following error options.

Error Option Purpose

WITHOUT When a unique-index violation occurs during an insert or update


ERROR operation, no integrity-violation error is returned to the user.

WITH When a unique-index violation occurs during an insert or update


ERROR operation, an integrity-violation error is returned to the user.

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

SQL Statements 2-179


CREATE INDEX

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

2-180 Informix Guide to SQL: Syntax


CREATE INDEX

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 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. So you cannot create a new index on a column or set of columns
if a disabled index on that column or set of columns already exists.

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.

XPS LOCK MODE Options


Use the lock modes to specify the locking granularity of the index.

LOCK MODE Back to CREATE INDEX


Options p. 2-157

LOCK MODE COARSE

NORMAL

When you use the coarse-lock mode, index-level locks are acquired on the
index instead of item-level or page-level locks. This mode reduces the
number of lock calls on an index.

SQL Statements 2-181


CREATE INDEX

Use the coarse-lock mode when you know the index is not going to change,
that is, when read-only operations are performed on the index.

If you do not specify a lock mode, the default is normal. That is, the database
server places item-level or page-level locks on the index as necessary.

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 table being indexed. A GK index stores information about the records in
a table based on the results of a query. Only tables created with the STATIC
type can be used in a GK index.

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 increase 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 non-static while a GK index depends on
that table, the database server returns an error.
■ Since any table involved in a GK index needs to be a static type,
UPDATE, DELETE, INSERT, and LOAD operations may not be
performed 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.

2-182 Informix Guide to SQL: Syntax


CREATE INDEX

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 the SELECT statement. The syntax of the
GK SELECT clause has the same format as the syntax for “SELECT” on
page 2-634.

GK SELECT Back to CREATE INDEX


Clause p. 2-157
,
GK
Expression FROM
SELECT p. 4-73 Clause
ALL p. 2-184 GK
WHERE
DISTINCT * Clause
p. 2-185
+
table.
UNIQUE
synonym.
alias.

Element Purpose Restrictions Syntax


alias Temporary name assigned to the You cannot use an alias for a Identifier, p. 4-205
table in the FROM clause select clause unless you assign
the alias to the table in the FROM
clause.
You cannot use an alias for the
table on which the index is being
built.
synonym Name of the synonym from The synonym and the table to Database Object
which you want to retrieve data which the synonym points must Name, p. 4-50
exist.
table Name of the table from which The table must exist. Database Object
you want to retrieve data Name, p. 4-50

The following limitations apply to the expression in the GK SELECT clause:


■ The expression cannot refer to any SPL routine.
■ The expression cannot include the USER, TODAY, CURRENT, DBINFO
built-in functions or any function that refers to a time or a time
interval.

SQL Statements 2-183


CREATE INDEX

FROM Clause for Generalized-Key Index

GK FROM Back to GK SELECT Clause


Clause p. 2-183

FROM indexed_table

synonym
, table

synonym alias

AS

Element Purpose Restrictions Syntax


alias Temporary name for a table You cannot use an alias with Identifier, p. 4-205
indexed_table.
indexed_table Name of the table on which the The FROM clause must include Database Object
index is being built the indexed table. Name, p. 4-50
synonym Synonym for the table from The synonym and the table to Database Object
which you want to retrieve data which the synonym points must Name, p. 4-50
exist.
table Name of the table from which The table must exist. Database Object
you want to retrieve data Name, p. 4-50

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)

2-184 Informix Guide to SQL: Syntax


CREATE INDEX

WHERE Clause for Generalized-Key Index

GK WHERE Back to GK SELECT Clause


Clause p. 2-183

AND

WHERE Condition
p. 4-27

Join
p. 2-666

The WHERE clause for a GK index has the following limitations:

■ The clause cannot include USER, TODAY, CURRENT, DBINFO built-in


functions or any functions that refer to time or a time interval.
■ The clause cannot refer to any SPL routine.
■ The clause cannot have any subqueries.
■ The clause cannot use any aggregate function.
■ The clause cannot have any IN, LIKE, or MATCH clauses.

Related Information
Related statements: ALTER INDEX, CREATE OPCLASS, CREATE TABLE, DROP
INDEX, and SET Database Object Mode

For a discussion of the structure of indexes, see your Administrator’s Reference.

For a discussion on 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
Informix Guide to GLS Functionality. ♦

For information about operator classes, refer to the CREATE OPCLASS


statement and Extending Informix Dynamic Server 2000.

For information about the indexes provided by DataBlade modules, refer to


your DataBlade module user’s guide.

SQL Statements 2-185


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

Element Purpose Restrictions Syntax


length Number of bytes needed by the The number must match the Literal Number,
database server to store a value positive integer reported when p. 4-237
of this data type the C language sizeof() directive
is applied to the type structure.
type Name of the new opaque data The name you specify must Identifier, p. 4-205
type follow the conventions of SQL Data Type, p. 4-53
identifiers.
The type must be unique within
the database.
In an ANSI-compliant database,
the combination
[Link] must be unique
within the database.

Usage
The CREATE OPAQUE TYPE statement registers a new opaque type in the
database. Dynamic Server stores information on extended data types,
including opaque types, in the sysxtdtypes system catalog table.

2-186 Informix Guide to SQL: Syntax


CREATE OPAQUE TYPE

Privileges on Opaque Types


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 find out what privileges exist on a particular type, check the sysxtdtypes
system catalog table for the owner name and the sysxtdtypeauth system
catalog table for additional type privileges that might have been granted. For
more information on system catalog tables, see the Informix Guide to SQL:
Reference.

DB The DB-Access utility can also display privileges on opaque types. ♦

Naming an Opaque Type


The actual name of an opaque 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_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 opaque-type owner is stored in uppercase letters. ♦

INTERNALLENGTH Modifier
The INTERNALLENGTH modifier specifies the size of an opaque type. The
way you specify the internal length defines whether the opaque type is fixed
length or varying length.

Fixed-Length Opaque Types


A fixed-length opaque type has an internal structure that has a fixed size. To
create a fixed-length opaque type, specify the size of the internal structure, in
bytes, for the INTERNALLENGTH modifier. The following statement creates a
fixed-length opaque type called fixlen_typ. The database server allocates
8 bytes for this type.
CREATE OPAQUE TYPE fixlen_typ(INTERNALLENGTH=8, CANNOTHASH)

SQL Statements 2-187


CREATE OPAQUE TYPE

Varying-Length Opaque Types


A varying-length opaque type has an internal structure whose size might
vary from one instance of the opaque type 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 type, use the VARIABLE keyword for the
INTERNALLENGTH modifier. The following statement creates a variable-
length opaque type called varlen_typ:
CREATE OPAQUE TYPE varlen_typ(INTERNALLENGTH=VARIABLE,
MAXLEN=1024)

Opaque-Type Modifier

Opaque-Type Modifier Back to CREATE OPAQUE TYPE


p. 2-186

MAXLEN = length

CANNOTHASH

PASSEDBYVALUE

ALIGNMENT = align_value

2-188 Informix Guide to SQL: Syntax


CREATE OPAQUE TYPE

Element Purpose Restrictions Syntax


align_value Byte boundary on which the The alignment must be 1, 2, 4, or Literal Number,
database server aligns the 8, depending on the C definition p. 4-237
opaque type when passing it to a of the opaque type and the
user-defined routine hardware and compiler used to
build the object file for the type.
If alignment is not specified, the
system default is 4 bytes.
length Maximum length in bytes to The length must be a positive Literal Number,
allocate for instances of the type integer less than or equal to p. 4-237
in varying-length opaque types 32 kilobytes. Do not specify for
fixed-length types.
If maximum length is not Values that exceed this length
specified for a variable-length return errors.
type, the default is 2 kilobytes.

Use modifiers to specify the following optional information:

■ MAXLEN specifies the maximum length for varying-length opaque


types.
■ CANNOTHASH specifies that the database server cannot use a hash
function on the opaque type.
You must provide an appropriate hash function for the database
server to evaluate GROUP BY clauses on the 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.
■ ALIGNMENT specifies the byte boundary on which the database
server aligns the opaque type.

SQL Statements 2-189


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 language:

■ A data structure that serves as the internal storage of the opaque type
The internal storage details of the data type are hidden, or opaque.
Once you define a new opaque type, the database server can manip-
ulate it without knowledge of the C structure in which it is stored.
■ Support functions that allow the database server to interact with this
internal structure
The support functions tell the database server how to interact with
the internal structure of the type. These support functions must be
written in the C programming language.
■ Additional user-defined functions that can be called by other
support functions or by end users to operate on the opaque type
(optional)
Possible support functions include operator functions and cast
functions. Before you can use these functions in SQL statements, they
must be registered with the appropriate DEFINE CAST, CREATE
PROCEDURE, or CREATE FUNCTION statement.

The following table summarizes the support functions for an opaque type.

Function Purpose 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 repre- When the database server sends a
sentation 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 opaque
internal representation on the server computer type in an INSERT, UPDATE, or
Provides platform-independent results regardless LOAD statement
of differences between client and server computer
types.
(1 of 2)

2-190 Informix Guide to SQL: Syntax


CREATE OPAQUE TYPE

Function Purpose 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 opaque
representation on the client computer type as a result of a SELECT or
Provides platform-independent results regardless FETCH statement
of differences between client and database server
computer types.
import Performs any tasks need to convert from the When DB-Access (LOAD) or the High
external (character) representation of an opaque Performance Loader initiates a bulk
type to the internal representation for a bulk copy copy from a text file to a database
export Performs any tasks need to convert from the When DB-Access (UNLOAD) or the
internal representation of an opaque type to the High Performance Loader initiates a
external (character) representation for a bulk copy bulk copy from a database to a text file
importbinary Performs any tasks need to convert from the When DB-Access (LOAD) or the High
internal representation of an opaque type on the Performance Loader initiates a bulk
client computer to the internal representation on copy from a binary file to a database
the server computer for a bulk copy
exportbinary Performs any tasks need to convert from the When DB-Access (UNLOAD) or the
internal representation of an opaque type on the High Performance Loader initiates a
server computer to the internal representation on bulk copy from a database to a binary
the client computer for a bulk copy file
assign() Performs any processing required before storing When the database server executes an
the opaque type to disk INSERT, UPDATE, and LOAD
This support function must be named assign(). statement, before 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 and DROP TABLE state-
This support function must be named destroy(). ments, before it removes the opaque
type from disk
lohandles() Returns a list of the LO-pointer structures Whenever the database server must
(pointers to smart large objects) in an opaque type search opaque types for references to
smart large objects: when the oncheck
utility runs, when an archive is
performed
compare() Compares two values of the opaque type and When the database server encounters
returns an integer value to indicate whether the an ORDER BY, UNIQUE, DISTINCT,
first value is less than, equal to, or greater than the or UNION clause in a SELECT
second value statement, or when it executes the
CREATE INDEX statement to create a
B-tree index
(2 of 2)

SQL Statements 2-191


CREATE OPAQUE TYPE

Once you write the necessary support functions for the opaque type, use the
CREATE FUNCTION statement to register these support functions in the same
database as the opaque type. Certain support functions convert other data
types to or from the new opaque type. After you create and register these
support functions, use the CREATE CAST statement to associate each function
with a particular cast. The cast must be registered in the same database as the
support function.

When you have written the necessary source code to define the opaque type,
you then use the CREATE OPAQUE TYPE statement to register the opaque type
in the database.

Related Information
Related statements: CREATE CAST, CREATE DISTINCT TYPE, CREATE
FUNCTION, CREATE ROW TYPE, CREATE TABLE, and DROP TYPE

For a summary of an opaque type, see the Informix Guide to SQL: Reference.

For information on how to define an opaque type, see Extending Informix


Dynamic Server 2000.

For information about the GLS aspects of the CREATE OPAQUE TYPE
statement, refer to the Informix Guide to GLS Functionality.

2-192 Informix Guide to SQL: Syntax


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-195 SUPPORT support_function

Element Purpose Restrictions Syntax


opclass Name of the operator class being The operator class name must be Database Object
created unique within the database. Name, p. 4-50
sec_acc_method Name of the secondary access The secondary access method Identifier, p. 4-205
method with which the specified must already exist and must be
operator class is being associated registered in the sysams system
catalog table.
The database server provides the
B-tree and R-tree secondary
access method.
support_function Name of a support function The support functions must be Identifier, p. 4-205
required by the specified listed in the order expected by
secondary access method the specified access method.

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.

SQL Statements 2-193


CREATE OPCLASS

You define a new operator class when you want:

■ an index to use a different order for the data than the sequence
provided by the default operator class.
■ a set of operators that is different from any existing operator classes
that are associated with a particular secondary access method.

You must have the Resource privilege or be the DBA to create an operator
class. The actual name of an operator class is an SQL identifier. When you
create an operator class, opclass name must be unique within a database.

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)

For more information on the btree secondary access method, see “Default
Operator Classes” on page 2-197.

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 statement, the abs_btree_ops operator class has five
strategy functions.
■ Support functions
Specify support functions of an operator class in the SUPPORT clause
of the CREATE OPCLASS statement. In the preceding CREATE
OPCLASS statement, the abs_btree_ops operator class has one
support function.

2-194 Informix Guide to SQL: Syntax


CREATE OPCLASS

STRATEGIES Clause
Strategy functions are functions that end users can invoke within an SQL
statement to operate on a data type. The query optimizer uses the strategy
functions to determine if a particular index can be used to process a query. If
an index exists on a column or user-defined function in a query, and the
qualifying operator in the query matches one of the strategy functions in the
Strategy Specification list, the optimizer considers using the index for the
query. For more information on query plans, see your Performance Guide.

When you create a new operator class, you specify the strategy functions for
the secondary access method in the STRATEGIES clause. The Strategy Specifi-
cation lists the name of each strategy function. List these functions in the
order that the secondary access method expects. For the specific order of
strategy operators for the default operator classes for a B-tree index and an
R-tree index, see Extending Informix Dynamic Server 2000.

Strategy Specification

Strategy Specification Back to CREATE OPCLASS, p. 2-193

strategy_function
,
( 2 input_type )
output_type

SQL Statements 2-195


CREATE OPCLASS

Element Purpose Restrictions Syntax


input_type Data type of the input argument This is the data type for which Data Type, p. 4-53
for the strategy function you want to use a specific
secondary access method.
A strategy function takes two
input arguments and one
optional output argument.
output_type Data type of the optional output This is an optional output Data Type, p. 4-53
argument for the strategy argument for side effect indexes.
function
strategy_function Name of a strategy function to The operators must be listed in Database Object
associate with the specified the order expected by the Name, p. 4-50
operator class specified secondary access
method.

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, you 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 user-defined data types as well as built-in types. If you do not
specify the function signature, the database server assumes that each strategy
function takes two arguments of the same data type and returns a boolean
value.

2-196 Informix Guide to SQL: Syntax


CREATE OPCLASS

Side-Effect Indexes
Side-effect data is additional data that a strategy function returns when
Dynamic Server executes a query containing the strategy function. For
example, an image DataBlade module might use a fuzzy index to search
image data. The index ranks the images according to how closely they match
the search criteria. The database server returns the rank value as the side-
effect data, along with the qualifying images.

SUPPORT Clause
Support functions are functions that the secondary access method uses inter-
nally to build and search the index. You specify the support functions for the
secondary access method in the SUPPORT clause of the CREATE OPCLASS
statement.

You must list the names of the support functions in the order that the
secondary access method expects. For the specific order of support operators
for the default operator classes for a B-tree index and an R-tree index, refer to
“Default Operator Classes” on page 2-197.

The support function is an external function. The CREATE OPCLASS


statement does not verify that a named support function exists. However, for
the secondary access method to use a support function, 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 creates 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)

SQL Statements 2-197


CREATE OPCLASS

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 of a database. 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 DataBlade modules implement the R-tree opera-
tor-class functions.

For information on the operator-class functions of these operator classes,


refer to the chapter on operator classes in Extending Informix Dynamic
Server 2000.

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

Related Information
Related statements: CREATE FUNCTION, CREATE INDEX, and DROP OPCLASS

For information on how to create and extend an operator class, see Extending
Informix Dynamic Server 2000.

For information about the R-tree index, see the Informix R-Tree Index User’s
Guide.

For information about the GLS aspects of the CREATE OPCLASS statement,
refer to the Informix Guide to GLS Functionality.

2-198 Informix Guide to SQL: Syntax


CREATE PROCEDURE

+
CREATE PROCEDURE
Use the CREATE PROCEDURE statement to create a user-defined procedure.

Tip: If you are trying to create a procedure from text that is in a separate file, use the
CREATE PROCEDURE FROM statement.

Using CREATE PROCEDURE Versus CREATE FUNCTION


XPS In Extended Parallel Server, in addition to using this statement to create an
SPL procedure, you must use the CREATE PROCEDURE statement 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 the CREATE PROCEDURE statement
to write and register an SPL routine that returns one or more values (that is,
an SPL function), Informix recommends that you use the CREATE FUNCTION
statement. To register an external function, you must use the CREATE
FUNCTION statement.

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

SQL Statements 2-199


CREATE PROCEDURE

Syntax

CREATE PROCEDURE procedure ( )


SPL Routine
DBA
function Parameter List
p. 4-286

SPL IDS IDS ,


Return Clause Specific Name SPL
SPECIFIC
p. 4-270 p. 4-296 Routine
WITH ( Modifier )
p. 4-274

Statement
SPL Block END PROCEDURE
p. 4-298
;
IDS External Routine
Reference
Ext p.4-202
END PROCEDURE

,
WITH LISTING IN 'pathname'
DOCUMENT Quoted String
p. 4-260

2-200 Informix Guide to SQL: Syntax


CREATE PROCEDURE

Element Purpose Restrictions Syntax


function Name of the SPL function to (XPS) The name must be unique Database Object
create among all SPL routines in the Name, p. 4-50
database.
(IDS) See “Naming a Procedure
in Dynamic Server” on
page 2-203.
pathname Pathname to a file in which The specified pathname must The pathname and
compile-time warnings are exist on the computer where the filename must
stored database resides. conform to the
conventions of your
operating system.
procedure Name of the user-defined (XPS) The name must be unique Database Object
procedure to create among all SPL routines in the Name, p. 4-50
database.
(IDS) See “Naming a Procedure
in Dynamic Server” on
page 2-203.

Usage
The entire length of a CREATE PROCEDURE statement must be less than
64 kilobytes. This length is the literal length of the CREATE PROCEDURE
statement, including blank space and tabs.

E/C In ESQL/C, you can use a CREATE PROCEDURE statement only within a
PREPARE statement. If you want to create a procedure for which the text is
known at compile time, you must use a CREATE PROCEDURE FROM
statement. ♦

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.

SQL Statements 2-201


CREATE PROCEDURE

You can write a UDR in SPL (SPL routine) or in an external language (external
routine) that the database server supports. Consequently, anywhere the term
UDR appears in the manual, its significance applies to both SPL routines and
external routines. Likewise, the term user-defined procedure applies to SPL
procedures and external procedures. Similarly, the term user-defined
function applies to SPL functions and external functions.

SPL In earlier Informix products, the term stored procedure was used for both SPL
procedures and SPL functions. In this manual, the term SPL routine replaces
the term stored procedure. When it is necessary to distinguish between an
SPL function and an SPL procedure, the manual does so. ♦

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. However, the
term user-defined routine (UDR) encompasses both the terms SPL routine and
external routine. Therefore, wherever the term UDR appears it is applicable
to SPL routines. ♦

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

SPL By default, the Usage privilege on SPL is granted to PUBLIC. You must also
have at least the Resource privilege on a database to create an SPL procedure
within that database. ♦

DBA Keyword and Privileges on the Created Procedure


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.

2-202 Informix Guide to SQL: Syntax


CREATE PROCEDURE

If you do not use 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.

XPS Naming a Procedure in Extended Parallel Server


In Extended Parallel Server, you must specify a unique name for the SPL
routine that you create. The name must be unique among 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-52.

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.

SQL Statements 2-203


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

Anyone with access to the database can query the sysprocbody system
catalog table to obtain a description of one or all the UDRs stored in the
database.

For example, to find the description of the SPL procedure raise_prices, shown
in “SPL Procedures” on page 2-205, enter a query such as the following
example:
SELECT data FROM sysprocbody b, sysprocedures p
WHERE [Link] = [Link]
--join between the two catalog tables
AND [Link] = 'raise_prices'
-- look for procedure named raise_prices
AND [Link] = 'D';-- want user document

The preceding query returns the following text:


USAGE: EXECUTE PROCEDURE raise_prices( xxx )
xxx = percentage from 1 - 100

A UDR or application program can query the system catalog tables to fetch
the DOCUMENT clause and display it for a user.

Ext You can use a DOCUMENT clause at the end of the CREATE PROCEDURE
statement, whether or not you use the END PROCEDURE keywords. ♦

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.

If you do not use the WITH LISTING IN clause, the compiler does not generate
a list of warnings.

This listing file is created on the computer where the database resides.

2-204 Informix Guide to SQL: Syntax


CREATE PROCEDURE

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 Procedures


SPL procedures are UDRs written in Stored Procedure Language (SPL) that do
not return a value.

To write and register an SPL procedure, use a CREATE PROCEDURE statement.


Embed appropriate SQL and SPL statements between the CREATE
PROCEDURE and END PROCEDURE keywords. You can also follow the
procedure with the DOCUMENT and WITH FILE IN options.

SPL procedures are parsed, optimized (as far as possible), and stored in the
system catalog tables in executable format. The body of an SPL procedure is
stored in the sysprocbody system catalog table. Other information about the
procedure is stored in other system catalog tables, including sysprocedures,
sysprocplan, and sysprocauth.

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

SQL Statements 2-205


CREATE PROCEDURE

Example
The following example creates an SPL procedure:
CREATE PROCEDURE raise_prices ( per_cent INT )
UPDATE stock SET unit_price =
unit_price + (unit_price * (per_cent/100) );
END PROCEDURE
DOCUMENT "USAGE: EXECUTE PROCEDURE raise_prices( xxx )",
"xxx = percentage from 1 - 100 "
WITH LISTING IN '/tmp/warn_file'

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, follow these steps:

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.

To create a user-defined procedure written in Java, follow these steps:

1. Write a Java static method, which can use the JDBC functions to
interact with the database server.
2. Compile the Java source file and create a jar file (the shared-object file
for Java).
3. Execute the install_jar() procedure with the EXECUTE PROCEDURE
statement to install the jar file in the current database.
4. If the UDR uses user-defined types, create a mapping between SQL
data types and Java classes.
Use the setUDTExtName() procedure that is explained in
“EXECUTE PROCEDURE” on page 2-444.
5. Register the UDR with the CREATE PROCEDURE statement.

2-206 Informix Guide to SQL: Syntax


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. When the database server
executes an external routine, the database server invokes the external object
code.

The database server stores information about an external function in several


system catalog tables, including sysprocbody and sysprocauth. For more
information on these system catalog tables, see the Informix Guide to SQL:
Reference.

If an external routine returns a value, you must register it with the CREATE
FUNCTION statement.

C Example of Registering a C User-Defined Procedure


The following example registers a C user-defined procedure named
check_owner() in the database. This procedure 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/[Link](unix_owner)"
LANGUAGE C
END PROCEDURE

Java Example of Registering a User-Defined Procedure Written in Java


The following example registers a user-defined procedure named
showusers():
CREATE PROCEDURE showusers()
WITH (CLASS = "jvp")
EXTERNAL NAME 'admin_jar:[Link]'
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.

SQL Statements 2-207


CREATE PROCEDURE

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.

However, in the case of a DBA-privileged UDR, the user who executes the
UDR, not the UDR owner, owns any database objects created by the UDR
unless another owner is specified for the database object within the UDR.

For examples of these situations, see the similar section, “Ownership of


Created Database Objects” on page 2-153, in the CREATE FUNCTION
statement.

Related Information
Related statements: ALTER FUNCTION, ALTER PROCEDURE, ALTER
ROUTINE, CREATE FUNCTION, CREATE FUNCTION FROM, CREATE
PROCEDURE FROM, DROP FUNCTION, DROP PROCEDURE, DROP ROUTINE,
EXECUTE FUNCTION, EXECUTE PROCEDURE, GRANT, EXECUTE
PROCEDURE, PREPARE, REVOKE, and UPDATE STATISTICS

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

For a discussion of how to create and use external routines, see Extending
Informix Dynamic Server 2000.

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

For more information on the NODEFDAC environment variable and the


relative system catalog tables (sysprocedures, sysprocplan, sysprocbody
and sysprocauth), see the Informix Guide to SQL: Reference.

2-208 Informix Guide to SQL: Syntax


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.

XPS In Extended Parallel Server, use this statement to access any SPL routine.
Extended Parallel Server does not support the CREATE FUNCTION FROM
statement. ♦

Use this statement with ESQL/C.

Syntax

CREATE PROCEDURE FROM ' file '


file_var

Element Purpose Restrictions Syntax


file Pathname and filename of the The specified file must exist. Pathname and
file that contains the full text of a The file must contain only one filename must
CREATE PROCEDURE CREATE PROCEDURE conform to the
statement statement. conventions of your
The default pathname is the operating system.
current directory.
file_var Name of a program variable that The file that is specified in the Name must conform
holds the value of file program variable must exist. to language-specific
This file must contain only one rules for variable
CREATE PROCEDURE names.
statement.

SQL Statements 2-209


CREATE PROCEDURE FROM

Usage
You cannot create a user-defined procedure directly in an ESQL/C program.
That is, the program cannot contain the CREATE PROCEDURE statement. The
following steps describe how you can use a user-defined procedure in an
ESQL/C program:

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 that you specify in the file parameter can contain only one
CREATE PROCEDURE statement.

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

Default Directory That Holds the File


The filename that you provide 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. ♦

2-210 Informix Guide to SQL: Syntax


CREATE PROCEDURE FROM

WIN NT On Windows NT, if you specify a filename but not a directory in the file
parameter, the client application looks for the file in your current working
directory if the database is on the local computer. Otherwise, the default
directory is %INFORMIXDIR%\bin. ♦

Important: The ESQL/C preprocessor does not process the contents of the file that you
specify. It just sends the contents to the database server for execution. Therefore, there
is no syntactic check that the file that you specify in CREATE PROCEDURE FROM
actually contains a CREATE PROCEDURE statement. However, to improve
readability of the code, Informix recommends that you match these two statements.

Related Information
Related statements: CREATE PROCEDURE, CREATE FUNCTION FROM, and
CREATE ROUTINE FROM

SQL Statements 2-211


CREATE ROLE

+ CREATE ROLE
IDS
Use the CREATE ROLE statement to create a new role.

Syntax

CREATE ROLE role

' role '

Element Purpose Restrictions Syntax


role Name assigned to a role created In Dynamic Server, the Identifier, p. 4-205
by the DBA maximum number of bytes in
role is 32. In Extended Parallel
Server, the maximum number of
bytes in role is 8.
A role name cannot be a user
name known to the database
server or the operating system of
the database server. A role name
cannot be in the username
column of the sysusers system
catalog table or in the grantor or
grantee columns of the
systabauth, syscolauth,
sysprocauth, sysfragauth, and
sysroleauth system catalog
tables.
When a role name is enclosed in
quotation marks, the role name
is case sensitive.

2-212 Informix Guide to SQL: Syntax


CREATE ROLE

Usage
The database administrator (DBA) uses the CREATE ROLE statement to create
a new role. A role can be considered as a classification, with privileges on
database objects granted to the role. The DBA can assign the privileges of a
related work task, such as engineer, to a role and then grant that role to users,
instead of granting the same set of privileges to every user.

After a role is created, the DBA can use the GRANT statement to grant the role
to users or to other roles. When a role is granted to a user, the user must use
the SET ROLE statement to enable the role. Only then can the user use the
privileges of the role.

The CREATE ROLE statement, when used with the GRANT and SET ROLE
statements, allows a DBA to create one set of privileges for a role and then
grant the role to many users, instead of granting the same set of privileges to
many users.

A role exists until either the DBA or a user to whom the role was granted with
the WITH GRANT OPTION uses the DROP ROLE statement to drop the role.

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 of how to use roles, see the Informix Guide to Database Design
and Implementation.

SQL Statements 2-213


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 the The specified file must exist. Pathname and
file that contains the full text of a The file that you specify can filename must
CREATE PROCEDURE or contain only one CREATE conform to the
CREATE FUNCTION statement FUNCTION or CREATE conventions of your
The default pathname is the PROCEDURE statement. operating system.
current directory.
file_var Name of a program variable that The file that is specified in the Name must conform
holds the value of file program variable must exist. to language-specific
The file that you specify can rules for variable
contain only one CREATE names.
FUNCTION or CREATE
PROCEDURE statement.

2-214 Informix Guide to SQL: Syntax


CREATE ROUTINE FROM

Usage
An Informix ESQL/C program cannot directly define a UDR. That is, it cannot
contain the CREATE FUNCTION or CREATE PROCEDURE statement. The
following steps describe how you can use a UDR in an ESQL/C program:

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 in the file parameter can contain only one
CREATE FUNCTION or CREATE PROCEDURE statement.

The filename that you provide is relative. If you provide a simple filename,
the client application looks for the file in the current directory.

If you do not know at compile time whether the UDR in the file is a function
or a procedure, use the CREATE ROUTINE FROM statement in the ESQL/C
program. However, if you do know if the UDR is a function or procedure,
Informix recommends that you use the matching statement to access the
source file:

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

Related Information
Related statements: CREATE FUNCTION, CREATE FUNCTION FROM, CREATE
PROCEDURE, and CREATE PROCEDURE FROM

SQL Statements 2-215


CREATE ROW TYPE

+ CREATE ROW TYPE


IDS
Use the CREATE ROW TYPE statement to create a named-row type.

Syntax
,
CREATE ROW TYPE row_type ( Field Definition )
p. 2-220

UNDER supertype

Element Purpose Restrictions Syntax


row_type Name of the named-row type The name you specify for the Identifier, p. 4-205
that you create named-row type must follow the
If you create a named-row type conventions for SQL identifiers.
under an existing supertype, this In an ANSI-compliant database,
is the name of the subtype. the combination owner. type
must be unique within the
database. In a database that is
not ANSI compliant, the type
name must be unique within the
database.
supertype Name of the supertype in an The supertype must already Data type, p. 4-53
inheritance hierarchy exist as a named-row type.

Usage
The CREATE ROW TYPE statement creates a named-row type. You can assign
a named-row type to a table or view to create a typed table or typed view. You
can also assign a named-row type to a column. Although you can assign a
row type to a table to define the structure of the table, row types are not the
same as table rows. Table rows consist of one or more columns; row types
consist of one or more fields, which are defined using the Field Definition
syntax.

2-216 Informix Guide to SQL: Syntax


CREATE ROW TYPE

You can use a named-row type anywhere you can use any other data type.
Named-row types are strongly typed. Any two named-row types are not
considered equivalent even if they are structurally equivalent. Row types
without names are called unnamed-row types. Any two unnamed-row types
are considered equivalent if they are structurally equivalent. For more infor-
mation on unnamed-row types, see “Unnamed Row Types” on page 4-68.

Privileges on Named-Row Types


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

To find out what privileges exist on a particular type, check the sysxtdtypes
system catalog table for the owner name and the sysxtdtypeauth system
catalog table for additional type privileges that might have been granted. For
more information on system catalog tables, see the Informix Guide to SQL:
Reference.

For information about the RESOURCE, UNDER, and ALL privileges, see
GRANT.

Privileges on a typed table (a table that is assigned a named-row type) are the
same as privileges on any table. For more information, see “Table-Level Privi-
leges” on page 2-505.

To find out what privileges you have on a particular table, check the
systabauth system catalog table.

SQL Statements 2-217


CREATE ROW TYPE

Privileges on Named -ow Type Columns


Privileges on named-row type columns are the same as privileges on any
column. For more information, see “Table-Level Privileges” on page 2-505.

To find out what privileges you have on a particular column, check the
syscolauth system catalog table. This table is described in the Informix Guide
to SQL: Reference.

Inheritance and Named-Row Types


A named-row type can belong to an inheritance hierarchy, as either a subtype
or a supertype. You 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.

When you create a named-row type as a subtype, the subtype inherits all
fields of the supertype. In addition, you can add new fields to the subtype
that you create. The new fields are specific to the subtype alone.

You cannot substitute a row type in an inheritance hierarchy for its supertype
or its subtype. For example, suppose you define a type hierarchy in which
person_t is the supertype and employee_t is the subtype. If a column is of
type person_t, the column can only contain person_t data. It cannot contain
employee_t data. Likewise, if a column is of type employee_t, the column
can only contain employee_t data. It cannot contain person_t data.

Creating a Subtype
In most cases, you add new fields when you create a named-row type as a
subtype of another named-row type (supertype). To create the fields of a
named-row type, you use the field definition clause (see “Field Definition”
on page 2-220).

When you create a subtype, you must use the UNDER keyword to associate
the supertype with the named-row type that you want to create. The
following statement creates the employee_t type under the person_t type:
CREATE ROW TYPE employee_t
(salary NUMERIC(10,2), bonus NUMERIC(10,2))
UNDER person_t;

2-218 Informix Guide to SQL: Syntax


CREATE ROW TYPE

The employee_t type inherits all the fields of person_t and has two
additional fields: salary and bonus. However, the person_t type is not
altered.

Type Hierarchies
When you create a subtype, you create a type hierarchy. In a type hierarchy,
each subtype that you create inherits its properties from a single supertype.
If you create a named-row type customer_t under person_t, customer_t
inherits all the fields of person_t. If you create another named-row type,
salesrep_t under customer_t, salesrep_t inherits all the fields of customer_t.
More specifically, salesrep_t inherits all the fields that customer_t inherited
from person_t as well as all the fields defined specifically for customer_t. For
a full discussion of type inheritance, refer to the Informix Guide to SQL:
Tutorial.

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 information in the sysusers system catalog table.
■ 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 [Link] 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 schema.
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 you want to use 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.

SQL Statements 2-219


CREATE ROW TYPE

Important: When you create a subtype, do not redefine fields that the subtype
inherited for its supertype. If you attempt to redefine these fields, the database server
returns an error.

Constraints on Named-Row Types


You cannot apply constraints to named-row types directly. Specify the
constraints for the tables that use named-row types when you create or alter
the table.

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


p. 2-216

field data_type

NOT NULL

Element Purpose Restrictions Syntax


data_type Data type of the field See “Limitations With Serial and Data type, p. 4-53
Simple-Large-Object Data
Types” on page 2-221.
field Name of a field in the row Name must be unique within the Identifier, p. 4-205
row type and its supertype.

The NOT NULL constraint that you specify on a field of a named-row type
also applies to corresponding columns of a table when the named-row type
is used to create a typed table.

2-220 Informix Guide to SQL: Syntax


CREATE ROW TYPE

Limitations With 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 value with CREATE ROW TYPE.

To modify the value for a serial field, you must use either the MODIFY clause
of the ALTER TABLE statement or the INSERT statement to insert a value that
is larger than the current maximum (or default) serial value.

When you use serial fields in row types, you create performance implications
across a table hierarchy. When you insert data into a subtable whose
supertable (or its supertable) contains the serial counter, the database server
must also open the supertable, update the serial value, and close the
supertable, thus adding extra overhead.

Related Information
Related statements: DROP ROW TYPE, CREATE TABLE, CREATE CAST, GRANT,
and REVOKE

For a discussion of named-row types, see the Informix Guide to Database


Design and Implementation and the Informix Guide to SQL: Reference.

SQL Statements 2-221


CREATE SCHEMA

DB CREATE SCHEMA
SQLE
Use the CREATE SCHEMA statement to issue a block of CREATE and GRANT
statements as a unit. The CREATE SCHEMA statement allows you to specify
an owner of your choice for all database objects that the CREATE SCHEMA
statement creates.

Use this statement with DB-Access and the SQL Editor.

2-222 Informix Guide to SQL: Syntax


CREATE SCHEMA

Syntax

CREATE SCHEMA AUTHORIZATION user CREATE TABLE Statement


p. 2-230

CREATE VIEW Statement


p. 2-334

GRANT Statement
p. 2-500

OP CREATE OPTICAL CLUSTER Statement


see the “Guide to the Optical Subsystem”
+
CREATE INDEX Statement
p. 2-157

CREATE SYNONYM Statement


p. 2-226

CREATE TRIGGER Statement


p. 2-296
IDS
CREATE ROW TYPE Statement
p. 2-216

CREATE OPAQUE TYPE Statement


p. 2-186

CREATE DISTINCT TYPE Statement


p. 2-127

CREATE CAST Statement


p. 2-119

SQL Statements 2-223


CREATE SCHEMA

Element Purpose Restrictions Syntax


user Name of the user who owns the If the user who issues the Identifier, p. 4-205
database objects that the CREATE SCHEMA statement
CREATE SCHEMA statement has the Resource privilege, user
creates must be the name of this user. If
the user who issues the CREATE
SCHEMA statement has the
DBA privilege, user can be the
name of this user or another
user.

Usage
You cannot issue the CREATE SCHEMA statement until you create the affected
database.

Users with the Resource privilege can create a schema for themselves. In this
case, user must be the name of the person with the Resource privilege who is
running the CREATE SCHEMA statement. Anyone with the DBA privilege can
also create a schema for someone else. In this case, user can identify a user
other than the person who is running the CREATE SCHEMA statement.

You can put CREATE and GRANT statements in any logical order within the
statement, as the following example shows. Statements are considered part
of the CREATE SCHEMA statement until a semicolon or an end-of-file symbol
is reached.
CREATE SCHEMA AUTHORIZATION sarah
CREATE TABLE mytable (mytime DATE, mytext TEXT)
GRANT SELECT, UPDATE, DELETE ON mytable TO rick
CREATE VIEW myview AS
SELECT * FROM mytable WHERE mytime > '12/31/1997'
CREATE INDEX idxtime ON mytable (mytime);

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,
and you try to create a database object for an owner other than yourself, you
receive an error message.

2-224 Informix Guide to SQL: Syntax


CREATE SCHEMA

Granting Privileges Within CREATE SCHEMA


You can only grant privileges with the CREATE SCHEMA statement; you
cannot revoke or drop privileges.

Creating Database Objects or Granting Privileges Outside


CREATE SCHEMA
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 Informix Guide to Database
Design and Implementation.

SQL Statements 2-225


CREATE SYNONYM

+
CREATE SYNONYM
Use the CREATE SYNONYM statement to provide an alternative name for a
table or view.

Syntax

CREATE SYNONYM synonym FOR table


PUBLIC view

PRIVATE

Element Purpose Restrictions Syntax


synonym Name of the synonym to be The synonym name must be Database Object
created unique in the database. Name, p. 4-50
table Name of the table for which the The table must exist. Database Object
synonym is created Name, p. 4-50
view Name of the view for which the The view must exist. Database Object
synonym is created Name, p. 4-50

Usage
Users have the same privileges for a synonym that they have for the table to
which the synonym applies.

The synonym name must be unique; that is, the synonym name cannot be the
same as another database object, such as a table, view, or temporary table.

Once a synonym is created, it persists until the owner executes the DROP
SYNONYM statement. This property distinguishes a synonym from an alias
that you can use in the FROM clause of a SELECT statement. The alias persists
for the existence of the SELECT statement. If a synonym refers to a table or
view in the same database, the synonym is automatically dropped if you
drop the referenced table or view.

You cannot create a synonym for a synonym in the same database.

2-226 Informix Guide to SQL: Syntax


CREATE SYNONYM

ANSI In an ANSI-compliant database, the owner of the synonym ([Link])


qualifies the name of a synonym. The identifier [Link] must be
unique among all the synonyms, tables, temporary tables, and views in the
database. You must specify owner when you refer to a synonym that another
user owns. The following example shows this convention:
CREATE SYNONYM emp FOR [Link]

You can create a synonym for any table or view in any database on your
database server. Use the owner. convention if the table is part of an
ANSI-compliant database. The following example shows a synonym for a
table outside the current database. It assumes that you are working on the
same database server that contains the payables database.
CREATE SYNONYM mysum FOR payables:[Link]

Creating a Synonym on a Table in a Remote Database


You can create a synonym for a table or view that exists on any networked
database server as well as on the database server that contains your current
database. The database server that holds the table must be on-line when you
create the synonym. In a network, the database server verifies that the
database object referred to by the synonym exists when you create the
synonym.

The following example shows how to create a synonym for a database object
that is not in the current database:
CREATE SYNONYM mysum FOR payables@phoenix:[Link]

The identifier mysum now refers to the table [Link], which is in the
payables database on the phoenix database server. Note that if the summary
table is dropped from the payables database, the mysum synonym is left
intact. Subsequent attempts to use mysum return the error Table not
found.

IDS Restrictions
You cannot create synonyms on the following types of remote tables:

■ Typed tables (including any table that is part of a table hierarchy)


■ Tables that contain any extended data types

SQL Statements 2-227


CREATE SYNONYM

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 a synonym is public, a user does not
need to know the name of the owner of the 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, synonyms are always private. If you use the
PUBLIC or PRIVATE keywords, you receive a syntax error. ♦

If you use the PRIVATE keyword, the synonym can be used only by the owner
of the synonym or if the name of the owner is specified explicitly with the
synonym. More than one private synonym with the same name can exist in
the same database. However, a different user must own each synonym with
that name.

You can own only one synonym with a given name; you cannot create both
private and public synonyms with the same name. For example, the
following code generates an error:
CREATE SYNONYM our_custs FOR customer;
CREATE PRIVATE SYNONYM our_custs FOR cust_calls;-- ERROR!!!

Synonyms with the Same Name


If you own a private synonym, and a public synonym exists with the same
name, when you use the synonym by its unqualified name, the private
synonym is used.

If you use DROP SYNONYM with a synonym, and multiple synonyms exist
with the same name, the private synonym is dropped. If you issue the DROP
SYNONYM statement again, the public synonym is dropped.

Chaining Synonyms
If you create a synonym for a table that is not in the current database, and this
table is dropped, the synonym stays in place. You can create a new synonym
for the dropped table, with the name of the dropped table as the synonym
name, which points to another external or remote table. In this way, you can
move a table to a new location and chain synonyms together so that the
original synonyms remain valid. (You can chain as many as 16 synonyms in
this manner.)

2-228 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 Informix Guide to


Database Design and Implementation.

SQL Statements 2-229


CREATE TABLE

CREATE TABLE
Use the CREATE TABLE statement to create a new table in the current
database, place data-integrity constraints on columns, designate where the
table should be stored, indicate the size of its initial and subsequent extents,
and specify how to lock it.

You can use the CREATE TABLE statement to create relational-database tables
or typed tables (object-relational tables). For information on how to create
temporary tables, see “CREATE Temporary TABLE” on page 2-286.

Syntax

CREATE TABLE table Table Definition


XPS
RAW
STATIC

OPERATIONAL

STANDARD

Table Definition
,

( Column Definition ) Options


p. 2-233 p. 2-255
,

+ , Multiple-Column
Constraint Format
IDS p. 2-250

OF TYPE Clause
p. 2-280

2-230 Informix Guide to SQL: Syntax


CREATE TABLE

Element Purpose Restrictions Syntax


table Name assigned to the table The name must be unique Database Object
Every table must have a name. within a database. It must not be Name, p. 4-50
used for any other tables or for
any views or synonyms within
the current database.

Usage
When you create a table, the table and columns within that table must have
unique names and every table column must have a data type associated with
it.

ANSI In an ANSI-compliant database, the combination [Link] 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


Informix Guide to SQL: Reference.

XPS Usage-Type Options


In Extended Parallel Server, use the Usage-TYPE Options to specify that the
table has particular characteristics that can improve various bulk operations
on it. Other than the default option (STANDARD) that is used for OLTP
databases, these usage-type options are used primarily to improve perfor-
mance in data warehousing databases.

SQL Statements 2-231


CREATE TABLE

A table can have any of the following usage characteristics.

Option Purpose

RAW Non-logging table that cannot have indexes or referential


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

STATIC Non-logging 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.

OPERATIONAL Logging table that uses light appends and cannot be


restored from archive
Use this type on tables that are refreshed frequently
because light appends allow the quick addition of many
rows.

STANDARD Logging table that allows rollback, recovery, and resto-


ration from archives
This type is the default.
Use this type for all the recovery and constraints function-
ality that you want on your OLTP databases.

For a more detailed description of these table types, refer to your


Administrator’s Guide.

2-232 Informix Guide to SQL: Syntax


CREATE TABLE

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

column Data Type


p. 4-53
DEFAULT Single-Column
Clause Constraint Format
p. 2-234 p. 2-237

Element Purpose Restrictions Syntax


column Name of a column in the table The name must be unique in a Identifier, p. 4-205
table, but you can use the same
names in different tables in the
same database.

When you name a column, as with any SQL identifier, you can use a reserved
word, but syntactic ambiguities can occur. For more information on reserved
words for Dynamic Server, see Appendix A, “Reserved Words for Dynamic
Server.” For more information on reserved words for Extended Parallel
Server, see Appendix B, “Reserved Words for Extended Parallel Server.” For
more information on the ambiguities that can occur, see “Using Keywords as
Column Names” on page 4-212.

IDS If you define a column of a table to be of a named-row type, the table does not
adopt any constraints of the named row. ♦

SQL Statements 2-233


CREATE TABLE

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

DEFAULT Back to Column Definition


Clause p. 2-233

DEFAULT literal

NULL

USER
+

CURRENT DATETIME Field Qualifier


p. 4-71

TODAY

SITENAME

DBSERVERNAME

Element Purpose Restrictions Syntax


literal String of alphabetic or numeric The string must be an appro- Expression, p. 4-73
characters priate type for the column. See
“Using a Literal as a Default
Value” on page 2-235

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.

You cannot specify default values for serial columns.

2-234 Informix Guide to SQL: Syntax


CREATE TABLE

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.

Format of
For Columns of Data Type Default Value Syntax Restrictions

BOOLEAN CHARACTER 't' or 'f' representing true or false


The literal must be specified as a
quoted string.

CHAR, VARCHAR, NCHAR, NVARCHAR, CHARACTER Quoted String, p. 4-260


CHARACTER VARYING, DATE

DATETIME DATETIME Literal DATETIME, p. 4-231

DECIMAL, MONEY, FLOAT, SMALLFLOAT DECIMAL Literal Number, p. 4-237

INTEGER, SMALLINT, DECIMAL, MONEY, INTEGER Literal Number, p. 4-237


FLOAT, SMALLFLOAT, INT8

INTERVAL INTERVAL Literal INTERVAL, p. 4-234

Opaque data types (IDS only) CHARACTER Quoted String, p. 4-260


You must use the single-column
constraint format to specify the
default value.

Date literals must be of the format that the DBDATE environment variable
specifies. If DBDATE is not set, the date literals must be of the mm/dd/yyyy
format.

Using NULL as a Default Value


If you do not indicate a default value for a column, the default is null unless
you place a not-null constraint on the column. In this case, no default value
exists for the column.

SQL Statements 2-235


CREATE TABLE

If you specify NULL as the default value for a column, you cannot specify a
not-null constraint as part of the column definition.

You cannot designate null as the default value for a column that is part of a
primary key.

If the column is BYTE or TEXT data type, null is the only default value that you
can designate.

IDS If the column is BLOB or CLOB data type, null is the only default value that
you can designate.

Using a Built-in Function as a Default Value


You can specify a built-in function as the default value for a column. The
following table indicates the built-in functions that you can specify, the data
type requirements, and the recommended size for their corresponding
columns.

Built-In Function Name Data Type Requirement Recommended Size of Column

CURRENT DATETIME column with matching qualifier Byte value that accommodates the
largest DATETIME value for your
locale.

DBSERVERNAME CHAR, VARCHAR, NCHAR, NVARCHAR, At least 128 bytes


or CHARACTER VARYING column (IDS)
At least 18 bytes (XPS)

SITENAME CHAR, VARCHAR, NCHAR, NVARCHAR, At least 128 bytes


or CHARACTER VARYING column (IDS)
At least 18 bytes (XPS)

TODAY DATE column Byte value that accommodates the


largest DATE value for your locale.

USER CHAR, VARCHAR, NCHAR, NVARCHAR, At least 32 bytes


or CHARACTER VARYING column (IDS)
At least 8 bytes (XPS)

2-236 Informix Guide to SQL: Syntax


CREATE TABLE

Informix recommends a column size because if the column length is too small
to store the default value during INSERT and ALTER TABLE operations, the
database server returns an error.

IDS You cannot designate a built-in function (that is, CURRENT, USER, TODAY,
SITENAME, or DBSERVERNAME) as the default value for a column that holds
opaque or distinct data types. ♦

For more information on these built-in functions, see “Constant Expressions”


on page 4-108.

Examples of Default Values in Column Definitions


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 particular column. You can use this portion of CREATE
TABLE to perform 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

SQL Statements 2-237


CREATE TABLE

Single-Column Back to Column Definition


Constraint Format p. 2-233

UNIQUE

NOT +
DISTINCT +
+
PRIMARY KEY Constraint
Definition
Constraint REFERENCES p. 2-247
Definition Clause
p. 2-247 p. 2-241

CHECK
Clause
p. 2-245

The following example creates a simple table with two constraints, a


primary-key constraint named num on the acc_num column and a unique
constraint named code 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.

Restrictions on Using the Single-Column Constraint Format


When you use the single-column constraint format, you cannot use
constraints that involve more than one column. For example, 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-250.

2-238 Informix Guide to SQL: Syntax


CREATE TABLE

Using Large-Object Types in Constraints


You cannot place unique, primary-key, or referential constraints on BYTE or
TEXT columns. However, you can check for null or non-null values with a
check constraint.

IDS You cannot place unique, primary-key, 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.

The following example creates the newitems table. In newitems, the column
manucode does not have a default value nor does it allow nulls.
CREATE TABLE newitems (
newitem_num INTEGER,
manucode CHAR(3) NOT NULL,
promotype INTEGER,
descrip CHAR(20))

Relationship Between the Default Value and the NOT NULL Constraint
If you do not indicate a default value for a column, the default is null unless
you place a NOT NULL constraint on the column. In this case, no default value
exists for the column.

You cannot specify NULL as the default value for a column and also specify
the NOT NULL constraint.

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. You cannot insert duplicate values in 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.

SQL Statements 2-239


CREATE TABLE

Restrictions on Defining Unique Constraints


You cannot place a unique constraint on a column on which you have already
placed 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 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() function. Therefore, if
the definition of the opaque type includes the equal() function, a column of
that opaque type can have a unique constraint. ♦

Example That Uses the Single-Column Constraint Format


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 “Choosing a Constraint


Name” on page 2-247.

Using the PRIMARY KEY Constraint


A primary key is a column or a set of columns (available 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.

Restrictions for Primary-Key Constraints


You can designate only one primary key for a table. If you define a single
column as the primary key, it is unique by definition; you cannot explicitly
give the same column a unique constraint.

2-240 Informix Guide to SQL: Syntax


CREATE TABLE

You cannot place a primary-key constraint on a BYTE or TEXT column.

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

Example That Uses the Single-Column Constraint Format


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


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

REFERENCES table
, +
( column ) ON DELETE CASCADE

SQL Statements 2-241


CREATE TABLE

Element Purpose Restrictions Syntax


column Name of the referenced column See “Restrictions on Referential Identifier, p.4-205
or columns Constraints” on page 2-242.
table Name of the referenced table The referenced table must reside Database Object
in the same database as the refer- Name, p. 4-50
encing table.

The referencing column (the column being defined) is the column or set of
columns that refers to the referenced column or set of columns. The refer-
encing column or set of columns can contain null and duplicate values.
However, the values in the referenced column or set of columns must be
unique.

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.

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.

2-242 Informix Guide to SQL: Syntax


CREATE TABLE

XPS ■ When you use the multiple-column constraint format, the maximum
number of columns in the REFERENCES clause is 16, and the total
length of the columns cannot exceed 255 bytes. ♦
IDS ■ When you use the multiple-column constraint format, the maximum
number of columns in the REFERENCES clause is 16, and the total
length of the columns cannot exceed 390 bytes.
■ You cannot place a referential constraint on a BLOB or CLOB
column. ♦

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.

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.

SQL Statements 2-243


CREATE TABLE

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

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.

2-244 Informix Guide to SQL: Syntax


CREATE TABLE

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

CHECK Clause
Use the CHECK clause to designate conditions that must be met before data
can be assigned to a column during an INSERT or UPDATE statement.

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


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

CHECK ( Condition )
p. 4-27

During an insert or update, if a row evaluates to false for any check constraint
defined on a table, the database server returns an error. The database server
does not return an error if a row evaluates to null for a check constraint. In
some cases, you might wish to use both a check constraint and a NOT NULL
constraint.

SQL Statements 2-245


CREATE TABLE

You use search conditions to define check constraints. The search condition
cannot contain the following items: subqueries, aggregates, host variables,
rowids, or user-defined routines. In addition, the search condition cannot
contain the following built-in functions: CURRENT, USER, SITENAME,
DBSERVERNAME, or TODAY.

When you specify a date value in a search condition, make sure you specify 4 digits
instead of 2 digits for the year. When you specify a 4-digit year, the DBCENTURY
environment variable has no effect on the distribution scheme. When you specify a 2-
digit year, the DBCENTURY environment variable can affect the distribution scheme
and can produce unpredictable results. See the “Informix Guide to SQL: Reference”
for more information on the DBCENTURY environment variable.
With a BYTE or TEXT column, you can check for null or not-null values. This
constraint is the only constraint allowed on a BYTE or TEXT columns.

IDS With a BLOB or CLOB column, you can check for null or not-null values. This
constraint is the only constraint allowed on a BLOB or CLOB columns.

Restrictions When Using the Single-Column Constraint Format


When you use the single-column constraint format to define a check
constraint, the only column that the check constraint can check against is the
column itself. In other words, the check constraint cannot depend on values
in other columns of the table.

Example
The following example creates the my_accounts table which has two
columns with check constraints:
CREATE TABLE my_accounts (
chk_id SERIAL PRIMARY KEY,
acct1 MONEY CHECK (acct1 BETWEEN 0 AND 99999),
acct2 MONEY CHECK (acct2 BETWEEN 0 AND 99999))

Both acct1 and acct2 are columns of MONEY data type whose values must be
between 0 and 99999.

If, however, you want to test that acct1 has a larger balance than acct2, you
cannot use the single-column constraint format. To create a constraint that
checks values in more than one column, you must use the “Multiple-Column
Constraint Format” on page 2-250.

2-246 Informix Guide to SQL: Syntax


CREATE TABLE

Constraint Definition
Use the constraint definition portion of CREATE TABLE for the following
purposes:

■ To assign a name to a constraint


IDS ■ To set a constraint to disabled, enabled, or filtering mode ♦

Constraint Back to Single-Column Constraint Format p. 2-237


Definition Back to Multiple-Column Constraint Format p. 2-250

IDS
CONSTRAINT constraint
DISABLED

ENABLED

FILTERING

WITHOUT ERROR

WITH ERROR

Element Purpose Restrictions Syntax


constraint Name of the constraint The constraint name must be Database Object
unique in the database. Name, p. 4-50

Choosing a Constraint Name


Whenever you use the single- or multiple-column constraint format to place
a data restriction on a column, the database server creates a constraint and
adds a row for that constraint to the sysconstraints 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 assign a name to a constraint, the database server generates the name
that appears in the sysindexes table.

SQL Statements 2-247


CREATE TABLE

If you wish, you can specify a meaningful name for the constraint. The name
of a constraint must be unique within 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 [Link] (the combi-
nation of the owner name and constraint name) must be unique within the
database. ♦

IDS The system catalog table that holds information about indexes is the
sysindices table. ♦

Constraint Names Generated by the Database Server


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.

If the generated name conflicts with an existing identifier, the database server
returns an error, and you must then supply a constraint name.

The index name in sysindexes (or sysindices) is created with the following
format:
[space]<tabid>_<constraintid>

For example, the index name might be something like: " 111_14" (quotation
marks are used to show the space).

2-248 Informix Guide to SQL: Syntax


CREATE TABLE

IDS Choosing a Constraint-Mode Option


Use the constraint-mode options to control the behavior of constraints during
insert, delete, and update operations. The following list explains these
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 is the default mode.

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 about the constraint violation to the
diagnostics table associated with the target 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 Does not return an integrity-violation error when a filtering-mode


ERROR constraint is violated during an insert, delete, or update operation.
This is the default error option.

WITH Returns an integrity-violation error when a filtering-mode


ERROR constraint is violated during an insert, delete, or update operation.

For how to set the constraint mode after the table exists, see “SET Database
Object Mode” on page 2-700. For information about where the database
server stores data that violates a constraint set to filtering, see “START
VIOLATIONS TABLE” on page 2-778.

SQL Statements 2-249


CREATE TABLE

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


Constraint Format , Back to OF TYPE Clause p. 2-280

UNIQUE ( column )
+ +

DISTINCT
Constraint
PRIMARY KEY Definition
p. 2-247
,
) REFERENCES
FOREIGN KEY ( column Clause
p. 2-241

CHECK Clause
p. 2-245

Element Purpose Restrictions Syntax


column Name of the column or columns The column must be defined. Identifier, p.4-205
on which the constraint is placed The column cannot be a BYTE or
TEXT, BLOB or CLOB column.
You can include a maximum of
16 columns in a constraint list.
The total length of all columns
cannot exceed:
■ 255 bytes (XPS)
■ 390 bytes (IDS)
When you define a unique
constraint (UNIQUE or
DISTINCT keywords), a column
cannot appear in the constraint
list more than once.

2-250 Informix Guide to SQL: Syntax


CREATE TABLE

When you use the multiple-column constraint format, you can perform the
following tasks:

■ Create one or more data-integrity constraints for a single column or


set of columns
■ Specify a meaningful name for a constraint
■ Specify the constraint-mode option that controls the behavior of a
constraint during insert, delete, and update operations

When you use this format, you can create composite primary and foreign
keys. You can also define check constraints that involve comparing data in
different columns.

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-237 and “Referential Relationships Within a Table” on
page 2-243 respectively.

Using Large-Object Types in Constraints


You cannot place unique, primary-key, or referential (FOREIGN KEY)
constraints on BYTE or TEXT columns. However, you can 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. ♦

SQL Statements 2-251


CREATE TABLE

Location of Information Regarding Specific Constraints


The following table indicates where you can find detailed discussions of
specific constraints

Constraint For more information, see For an Example, see

CHECK “CHECK Clause” on “Defining Check Constraints


page 2-245 Across Columns” on
page 2-253

DISTINCT “Using the UNIQUE or “Examples that Use the


DISTINCT Constraints” on Multiple-Column Constraint
page 2-239 Format” on page 2-253

FOREIGN KEY “Using the FOREIGN KEY “Defining Composite


Constraint” on page 2-252 Primary and Foreign Keys”
on page 2-254

PRIMARY KEY “Using the PRIMARY KEY “Defining Composite


Constraint” on page 2-240 Primary and Foreign Keys”
on page 2-254

UNIQUE “Using the UNIQUE or “Examples that Use the


DISTINCT Constraints” on Multiple-Column Constraint
page 2-239 Format” on page 2-253

Using the FOREIGN KEY Constraint


A foreign key joins and establishes dependencies between tables, that is, it
creates a referential constraint.

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 make BYTE or TEXT columns be foreign keys.

IDS You cannot make BLOB or CLOB columns be foreign keys. ♦

For more information on referential constraints, see the “REFERENCES


Clause” on page 2-241.

2-252 Informix Guide to SQL: Syntax


CREATE TABLE

Examples that Use the Multiple-Column Constraint Format


The following example creates a simple table with a unique constraint. The
example uses the multiple-column constraint format. However, nothing in
this example would prohibit 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 an explanation of the constraint name, refer to “Choosing a Constraint


Name” on page 2-247.

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
table. (However, you cannot create a check constraint for columns across
tables.)
The following example includes a comparison of acct1 and acct2 two
columns in the 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)
)

In this example, the acct1 column must be greater than the acct2 column, or
the insert or update fails.

SQL Statements 2-253


CREATE TABLE

Defining Composite Primary and Foreign Keys


When you use the multiple-column constraint format, you can create a
composite key (that is, you can specify multiple columns for a primary key
or foreign key constraint.

The following example creates two tables. The first table has a composite key
that acts as a primary key, and the second table has a composite key that acts
as a foreign key.
CREATE TABLE accounts (
acc_num INTEGER,
acc_type INTEGER,
acc_descr CHAR(20),
PRIMARY KEY (acc_num, acc_type))

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-254 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-230

IDS +
LOCK MODE USING
Options Access-Method
WITH CRCOLS Storage p. 2-278 Clause
Options p. 2-279
p. 2-256

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

SQL Statements 2-255


CREATE TABLE

For more information about using this option, refer to the Guide to Informix
Enterprise Replication.

Storage Options
Use the storage option portion of CREATE TABLE to specify the storage space
and the size of the extents for the table.

Storage Options Back to Options


p. 2-255

IDS
IN dbspace EXTENT SIZE
PUT Clause Options
p. 2-273 p. 2-276
XPS dbslice
IDS

extspace

FRAGMENT BY
Clause
p. 2-259

Element Purpose Restrictions Syntax


dbslice Name of the dbslice in which to The specified dbslice must Identifier, p. 4-205
store the table already exist.
dbspace Name of the dbspace in which to The specified dbspace must Identifier, p. 4-205
store the table already exist.
If you do not specify a location
with either the IN dbspace clause
or a fragmentation scheme, the
default is the dbspace where the
current database resides.
extspace Name assigned with the The specified extspace must Refer to the user
onspaces command to a storage already exist. documentation for
area outside the database server your custom access
method for more
information.

2-256 Informix Guide to SQL: Syntax


CREATE TABLE

If you use the “USING Access-Method Clause” on page 2-279 to specify an


access method, the storage space named must be supported by that access
method.

You can specify a dbspace for the table that is different from the storage
location specified for the database, or fragment the table into several
dbspaces. If you do not specify the IN clause or a fragmentation scheme, the
database server stores the table in the dbspace where the current database
resides.

IDS You can use the PUT clause to specify storage options for smart large objects.
For more information, see “PUT Clause” on page 2-273.

Tip: If your table has columns that contain simple large objects (TEXT or BYTE), you
can specify a separate blobspace for each object. For information on storing simple
large objects, refer to “Large-Object Data Types” on page 4-62. ♦

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.

SQL Statements 2-257


CREATE TABLE

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, you use this option in conjunction with the “USING Access-
Method Clause” on page 2-279. Refer to the user documentation for your
custom-access method for more information.

2-258 Informix Guide to SQL: Syntax


CREATE TABLE

FRAGMENT BY Clause
Use the FRAGMENT BY clause to create fragmented tables and specify the
distribution scheme.

FRAGMENT BY Back to Storage Options


Clause p. 2-256
,

FRAGMENT BY ROUND ROBIN IN dbspace , dbspace


IDS XPS

WITH ROWIDS IN dbslice

EXPRESSION expression IN dbspace , expression IN dbspace

REMAINDER
XPS
, ,

HASH ( column ) IN dbspace , dbspace

IN dbslice
,
HYBRID ( column )

,
EXPRESSION expression IN dbslice , expression IN dbslice

REMAINDER

dbspace dbspace
, ,
( dbspace ) ( dbspace )

RANGE Method Clause


p. 2-265

SQL Statements 2-259


CREATE TABLE

Element Purpose Restrictions Element


column Name of the column or columns on All specified columns must be in Identifier, p. 4-205
which you want to apply the the current table.
fragmentation strategy If you specify a serial column,
In the HYBRID clause, column you cannot specify any other
identifies the column or columns on column.
which you want to apply the hash
portion of the hybrid table fragmen-
tation strategy.
dbslice Name of the dbslice that contains the The dbslice must exist when you Identifier, p.4-205
dbspaces in which the table execute the statement.
fragments reside
dbspace Name of the dbspace that contains The dbspace must exist when Identifier, p. 4-205
the table fragment you execute the statement.
If you do not specify a location with The minimum number of
either the IN dbspace clause or a dbspaces that you can specify is
fragmentation scheme, the default is two.
the dbspace where the current The maximum number of
database resides. dbspaces that you can specify is
2,048.
expression Expression that defines which rows Each expression can contain Expression, p. 4-73
are stored in a fragment only columns from the current
table and only data values from
a single row.
No subqueries, user-defined
routines, serial columns, aggre-
gates, or references to the fields
of a row-type column are
allowed. In addition, the built-in
current, date and/or time
functions are not allowed.

When you fragment a table, the IN keyword introduces the storage space
where a table fragment is to be stored.

2-260 Informix Guide to SQL: Syntax


CREATE TABLE

IDS Using the WITH ROWIDS Option


Nonfragmented tables contain a hidden column called the rowid column.
However, fragmented tables do not contain this column. If a table is
fragmented, you can use the WITH ROWIDS keywords to add the rowid
column to the table. The database server assigns to each row in the rowid
column a unique number that remains stable for the life of the row. The
database server uses an index to find the physical location of the row. After
you add the rowid column, each row contains an additional 4 bytes to store
the rowid.
Important: Informix recommends that you 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 If you are using Extended Parallel Server, you can specify the name of a
dbslice to fragment a table across a group of dbspaces that share the same
naming convention. For a syntax alternative to FRAGMENT BY ROUND ROBIN
IN dbslice that achieves the same results, see “Storing Data in a dbslice” on
page 2-258. ♦

IDS Use the PUT clause to specify round-robin fragmentation for smart large
objects. For more information, see “PUT Clause” on page 2-273. ♦

SQL Statements 2-261


CREATE TABLE

Fragmenting by EXPRESSION
In an expression-based distribution scheme, each fragment expression in a rule
specifies a storage space. Each fragment expression in the rule isolates data
and aids the database server in searching for rows. Specify one of the
following rules:

■ Range rule
A range rule specifies fragment expressions that use a range to
specify which rows are placed in a fragment, as the following
example shows:
...
FRAGMENT BY EXPRESSION
c1 < 100 IN dbsp1,
c1 >= 100 AND c1 < 200 IN dbsp2,
c1 >= 200 IN dbsp3
■ Arbitrary rule
An arbitrary rule specifies fragment expressions based on a
predefined SQL expression that typically uses OR clauses to group
data, as the following example shows:
...
FRAGMENT BY EXPRESSION
zip_num = 95228 OR zip_num = 95443 IN dbsp2,
zip_num = 91120 OR zip_num = 92310 IN dbsp4,
REMAINDER IN dbsp5

Warning: When you specify a date value in a fragment expression, make sure you
specify 4 digits instead of 2 digits for the year. When you specify a 4-digit year, the
DBCENTURY environment variable has no effect on the distribution scheme. When
you specify a 2-digit year, the DBCENTURY environment variable can affect the
distribution scheme and can produce unpredictable results. See the “Informix Guide
to SQL: Reference” for more information on the DBCENTURY environment variable.

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.

2-262 Informix Guide to SQL: Syntax


CREATE TABLE

XPS Fragmenting by HASH


If you use a hash-distribution scheme, the database server 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 very 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 a lot of queries that scan most of
the data, you can use a system-defined hash-distribution scheme to balance
the I/O processing as follows:
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
.
.
.

This example uses eight coservers with one dbspace defined on each
coserver.

SQL Statements 2-263


CREATE TABLE

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 choose to fragment on a serial column, the only distribution scheme
that you can use is a hash-distribution scheme. In addition, the serial column
must be the only column in the hashing key.

The following excerpt is a sample 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
more information on range fragmentation, see “RANGE Method Clause” on
page 2-265.

2-264 Informix Guide to SQL: Syntax


CREATE TABLE

When you specify hybrid fragmentation, the EXPRESSION clause determines


the base fragmentation strategy of the table. In this clause, you associate an
expression with a set of dbspaces (dbspace, dbslice, or dbspacelist format) to
designate where the data is stored. The hash column (or columns) 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 dbspacelist,
the database server fragments the table across the dbspaces specified in that
list.

For example, the following table, my_hybrid, distributes rows based on two
columns of the table. The value of col1 determines in which dbslice the row
belongs. The hash value of col2 determines in which dbspace (within the
previously determined dbslice) to insert into.
CREATE TABLE my_hybrid
(col1 INT,
col2 DATE,
col3 CHAR(10)
)
HYBRID (col2)
EXPRESSION
col1 < 100 IN dbslice1,
col1 >= 100 and col1 < 200 IN dbslice2,
REMAINDER IN dbslice3

For more information on an expression-based distribution scheme, see


“Fragmenting by EXPRESSION” on page 2-262.

XPS RANGE Method Clause


You can use a range-fragmentation method as a convenient alternative to
fragmenting by the EXPRESSION or HYBRID clauses. This method provides a
method to implicitly and uniformly distribute data whose fragmentation
column values are dense or naturally uniform.

In a range-fragmented table, the database server assigns each dbspace 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.

SQL Statements 2-265


CREATE TABLE

RANGE Method Back to FRAGMENT BY Clause


Clause p. 2-259

,
Range
RANGE ( column Definition ) IN dbspace
p. 2-268
dbslice

REMAINDER IN dbspace

( ( column Range ) ) ( column ) Range IN


HYBRID RANGE Definition RANGE Clause
p. 2-268 p. 2-269

Range Range IN
HYBRID ( RANGE ( column ) ) RANGE ( column Definition ) Clause
p. 2-268 p. 2-269

Range Range Range IN


HYBRID ( RANGE ( column Definition )) RANGE ( col2 Definition ) Clause
p. 2-268 p. 2-268 p. 2-269

Element Purpose Restrictions Element


column Name of the column on which The column must be in the Identifier, p. 4-205
you want to apply the fragmen- current table.
tation strategy The column must be of type INT
or SMALL INT.
If you use one of the hybrid-
range fragmentation strategies
in which column appears twice,
both occurrences of column must
be the same column.
(1 of 2)

2-266 Informix Guide to SQL: Syntax


CREATE TABLE

Element Purpose Restrictions Element


col2 Name of the column on which The column must be of type INT Identifier, p. 4-205
you want to apply the second or SMALL INT.
fragmentation strategy The column must be in the
current table.
This column must be a different
column from that specified in
column.
dbslice Name of the dbslice that The dbslice must exist when you Identifier, p.4-205
contains the dbspaces in which execute the statement.
the table fragments reside If you list more than one dbslice,
including a remainder dbslice,
each dbslice must contain the
same number of dbspaces.
dbspace Name of the dbspace that The dbspace must exist when Identifier, p. 4-205
contains the table fragment you execute the statement.
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.
(2 of 2)

SQL Statements 2-267


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

max_val

MIN min_val MAX

Element Purpose Restrictions Element


max_val Maximum value in the range The value must an INT or Literal Number,
SMALLINT. p. 4-237
The max_val must be greater
than or equal to the min_val if
min_val is supplied.
min_val Minimum value in the range The value must an INT or Literal Number,
The default is 0. SMALLINT. p. 4-237
The min_val must be less than or
equal to the max_val.

You do not have to specify a minimum value.

The database server uses the minimum and maximum values to determine
the exact range of values to allocate for each storage space.

2-268 Informix Guide to SQL: Syntax


CREATE TABLE

Range IN Clause
Use the IN clause to specify the storage spaces across which to distribute the
data.

Range IN Back to RANGE Method Clause


Clause p. 2-265
,

IN dbslice
, REMAINDER IN dbslice
( dbspace ) ,
( dbspace )

Element Purpose Restrictions Element


dbslice Name of the dbslice that The dbslice must exist when you Identifier, p.4-205
contains the dbspaces in which execute the statement.
the table fragments reside If you list more than one dbslice,
including a remainder dbslice,
each dbslice must contain the
same number of dbspaces.
dbspace Name of the dbspace that The dbspace must exist when Identifier, p. 4-205
contains the table fragment you execute the statement.
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 integral values
between the minimum and maximum specified values must be equal to or
greater than the number of storage spaces specified so that the database
server can allocate non-overlapping contiguous ranges across the dbspaces.

SQL Statements 2-269


CREATE TABLE

For example, the following code returns an error because the allocations for
the range cannot be distributed across all specified dbspaces:
CREATE TABLE Tab1 (Col1 INT...)
FRAGMENT BY RANGE (Col1 MIN 5 MAX 7)
IN db1, db2, db3, db4, db5, db6 -- code returns an
error

The error for this example occurs because the specified range contains three
values (5, 6, and 7), but six dbspaces are specified; three values cannot be
distributed across six dbspaces.

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 it once it is created:

■ You cannot change the fragmentation strategy (ALTER FRAGMENT).


■ You cannot rename the columns of the table (RENAME COLUMN).
■ You cannot duplicate the table locally (COPY TABLE).
■ 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 options of the ALTER TABLE statement that you can use on a
table that has range fragmentation.

Examples
The following examples illustrate range fragmentation in its simple and
hybrid forms.

2-270 Informix Guide to SQL: Syntax


CREATE TABLE

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

db1 100 <= Col1 < 125

db2 125 <= Col1 < 150

db3 150 <= Col1 < 175

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

However, 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 methods in relation 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-271


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 fragmen-
tation does not provide subdivisions within either column.

With this type of fragmentation, a query that specifies values for both
columns (such as, WHERE col4 = 128 and col5 = 650) uniquely identifies
the dbspace at the intersection of the two dbslices identified by the columns
independently.

2-272 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-256

,
,
PUT column IN ( sbspace )

,
( )
EXTENT SIZE kbytes

LOG

NO LOG

HIGH INTEG

KEEP ACCESS TIME

NO KEEP ACCESS TIME

SQL Statements 2-273


CREATE TABLE

Element Purpose Restrictions Syntax


column Name of the column to store in Column must contain a user- Identifier, p. 4-205
the specified sbspace defined type, complex type,
BLOB, or CLOB data type.
The column cannot be in the
form [Link]. That is, the
smart large object that you are
storing cannot be one field of a
row type.
kbytes Number of kilobytes to allocate The number must be an integer Literal Number,
for the extent size value. p. 4-237
sbspace Name of an area of storage used The sbspace must exist. Identifier, p. 4-205
for smart large objects

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.

When you specify more than one sbspace, the database server distributes the
smart large objects in a round-robin distribution scheme so that the number
of smart large objects in each space is approximately equal. The fragmen-
tation scheme is stored in the syscolattribs system catalog table.

When you fragment smart large objects across different sbspaces you can
work with smaller sbspaces. If you limit the size of an sbspace, backup and
archive operations can perform more quickly. For an example that uses the
PUT clause, see “Storage Options” on page 2-256.

Important: The PUT clause does not affect the storage of simple-large-object data
types (BYTE and TEXT). For information on how to store BYTE and TEXT data, see
“Large-Object Data Types” on page 4-62.

2-274 Informix Guide to SQL: Syntax


CREATE TABLE

Using Options in the PUT Clause


The following table describes the storage options available when you store
BLOB and CLOB data.

Option Purpose

EXTENT SIZE Specifies the number of 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 TIME Records, in the smart-large-object metadata, the system


time at which the corresponding smart large object was last
read or written.
This capability is provided for compatibility with the
Illustra interface.

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 that the logical log fills up. For an alter-
native, see “Alternative to Full Logging” on page 2-276.

NO LOG Turns off logging.


The NO LOG option is the default logging behavior.

NO KEEP ACCESS Do not record the system time at which the corresponding
TIME smart large object was last read or written.
This option provides better performance than the KEEP
ACCESS TIME option.
This option is the default tracking behavior.

If a user-defined type or complex type contains more than one large object,
the specified large-object storage options apply to all large objects in the type
unless the storage options are overridden when the large object is created.

SQL Statements 2-275


CREATE TABLE

Alternative to Full Logging


Instead of full logging, you might turn off logging when you load the smart
large object initially, and then turn logging back on once the smart large
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.

Example of Using the PUT Clause


The following statement creates the greek table. The data for the table is
fragmented into the dbs1 and dbs2 dbspaces. However, 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 in the eps column is
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


Use the extent size options to define the size of the extents assigned to the
table.

EXTENT SIZE Option Back to Storage Options


p. 2-256

EXTENT SIZE first_kilobytes NEXT SIZE next_kilobytes

2-276 Informix Guide to SQL: Syntax


CREATE TABLE

Element Purpose Restrictions Syntax


first_kilobytes Length in kilobytes of the first The minimum length is four Expression, p.4-73
extent for the table times the disk-page size on your
The default is 16 kilobytes. system. 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.
next_kilobytes Length in kilobytes for the The minimum length is four Expression, p.4-73
subsequent extents times the disk-page size on your
The default is 16 kilobytes. system. 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 a first extent of 20 kilobytes and allows the
rest of the extents to use the default size:
CREATE TABLE emp_info
(
f_name CHAR(20),
l_name CHAR(20),
position CHAR(20),
start_date DATETIME YEAR TO DAY,
comments VARCHAR(255)
)
EXTENT SIZE 20

Revising Extent Sizes


If you need to revise the extent sizes of a table, you can modify the extent and
next-extent sizes in the generated schema files of an unloaded table. For
example, to make a database more efficient, you might unload a table, modify
the extent sizes in the schema files and then create and load a new table. For
information about optimizing extents, see your Administrator’s Guide.

SQL Statements 2-277


CREATE TABLE

LOCK MODE Options


Use the LOCK MODE options to specify the locking granularity of the table.

LOCK MODE Back to Options


Options p. 2-255

LOCK MODE PAGE

ROW

XPS TABLE

The following table describes the locking-granularity options available.

Locking-
Granularity Option Purpose
ROW Obtains and releases one lock per row
Row-level locking provides the highest level of concurrency.
However, if you are using many rows at one time, the lock-
management overhead can become significant. You can also
exceed the maximum number of locks available, depending on
the configuration of your database server.
PAGE Obtains and releases one lock on a whole page of rows
This is the default locking granularity.
Page-level locking is especially useful when you know that the
rows are grouped into pages in the same order that you are
using to process all the rows. For example, if you are processing
the contents of a table in the same order as its cluster index,
page locking is appropriate.
TABLE Places a lock on the entire table
(XPS only) This type of lock reduces update concurrency compared to row
and page locks. A table lock reduces the lock-management
overhead for the table
With table locking, multiple read-only transactions can still
access the table.

You can change the lock mode of an existing table with the ALTER TABLE
statement.

2-278 Informix Guide to SQL: Syntax


CREATE TABLE

IDS USING Access-Method Clause


A primary access method is a set of routines that perform all of the operations
you need to make a table available to a server, such as create, drop, insert,
delete, update, and scan. The database server provides a built-in primary
access method.

You store and manage a virtual table either outside of the database server in
an extspace or inside the database server in an sbspace. (See “Storage
Options” on page 2-256.) You can access a virtual table with SQL statements.
Access to a virtual table requires a user-defined primary access method.

DataBlade modules can provide other primary access methods to access


virtual tables. When you access a virtual table, the database server calls the
routines associated with that access method rather than the built-in table
routines. For more information on these other primary access methods, refer
to your access method documentation.

USING Access-Method Back to Options


Clause p. 2-255

,
Specific
USING Name
p. 4-296 ,

( config_ keyword )
= ' config_value '

Element Purpose Restrictions Syntax


config_keyword Configuration keyword The maximum length is 18 bytes.
associated with the specified
access method name
config_value Value of the specified configu- The value must be defined by Quoted String,
ration keyword the access method. p. 4-260
You can retrieve a list of configu- Not all keywords require config-
ration values for an access uration values.
method from a table descriptor The maximum length is
(mi_am_table_desc) using the 236 bytes.
MI_TAB_AMPARAM macro.

SQL Statements 2-279


CREATE TABLE

For example, if an access method called textfile exists, you can specify that
access method with the following syntax:
create table mybook
(... )
IN myextspace
USING textfile (delimiter=’:’)

The access method must already exist.

IDS OF TYPE Clause


Use the OF TYPE clause to create a typed table for an object-relational database.
A typed table is a table that has a named-row type assigned to it.

OF TYPE Clause Back to CREATE TABLE


p. 2-230

OF TYPE row_type ( ) Options


p. 2-255
,

, Multiple-Column
Constraint Format
p. 2-250 UNDER supertable

Element Purpose Restrictions Syntax


row_type Name of the row type on which This type must already exist and Data Type, p. 4-53
this table is based must be a named-row type. Identifier, p. 4-205
If you are using the UNDER
clause, the row_type must be
derived from the row type of the
supertable.
supertable Name of the table from which The supertable must already Database Object
this table inherits its properties exist as a typed table. Name, p. 4-50
A type hierarchy must already
exist in which the named-row
type of this table is a subtype of
the named-row type of the
supertable.

2-280 Informix Guide to SQL: Syntax


CREATE TABLE

When you create a typed table, the columns of the table are not named in the
CREATE TABLE statement. Instead, the columns are specified when you create
the row type. The columns of a typed table correspond to the fields of the
named-row type. You cannot add additional columns to a typed table.

For example, suppose you create a named-row type, student_t, as follows:


CREATE ROW TYPE student_t
(name VARCHAR(30),
average REAL,
birthdate DATETIME YEAR TO DAY)

If a table is assigned the type student_t, the table is a typed table whose
columns are of the same name and data type (and in the same order) as the
fields of the type student_t.

The following CREATE TABLE statement creates a typed table named


students whose type is student_t:
CREATE TABLE students OF TYPE student_t

The students table has the following columns:


name VARCHAR(30)
average REAL
birthdate DATETIME

For more information about row types, refer to the CREATE ROW TYPE
statement on page 1-194.

Using Large-Object Data in Typed Tables


Informix recommends that you use the BLOB or CLOB data types instead of
the BYTE or TEXT data types when you create a typed table that contains
columns for large objects. For backward compatibility, you can create a
named-row type that contains BYTE or TEXT fields and use that type to
recreate an existing (untyped) table as a typed table. However, although you
can use a row type that contains BYTE or TEXT fields to create a typed table,
you cannot use such a row type as a column. You can use a row type that
contains BLOB or CLOB fields in both typed tables and columns.

SQL Statements 2-281


CREATE TABLE

Using the UNDER Clause


Use the UNDER clause to specify inheritance (that is, define the table as a
subtable.) The subtable inherits properties from the supertable which it is
under. In addition, you can define new properties specific to the subtable.

Continuing the example shown in “OF TYPE Clause” on page 2-280, the
following statements create a typed table, grad_students, that inherits all of
the columns of the students table. In addition, the grad_students table has
columns for adviser and field_of_study that correspond to their respective
fields in the grad_student_t row type:
CREATE ROW TYPE grad_student_t
(adviser CHAR(25),
field_of_study CHAR(40))
UNDER student_t;

CREATE TABLE grad_students OF TYPE grad_student_t


UNDER students;

Properties That a Subtable Inherits


When you use the UNDER clause, the subtable inherits the following
properties:

■ All columns in the supertable


■ All constraints defined on the supertable
■ All indexes defined on the supertable
■ Referential integrity
■ The access method
■ The storage option (including fragmentation strategy)
If a subtable does not define fragments, and if its supertable has
fragments defined, then the subtable inherits the fragments of the
supertable.
■ All triggers defined on the supertable
Tip: Any heritable attributes that are added to a supertable after subtables have been
created will automatically be inherited by existing subtables. You do not need to add
all heritable attributes to a supertable before you create its subtables.

2-282 Informix Guide to SQL: Syntax


CREATE TABLE

Inheritance occurs in one direction only—from supertable to subtable.


Properties of subtables are not inherited by supertables.

Restrictions on the Inheritance Hierarchy


No two tables in a table hierarchy can have the same type. For example, the
final line of the following code sample is illegal because the tables tab2 and
tab3 cannot have the same row type (rowtype2):
create row type rowtype1 (...);
create row type rowtype2 (...) under rowtype1;
create table tab1 of type rowtype1;
create table tab2 of type rowtype2 under tab1;
Illegal --> create table tab3 of type rowtype2 under tab1;

Recording Properties in the System Catalog Tables


Constraints, indexes, and triggers are recorded in the system catalog for the
supertable, but not for subtables that inherit them. Fragmentation infor-
mation is recorded for both supertables and subtables.

For more information about inheritance, refer to the Informix Guide to SQL:
Tutorial.

Privileges on Tables
The privileges on a table describe both who can access the information in the
table and who can create new tables. For more information about privileges,
see “GRANT” on page 2-500.

ANSI In an ANSI-compliant database, no default table-level privileges exist. You


must grant these privileges explicitly. ♦

When set to yes, the environment variable NODEFDAC prevents default


privileges from being granted to PUBLIC on a new table in a database that is
not ANSI compliant.

For information about how to prevent privileges from being granted to


PUBLIC, see the NODEFDAC environment variable in the Informix Guide to
SQL: Reference. For additional information about privileges, see the Informix
Guide to SQL: Tutorial.

SQL Statements 2-283


CREATE TABLE

Default Index Creation Strategy for Constraints


When you create a table with unique or primary-key constraints, the
database server creates an internal, unique, ascending index for each
constraint.

When you create a table with a referential constraint, the database server
creates an internal, nonunique, ascending index for each column specified in
the referential constraint.

The database server stores this internal index in the same location that the
table uses. If you fragment the table, the database server stores the index
fragments in the same dbspaces as the table fragments or in some cases, the
database dbspace.

If you require an index fragmentation strategy that is independent of the


underlying table fragmentation, do not include the constraint when you
create the table. Instead, use the CREATE INDEX statement to create a unique
index with the desired fragmentation strategy. Then use the ALTER TABLE
statement to add the constraint. The new constraint will use the previously
defined index.

Important: In a database without logging, detached checking is the only kind of


constraint checking available. Detached checking means that constraint checking is
performed on a row-by-row basis.

System Catalog Information


When you create a table, the database server adds basic information about
the table to the systables system catalog table and column information to
syscolumns table. The sysblobs table contains information about the
location of dbspaces and simple large objects. The syschunks table in the
sysmaster database contains information about the location of smart large
objects.

The systabauth, syscolauth, sysfragauth, sysprocauth, sysusers, and sysxt-


dtypeauth tables contain information about the privileges that various
CREATE TABLE options require. The systables, sysxtdtypes, and sysinherits
system catalog tables provide information about table types.

2-284 Informix Guide to SQL: Syntax


CREATE TABLE

Related Information
Related statements: ALTER TABLE, CREATE INDEX, CREATE DATABASE,
CREATE EXTERNAL TABLE, CREATE ROW TYPE, CREATE Temporary TABLE,
DROP TABLE, SET Database Object Mode, and SET Transaction Mode

For discussions of database and table creation, including discussions on data


types, data-integrity constraints, and tables in hierarchies, see the Informix
Guide to Database Design and Implementation.

For information about the system catalog tables that store information about
objects in the database, see the Informix Guide to SQL: Reference.

For information about the syschunks table (in the sysmaster database) that
contains information about the location of smart large objects, see your
Administrator’s Reference.

SQL Statements 2-285


CREATE Temporary TABLE

CREATE Temporary TABLE


Use the CREATE Temporary TABLE statement to create a temporary table in
the current database.

Syntax

CREATE TEMP TABLE table Table Definition

XPS

SCRATCH

Table Definition

,
Column Definition Options
( p. 2-288 ) p. 2-292
,
Multiple-Column
, Constraint Format WITH NO LOG
p. 2-290

Element Purpose Restrictions Syntax


table Name assigned to the table The name must be unique in the Database Object
database. Name, p. 4-50

Usage
If you have the Connect privilege on a database, you can create a temporary
table. However, you are the only user who can see the temporary table.

DB In DB-Access, using the CREATE Temporary TABLE statement outside the


CREATE SCHEMA statement generates warnings if you set DBANSIWARN. ♦

2-286 Informix Guide to SQL: Syntax


CREATE Temporary TABLE

E/C The CREATE TABLE statement generates warnings if you use the -ansi flag or
set the DBANSIWARN environment variable. ♦

Using the TEMP Option


Once a TEMP table is created, you can build indexes on the table.

IDS If your database does not have logging, the table behaves in the same way as
a table that uses the WITH NO LOG option. ♦

XPS Using the SCRATCH Option


Use the INTO SCRATCH clause to reduce the overhead of transaction logging.
A scratch table is a nonlogging temporary table that does not support indexes
or referential constraints. A scratch table is identical to a TEMP table created
with the WITH NO LOG option. Operations on scratch tables are not included
in transaction-log operations.

Naming a Temporary Table


A temporary table is associated with a session, not a database. Therefore,
when you create a temporary table, you cannot create another temporary
table with the same name (even for another database) until you drop the first
temporary table or end the session.

The name must be different from existing table, view, or synonym names in
the current database; however, it need not be different from other temporary
table names used by other users.

ANSI In an ANSI-compliant database, the combination [Link] must be unique


in the database. ♦

Using the WITH NO LOG Option


XPS Informix recommends that you use a scratch table rather than a TEMP…WITH
NO LOG table. The behavior of a temporary table that you create with the
WITH NO LOG option is the same as that of a scratch table. ♦

Use the WITH NO LOG option to reduce the overhead of transaction logging.
If you use the WITH NO LOG option, operations on the temporary table are
not included in the transaction-log operations.

SQL Statements 2-287


CREATE Temporary TABLE

You must use the WITH NO LOG option on temporary tables you create in
temporary dbspaces.

IDS If you use the WITH NO LOG option in a database that does not use logging,
the WITH NO LOG option is ignored. ♦
Once you turn off logging on a temporary table, you cannot turn it back on;
a temporary table is, therefore, always logged or never logged.

The following example shows how to prevent logging temporary tables in a


database that uses logging:
CREATE TEMP TABLE tab2
(fname CHAR(15),
lname CHAR(15))
WITH NO LOG

Column Definition
Use the column definition portion of CREATE Temporary TABLE to list the
name, data type, default value, and constraints of a single column.

Column Back to CREATE Temporary TABLE


Definition p. 2-286

column Data Type


p. 4-53
DEFAULT Single-Column
Clause Constraint Format
p. 2-234 p. 2-289

Element Purpose Restrictions Syntax


column Name of a column in the table The name must be unique in a Identifier, p. 4-205
table, but you can use the same
names in different tables in the
same database.

This portion of the CREATE Temporary TABLE statement is almost identical to


the corresponding section in the CREATE TABLE statement. The difference is
that fewer types of constraints are allowed in a temporary table.

2-288 Informix Guide to SQL: Syntax


CREATE Temporary TABLE

Single-Column Constraint Format


Use the single column constraint format to create one or more data-integrity
constraints for a single column in a temporary table.

Single-Column Back to Column Definition


Constraint Format p. 2-288

UNIQUE

NOT NULL +

DISTINCT

PRIMARY KEY

CHECK Clause
p. 2-245

The following table indicates where you can find detailed discussions of
specific constraints.

Constraint For more information, see

CHECK “CHECK Clause” on page 2-245

DISTINCT “Using the UNIQUE or DISTINCT Constraints” on page 2-239

NOT NULL “Using the NOT NULL Constraint” on page 2-239.

PRIMARY KEY “Using the PRIMARY KEY Constraint” on page 2-240

UNIQUE “Using the UNIQUE or DISTINCT Constraints” on page 2-239

Constraints you define on temporary tables are always enabled.

SQL Statements 2-289


CREATE Temporary TABLE

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 Temporary TABLE


Constraint Format p. 2-286
,

UNIQUE ( column )
+

DISTINCT

PRIMARY KEY

CHECK Clause
p. 2-245

Element Purpose Restrictions Syntax


column Name of the column or columns The name must be unique in a Identifier, p. 4-205
on which the constraint is placed table, but you can use the same
names in different tables in the
same database.

This alternative to the column-level constraints portion of the CREATE TABLE


statement allows you to associate multiple columns with a constraint.

Constraints you define on temporary tables are always enabled.

2-290 Informix Guide to SQL: Syntax


CREATE Temporary TABLE

The following table indicates where you can find detailed discussions of
specific constraints.

Constraint For more information, see For an Example, see

CHECK “CHECK Clause” on “Defining Check Constraints


page 2-245 Across Columns” on
page 2-253

DISTINCT “Using the UNIQUE or “Examples that Use the


DISTINCT Constraints” on Multiple-Column Constraint
page 2-239 Format” on page 2-253

PRIMARY KEY “Using the PRIMARY KEY “Defining Composite


Constraint” on page 2-240 Primary and Foreign Keys”
on page 2-254

UNIQUE “Using the UNIQUE or “Examples that Use the


DISTINCT Constraints” on Multiple-Column Constraint
page 2-239 Format” on page 2-253

Options
The CREATE TABLE options let you specify storage locations, locking modes,
and user-defined access methods

You cannot specify initial and next extents for a temporary table. Extents for
a temporary table are always eight pages.

Options Back to CREATE Temporary TABLE


p. 2-286

IDS +
Storage LOCK MODE USING
Options Options Access-Method
WITH CRCOLS p. 2-292 p. 2-278 Clause
p. 2-279

SQL Statements 2-291


CREATE Temporary TABLE

Storage Options
Use the storage-option portion of the CREATE Temporary Table statement to
specify the distribution scheme for the table.

XPS If you are using Extended Parallel Server, you can fragment a temporary
table across multiple dbspaces that different coservers manage. ♦

Storage Back to Options


Options p. 2-292

IDS
IN dbspace
PUT Clause
p. 2-273
XPS dbslice

IDS extspace

FRAGMENT BY
Clause
p. 2-259

Element Purpose Restrictions Syntax


dbspace Name of the dbspace in which to Specified dbspace must already Identifier, p. 4-205
store the table exist.
The default for database tables is
the dbspace in which the current
database resides.
dbslice Name of the dbslice in which to The specified dbslice must Identifier, p. 4-205
store the table already exist.
extspace Name assigned with the Specified extspace must already Refer to the user
onspaces command to a storage exist. documentation for
area outside the database server your custom access
method for more
information.

If you plan to create a fragmented, unique index on a temporary table, you


must specify an explicit expression-based distribution scheme for a
temporary table in the CREATE Temporary TABLE statement.

2-292 Informix Guide to SQL: Syntax


CREATE Temporary TABLE

Where Temporary Tables are Stored


The distribution scheme that you specify with the CREATE Temporary TABLE
statement (either with the IN clause or the FRAGMENT BY clause) takes prece-
dence over the information specified in the DBSPACETEMP environment
variable and the DBSPSCETEMP configuration parameter.

For temporary tables for which you do not specify an explicit distribution
scheme, each temporary table that you create round-robins to a dbspace
specified by the DBSPACETEMP environment variable or the DBSPACETEMP
configuration parameter if the environment variable is not set. For example,
if you create three temporary tables, the first one goes into the dbspace called
tempspc1, the second one goes into tempspc2, and the third one goes into
tempspc3.

This behavior also applies temporary tables that you create with
SELECT...INTO TEMP or SELECT...INTO SCRATCH.

For more information on the DBSPACETEMP environment variable, see


Informix Guide to SQL: Reference.

For more information on the DBSPACETEMP configuration parameter, see


your Administrator’s Reference.

Example
The following example shows how to insert data into a temporary table
called result_tmp to output to a file the results of a user-defined function
(f_one) that returns multiple rows.
CREATE TEMP TABLE result_tmp( ... );
INSERT INTO result_tmp EXECUTE FUNCTION f_one();
UNLOAD TO 'file' SELECT * FROM temp1;

XPS In Extended Parallel Server, to recreate this example use the CREATE
PROCEDURE statement instead of the CREATE FUNCTION statement. ♦

SQL Statements 2-293


CREATE Temporary TABLE

Differences between Temporary Tables and Permanent


Tables
Temporary tables differ from permanent tables in a number of ways.
Temporary tables:

■ have fewer types of constraints available.


■ have fewer options that you can specify.
■ are not preserved.
For more information, see “Duration of Temporary Tables” on
page 2-294.
■ are not visible to other users or sessions.
■ do not appear in the system catalogs.

XPS You can use the following data definition statements on a temporary table
from a secondary coserver: CREATE Temporary TABLE, CREATE INDEX,
CREATE SCHEMA, DROP TABLE, and DROP INDEX.

DB You cannot use the INFO statement and the Info Menu option with temporary
tables. ♦

Duration of Temporary Tables


The duration of a temporary table depends on whether or not that table is
logged.

Logged Temporary Tables


A logged, temporary table exists until one of the following situations occurs:
■ The application disconnects.
■ A DROP TABLE statement is issued on the temporary table.
■ The database is closed.

When any of these events occur, the temporary table is deleted.

2-294 Informix Guide to SQL: Syntax


CREATE Temporary TABLE

Nonlogging Temporary Tables


Nonlogging temporary tables include temp tables created with the WITH NO
LOG option and SCRATCH tables.

A nonlogging, temporary table exists until one of the following situations


occurs:

■ The application disconnects.


■ A DROP TABLE statement is issued on the temporary table.

Because these tables do not disappear when the database is closed, you can
use a nonlogging temporary table to transfer data from one database to
another while the application remains connected.

Related Information
Related statements: ALTER TABLE, CREATE TABLE, CREATE DATABASE, DROP
TABLE, and SELECT

For additional information about the DBANSIWARN and DBSPACETEMP


environment variables, refer to the Informix Guide to SQL: Reference.

For additional information about the ONCONFIG parameter DBSPACETEMP,


see your Administrator’s Guide.

SQL Statements 2-295


CREATE TRIGGER

+
CREATE TRIGGER
Use the CREATE TRIGGER statement to create a trigger on a table.

Syntax

CREATE TRIGGER trigger INSERT ON table Action Clause


p. 2-307
IDS

REFERENCING
Clause Action Clause Trigger
for Insert Referencing Modes
p. 2-310 p. 2-314 p. 2-332

DELETE ON table Action Clause


p. 2-307

REFERENCING
Clause Action Clause
for Delete Referencing
p. 2-311 p. 2-314

UPDATE
Clause ON table Action Clause
p. 2-300 p. 2-307

REFERENCING
Clause Action Clause
IDS for Update Referencing
p. 2-312 p. 2-314

SELECT
Clause ON table Action Clause
p. 2-302 p. 2-307

REFERENCING
Clause Action Clause
for Select Referencing
p. 2-313 p. 2-314

2-296 Informix Guide to SQL: Syntax


CREATE TRIGGER

Element Purpose Restrictions Syntax


table Name of the table that the The name must be different from Database Object
trigger affects any existing table, view, or Name, p. 4-50
synonym name in the current
database.
trigger Name of the trigger You can specify a trigger for the Database Object
current database only. The name Name, p. 4-50
of the trigger must be unique.

Usage
You can use the CREATE TRIGGER statement to define a trigger on a table. A
trigger is a database object that automatically sets off a specified set of SQL
statements when a specified event occurs.

XPS You cannot create a trigger on a raw or static table. When you create a trigger
on an operational table, the table cannot use light appends. For more infor-
mation on light appends, see your Administrator’s Guide.

Information in this statement that discusses nonlogging databases does not


apply to Extended Parallel Server. In Extended Parallel Server, all databases
are logging databases. ♦

Rules for Triggers


You must be either the owner of the table or have the DBA status to create a
trigger on a table.

For information about the relationship between the privileges of the trigger
owner and the privileges of other users, see “Privileges to Execute Triggered
Actions” on page 2-326.

IDS You can use roles with triggers. Role-related statements (CREATE ROLE,
DROP ROLE, and SET ROLE) and SET SESSION AUTHORIZATION statements
can be triggered inside a trigger. Privileges that a user has acquired through
enabling a role or through a SET SESSION AUTHORIZATION statement are not
relinquished when a trigger is executed. ♦

When you create a trigger, the name of the trigger must be unique within a
database.

SQL Statements 2-297


CREATE TRIGGER

You can create a trigger only on a table in the current database. You cannot
create a trigger on a temporary table, a view, or a system catalog table.

You cannot create a trigger inside an SPL routine if the routine is called inside
a data manipulation statement. For example, in the following INSERT
statement, if the sp_items procedure contains a trigger, the database server
returns an error:
INSERT INTO items EXECUTE PROCEDURE sp_items

For a list of data manipulation statements, see “Data Manipulation State-


ments” on page 1-10.

You cannot use an SPL variable in a CREATE TRIGGER statement.

DB In DB-Access, if you want to define a trigger as part of a schema, place the


CREATE TRIGGER statement inside a CREATE SCHEMA statement. ♦

E/C If you are embedding the CREATE TRIGGER statement in an ESQL/C program,
you cannot use a host variable in the trigger specification. ♦

Trigger Events
The trigger event specifies the type of statement that activates a trigger. The
trigger event can be an INSERT, DELETE, UPDATE, or SELECT statement. Each