[vertical list of authors]
©    Copyright   ,.
[cover art/text goes here]




Copyright
   
Contents


Copyright
Apache Software FoundationDerby Reference ManualApache Derby
Copyright
Copyright 1997, 2006 The Apache Software Foundation or its licensors, as applicable.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
About this guide
For general information about the Derby documentation, such as a complete list of books, conventions, and further reading, see Getting Started with Derby .
Purpose of this document
This book, the Derby Reference Manual , provides reference information about Derby. It covers Derby's SQL language, the Derby implementation of JDBC, Derby system catalogs, Derby error messages, Derby properties, and SQL keywords.
Audience
This book is a reference for Derby users, typically application developers. Derby users who are not familiar with the SQL standard or the Java programming language will benefit from consulting books on those topics.
Derby users who want a how-to approach to working with Derby or an introduction to Derby concepts should read the Derby Developer's Guide .
How this guide is organized
This guide includes the following sections:
 
SQL language reference
Reference information about Derby's SQL language, including manual pages for statements, functions, and other syntax elements.
 
SQL reserved words
SQL keywords beyond the standard SQL-92 keywords.
 
Derby support for SQL-92 features
A list of SQL-92 features that Derby does and does not support.
 
Derby System Tables
Reference information about the Derby system catalogs.
 
Derby exception messages and SQL states
Information about Derby exception messages.
 
JDBC Reference
Information about Derby's implementation of the JDBC interface include support for JDBC 2.0 features.
 
Setting attributes for the database connection URL
Information about the supported attributes to Derby's JDBC database connection URL.
 
J2EE Compliance: Java Transaction API and javax.sql Extensions
Information about the supported attributes to Derby's support for the Java Transaction API.
 
Derby API
Notes about proprietary APIs for Derby.
SQL language reference
Derby implements an SQL-92 core subset, as well as some SQL-99 features.
This section provides an overview of the current SQL language by describing the statements, built-in functions, data types, expressions, and special characters it contains.
Capitalization and special characters
Using the classes and methods of JDBC, you submit SQL statements to Derby as strings. The character set permitted for strings containing SQL statements is Unicode. Within these strings, the following rules apply:
 
Double quotation marks delimit special identifiers referred to in SQL-92 as delimited identifiers.
 
Single quotation marks delimit character strings.
 
Within a character string, to represent a single quotation mark or apostrophe, use two single quotation marks. (In other words, a single quotation mark is the escape character for a single quotation mark.)
A double quotation mark does not need an escape character. To represent a double quotation mark, simply use a double quotation mark. However, note that in a Java program, a double quotation mark requires the backslash escape character.
Example:
-- a single quotation mark is the escape character -- for a single quotation mark VALUES 'Joe''s umbrella' -- in ij, you don't need to escape the double quotation marks VALUES 'He said, "hello!"' n = stmt.executeUpdate( "UPDATE aTable setStringcol = 'He said, \"hello!\"'");
 
SQL keywords are case-insensitive. For example, you can type the keyword SELECT as SELECT, Select, select, or sELECT.
 
SQL-92-style identifiers are case-insensitive (see SQL92Identifier ), unless they are delimited.
 
Java-style identifiers are always case-sensitive.
 
* is a wildcard within a SelectExpression . See The * wildcard . It can also be the multiplication operator. In all other cases, it is a syntactical metasymbol that flags items you can repeat 0 or more times.
 
% and _ are character wildcards when used within character strings following a LIKE operator (except when escaped with an escape character). See Boolean expression .
 
Two dashes (--) and a newline character delimit a comment, as per the SQL-92 standard. The two dashes start the comment and the newline character ends the comment.
SQL identifiers
An identifier is the representation within the language of items created by the user, as opposed to language keywords or commands. Some identifiers stand for dictionary objects, which are the objects you create- such as tables, views, indexes, columns, and constraints- that are stored in a database. They are called dictionary objects because Derby stores information about them in the system tables, sometimes known as a data dictionary. SQL also defines ways to alias these objects within certain statements.
Each kind of identifier must conform to a different set of rules. Identifiers representing dictionary objects must conform to SQL-92 identifier rules and are thus called SQL92Identifier s.
Rules for SQL92 identifiers
Ordinary identifiers are identifiers not surrounded by double quotation marks. Delimited identifiers are identifiers surrounded by double quotation marks.
An ordinary identifier must begin with a letter and contain only letters, underscore characters (_), and digits. The permitted letters and digits include all Unicode letters and digits, but Derby does not attempt to ensure that the characters in identifiers are valid in the database's locale.
A delimited identifier can contain any characters within the double quotation marks. The enclosing double quotation marks are not part of the identifier; they serve only to mark its beginning and end. Spaces at the end of a delimited identifier are insignificant (truncated). Derby translates two consecutive double quotation marks within a delimited identifier as one double quotation mark-that is, the "translated" double quotation mark becomes a character in the delimited identifier.
Periods within delimited identifiers are not separators but are part of the identifier (the name of the dictionary object being represented).
So, in the following example:
"A.B"
is a dictionary object, while
"A"."B"
is a dictionary object qualified by another dictionary object (such as a column named "B" within the table "A").
SQL92Identifier
An SQL92Identifier is a dictionary object identifier that conforms to the rules of SQL-92. SQL-92 states that identifiers for dictionary objects are limited to 128 characters and are case-insensitive (unless delimited by double quotes), because they are automatically translated into uppercase by the system. You cannot use reserved words as identifiers for dictionary objects unless they are delimited. If you attempt to use a name longer than 128 characters, SQLException X0X11 is raised.
Derby defines keywords beyond those specified by the SQL-92 standard (see SQL reserved words ).
Example
-- the view name is stored in the -- system catalogs as ANIDENTIFIER CREATE VIEW AnIdentifier (RECEIVED) AS VALUES 1 -- the view name is stored in the system -- catalogs with case intact CREATE VIEW "ACaseSensitiveIdentifier" (RECEIVED) AS VALUES 1
This section describes the rules for using SQL92Identifiers to represent the following dictionary objects.
Qualifying dictionary objects
Since some dictionary objects can be contained within other objects, you can qualify those dictionary object names. Each component is separated from the next by a period. An SQL92Identifier is "dot-separated." You qualify a dictionary object name in order to avoid ambiguity.
column-Name
In many places in the SQL syntax, you can represent the name of a column by qualifying it with a table-Name or correlation-Name.
In some situations, you cannot qualify a column-Name with a table-Name or a correlation-Name, but must use a Simple-column-Name instead. Those situations are:
 
creating a table ( CREATE TABLE statement )
 
specifying updatable columns in a cursor
 
in a column's correlation name in a SELECT expression (see SelectExpression )
 
in a column's correlation name in a TableExpression (see TableExpression )
You cannot use correlation-Names for updatable columns; using correlation-Names in this way will cause an SQL exception. For example:
SELECT c11 AS col1, c12 AS col2, c13 FROM t1 FOR UPDATE of c11,c13
In this example, the correlation-Name col1 FOR c11 is not permitted because c11 is listed in the FOR UPDATE list of columns. You can use the correlation-Name FOR c12 because it is not in the FOR UPDATE list.
Example
-- C.Country is a column-Name qualified with a -- correlation-Name . SELECT C.Country FROM APP.Countries C
correlation-Name
A correlation-Name is given to a table expression in a FROM clause as a new name or alias for that table. You do not qualify a correlation-Name with a schema-Name.
You cannot use correlation-Names for updatable columns; using correlation-Names in this way will cause an SQL exception. For example:
SELECT c11 AS col1, c12 AS col2, c13 FROM t1 FOR UPDATE of c11,c13
In this example, the correlation-Name col1 FOR c11 is not permitted because c11 is listed in the FOR UPDATE list of columns. You can use the correlation-Name FOR c12 because it is not in the FOR UPDATE list.
Example
-- C is a correlation-Name SELECT C.NAME FROM SAMP.STAFF C
new-table-Name
A new-table-Name represents a renamed table. You cannot qualify a new-table-Name with a schema-Name.
Example
-- FlightBooks is a new-table-Name that does not include a schema-Name RENAME TABLE FLIGHTAVAILABILITY TO FLIGHTAVAILABLE
schemaName
A schemaName represents a schema. Schemas contain other dictionary objects, such as tables and indexes. Schemas provide a way to name a subset of tables and other dictionary objects within a database.
You can explicitly create or drop a schema. The default user schema is the APP schema (if no user name is specified at connection time). You cannot create objects in schemas starting with SYS.
Thus, you can qualify references to tables with the schema name. When a schemaName is not specified, the default schema name is implicitly inserted. System tables are placed in the SYS schema. You must qualify all references to system tables with the SYS schema identifier. For more information about system tables, see Derby System Tables .
A schema is hierarchically the highest level of dictionary object, so you cannot qualify a schemaName.
Syntax
SQL92Identifier
Example
-- SAMP.EMPLOYEE is a table-Name qualified by a schemaName SELECT COUNT(*) FROM SAMP.EMPLOYEE -- You must qualify system catalog names with their schema, SYS SELECT COUNT(*) FROM SYS.SysColumns
Simple-column-Name
A Simple-column-Name is used to represent a column when it cannot be qualified by a table-Name or correlation-Name. This is the case when the qualification is fixed, as it is in a column definition within a CREATE TABLE statement.
Example
-- country is a Simple-column-Name CREATE TABLE CONTINENT (COUNTRY VARCHAR(26) NOT NULL PRIMARY KEY, COUNTRY_ISO_CODE CHAR(2), REGION VARCHAR(26))
synonym-Name
A synonym-Name represents a synonym for a table or a view. You can qualify a synonym-Name with a schema-Name.
table-Name
A table-Name represents a table. You can qualify a table-Name with a schemaName.
Example
-- SAMP.PROJECT is a table-Name that includes a schemaName SELECT COUNT(*) FROM SAMP.PROJECT
view-Name
A view-Name represents a table or a view. You can qualify a view-Name with a schema-Name.
Example
-- This is a View qualified by a schema-Name SELECT COUNT(*) FROM SAMP.EMP_RESUME
index-Name
An index-Name represents an index. Indexes live in schemas, so you can qualify their names with schema-Names. Indexes on system tables are in the SYS schema.
Example
DROP INDEX APP.ORIGINDEX; -- OrigIndex is an index-Name without a schema-Name CREATE INDEX ORIGINDEX ON FLIGHTS (ORIG_AIRPORT)
constraint-Name
You cannot qualify constraint-names.
Example
-- country_fk2 is a constraint name CREATE TABLE DETAILED_MAPS (COUNTRY_ISO_CODE CHAR(2) CONSTRAINT country_fk2 REFERENCES COUNTRIES)
cursor-Name
A cursor-Name refers to a cursor. No SQL language command exists to assign a name to a cursor. Instead, you use the JDBC API to assign names to cursors or to retrieve system-generated names. For more information, see the Derby Developer's Guide . If you assign a name to a cursor, you can refer to that name from within SQL statements.
You cannot qualify a cursor-Name.
Example
stmt.executeUpdate("UPDATE SAMP.STAFF SET COMM = " + "COMM + 20 " + "WHERE CURRENT OF " + ResultSet.getCursorName());
TriggerName
A TriggerName refers to a trigger created by a user.
Example
DROP TRIGGER TRIG1
AuthorizationIdentifier
User names within the Derby system are known as authorization identifiers. The authorization identifier represents the name of the user, if one has been provided in the connection request. The default schema for a user is equal to its authorization identifier. User names can be case-sensitive within the authentication system, but they are always case-insensitive within Derby's authorization system unless they are delimited. For more information, see the Derby Developer's Guide .
Example
CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY( 'derby.database.fullAccessUsers', 'Amber,FRED')
Statements
This section provides manual pages for both high-level language constructs and parts thereof. For example, the CREATE INDEX statement is a high-level statement that you can execute directly via the JDBC interface. This section also includes clauses, which are not high-level statements and which you cannot execute directly but only as part of a high-level statement. The ORDER BY and WHERE clauses are examples of this kind of clause. Finally, this section also includes some syntactically complex portions of statements called expressions, for example SelectExpression and TableSubquery . These clauses and expressions receive their own manual pages for ease of reference.
Unless it is explicitly stated otherwise, you can execute or prepare and then execute all the high-level statements, which are all marked with the word statement, via the interfaces provided by JDBC. This manual indicates whether an expression can be executed as a high-level statement.
The sections provide general information about statement use, and descriptions of the specific statements.
Interaction with the dependency system
Derby internally tracks the dependencies of prepared statements, which are SQL statements that are precompiled before being executed. Typically they are prepared (precompiled) once and executed multiple times.
Prepared statements depend on the dictionary objects and statements they reference. (Dictionary objects include tables, columns, constraints, indexes, views, and triggers.) Removing or modifying the dictionary objects or statements on which they depend invalidates them internally, which means that Derby will automatically try to recompile the statement when you execute it. If the statement fails to recompile, the execution request fails. However, if you take some action to restore the broken dependency (such as restoring the missing table), you can execute the same prepared statement, because Derby will recompile it automatically at the next execute request.
Statements depend on one another-an UPDATE WHERE CURRENT statement depends on the statement it references. Removing the statement on which it depends invalidates the UPDATE WHERE CURRENT statement.
In addition, prepared statements prevent execution of certain DDL statements if there are open results sets on them.
Manual pages for each statement detail what actions would invalidate that statement, if prepared.
Here is an example using the Derby tool ij:
ij> CREATE TABLE mytable (mycol INT); 0 rows inserted/updated/deleted ij> INSERT INTO mytable VALUES (1), (2), (3); 3 rows inserted/updated/deleted -- this example uses the ij command prepare, -- which prepares a statement ij> prepare p1 AS 'INSERT INTO MyTable VALUES (4)'; -- p1 depends on mytable; ij> execute p1; 1 row inserted/updated/deleted -- Derby executes it without recompiling ij> CREATE INDEX i1 ON mytable(mycol); 0 rows inserted/updated/deleted -- p1 is temporarily invalidated because of new index ij> execute p1; 1 row inserted/updated/deleted -- Derby automatically recompiles p1 and executes it ij> DROP TABLE mytable; 0 rows inserted/updated/deleted -- Derby permits you to drop table -- because result set of p1 is closed -- however, the statement p1 is temporarily invalidated ij> CREATE TABLE mytable (mycol INT); 0 rows inserted/updated/deleted ij> INSERT INTO mytable VALUES (1), (2), (3); 3 rows inserted/updated/deleted ij> execute p1; 1 row inserted/updated/deleted -- Because p1 is invalid, Derby tries to recompile it -- before executing. -- It is successful and executes. ij> DROP TABLE mytable; 0 rows inserted/updated/deleted -- statement p1 is now invalid, -- and this time the attempt to recompile it -- upon execution will fail ij> execute p1; ERROR 42X05: Table 'MYTABLE' does not exist.
ALTER TABLE statement
The ALTER TABLE statement allows you to:
 
add a column to a table
 
add a constraint to a table
 
drop an existing constraint from a table
 
increase the width of a VARCHAR, CHAR VARYING, and CHARACTER VARYING column
 
override row-level locking for the table (or drop the override)
Syntax
ALTER TABLE table-Name { ADD COLUMN column-definition | ADD CONSTRAINT clause | DROP { PRIMARY KEY | FOREIGN KEY constraint-name | UNIQUE constraint-name | CHECK constraint-name | CONSTRAINT constraint-name } ALTER column-alteration | LOCKSIZE { ROW | TABLE } }
column-definition
Simple-column-Name DataType [ Column-level-constraint ]* [ [ WITH ] DEFAULT {ConstantExpression | NULL } ]
column-alteration
column-Name SET DATA TYPE VARCHAR(integer) | column-name SET INCREMENT BY integer-constant
In the column-alteration, SET INCREMENT BY integer-constant, specifies the interval between consecutive values of the identity column. The next value to be generated for the identity column will be determined from the last assigned value with the increment applied. The column must already be defined with the IDENTITY attribute.
ALTER TABLE does not affect any view that references the table being altered. This includes views that have an "*" in their SELECT list. You must drop and re-create those views if you wish them to return the new columns.
Adding columns
The syntax for the column-definition for a new column is the same as for a column in a CREATE TABLE statement. This means that a column constraint can be placed on the new column within the ALTER TABLE ADD COLUMN statement. However, a column with a NOT NULL constraint can be added to an existing table if you give a default value; otherwise, an exception is thrown when the ALTER TABLE statement is executed.
Just as in CREATE TABLE, if the column definition includes a unique or primary key constraint, the column cannot contain null values, so the NOT NULL attribute must also be specified (SQLSTATE 42831).
Note: If a table has an UPDATE trigger without an explicit column list, adding a column to that table in effect adds that column to the implicit update column list upon which the trigger is defined, and all references to transition variables are invalidated so that they pick up the new column.
Adding constraints
ALTER TABLE ADD CONSTRAINT adds a table-level constraint to an existing table. Any supported table-level constraint type can be added via ALTER TABLE. The following limitations exist on adding a constraint to an existing table:
 
When adding a foreign key or check constraint to an existing table, Derby checks the table to make sure existing rows satisfy the constraint. If any row is invalid, Derby throws a statement exception and the constraint is not added.
 
All columns included in a primary key must contain non null data and be unique.
ALTER TABLE ADD UNIQUE or PRIMARY KEY provide a shorthand method of defining a primary key composed of a single column. If PRIMARY KEY is specified in the definition of column C, the effect is the same as if the PRIMARY KEY(C) clause were specified as a separate clause. The column cannot contain null values, so the NOT NULL attribute must also be specified.
For information on the syntax of constraints, see CONSTRAINT clause . Use the syntax for table-level constraint when adding a constraint with the ADD TABLE ADD CONSTRAINT syntax.
Dropping constraints
ALTER TABLE DROP CONSTRAINT drops a constraint on an existing table. To drop an unnamed constraint, you must specify the generated constraint name stored in SYS.SYSCONSTRAINTS as a delimited identifier.
Dropping a primary key, unique, or foreign key constraint drops the physical index that enforces the constraint (also known as a backing index).
Modifying columns
The column-alteration allows you to alter the named column in the following ways:
 
Increasing the length of an existing VARCHAR column. CHARACTER VARYING or CHAR VARYING can be used as synonyms for the VARCHAR keyword.
To increase the width of a column of these types, specify the data type and new size after the column name.
You are not allowed to decrease the width or to change the data type. You are not allowed to increase the width of a column that is part of a primary or unique key referenced by a foreign key constraint or that is part of a foreign key constraint.
 
Specifying the interval between consecutive values of the identity column.
To set an interval between consecutive values of the identity column, specify the integer-constant. You must previously define the column with the IDENTITY attribute (SQLSTATE 42837). If there are existing rows in the table, the values in the column for which the SET INCREMENT default was added do not change.
Setting defaults
You can specify a default value for a new column. A default value is the value that is inserted into a column if no other value is specified. If not explicitly specified, the default value of a column is NULL. If you add a default to a new column, existing rows in the table gain the default value in the new column.
For more information about defaults, see CREATE TABLE statement .
Changing the lock granularity for the table
The LOCKSIZE clause allows you to override row-level locking for the specific table, if your system uses the default setting of row-level locking. (If your system is set for table-level locking, you cannot change the locking granularity to row-level locking, although Derby allows you to use the LOCKSIZE clause in such a situation without throwing an exception.) To override row-level locking for the specific table, set locking for the table to TABLE. If you created the table with table-level locking granularity, you can change locking back to ROW with the LOCKSIZE clause in the ALTER TABLE STATEMENT. For information about why this is sometimes useful, see Tuning Derby .
Examples
-- Add a new column with a column-level constraint -- to an existing table -- An exception will be thrown if the table -- contains any rows -- since the newcol will be initialized to NULL -- in all existing rows in the table ALTER TABLE CITIES ADD COLUMN REGION VARCHAR(26) CONSTRAINT NEW_CONSTRAINT CHECK (REGION IS NOT NULL); -- Add a new unique constraint to an existing table -- An exception will be thrown if duplicate keys are found ALTER TABLE SAMP.DEPARTMENT ADD CONSTRAINT NEW_UNIQUE UNIQUE (DEPTNO); -- add a new foreign key constraint to the -- Cities table. Each row in Cities is checked -- to make sure it satisfied the constraints. -- if any rows don't satisfy the constraint, the -- constraint is not added ALTER TABLE CITIES ADD CONSTRAINT COUNTRY_FK Foreign Key (COUNTRY) REFERENCES COUNTRIES (COUNTRY); -- Add a primary key constraint to a table -- First, create a new table CREATE TABLE ACTIVITIES (CITY_ID INT NOT NULL, SEASON CHAR(2), ACTIVITY VARCHAR(32) NOT NULL); -- You will not be able to add this constraint if the -- columns you are including in the primary key have -- null data or duplicate values. ALTER TABLE Activities ADD PRIMARY KEY (city_id, activity); -- Drop a primary key constraint from the CITIES table ALTER TABLE Cities DROP CONSTRAINT Cities_PK; -- Drop a foreign key constraint from the CITIES table ALTER TABLE Cities DROP CONSTRAINT COUNTRIES_FK; -- add a DEPTNO column with a default value of 1 ALTER TABLE SAMP.EMP_ACT ADD COLUMN DEPTNO INT DEFAULT 1; -- increase the width of a VARCHAR column ALTER TABLE SAMP.EMP_PHOTO ALTER PHOTO_FORMAT SET DATA TYPE VARCHAR(30); -- change the lock granularity of a table ALTER TABLE SAMP.SALES LOCKSIZE TABLE;
Results
An ALTER TABLE statement causes all statements that are dependent on the table being altered to be recompiled before their next execution. ALTER TABLE is not allowed if there are any open cursors that reference the table being altered.
CREATE statements
Use the Create statements with functions, indexes, procedures, schemas, synonyms, tables, triggers, and views.
CREATE FUNCTION statement
The CREATE FUNCTION statement allows you to create Java functions, which you can then use in an expression.
Syntax
CREATE FUNCTION function-name ( [ FunctionParameter [, FunctionParameter ] ] * ) RETURNS DataType [ FunctionElement ] *
function-Name
If schema-Name is not provided, the current schema is the default schema. If a qualified procedure name is specified, the schema name cannot begin with SYS.
FunctionParameter
[ parameter-Name ] DataType
PararameterName must be unique within a function.
The syntax of DataType is described in Data types .
Note: Long data-types such as LONG VARCHAR, LONG VARCHAR FOR BIT DATA, CLOB, and BLOB are not allowed as parameters in a CREATE FUNCTION statement.
FunctionElement
{ | LANGUAGE { JAVA } | EXTERNAL NAME string | PARAMETER STYLE JAVA | { NO SQL | CONTAINS SQL | READS SQL DATA } | { RETURNS NULL ON NULL INPUT | CALLED ON NULL INPUT } }
LANGUAGE
JAVA- the database manager will call the function as a public static method in a Java class.
EXTERNAL NAME string
String describes the Java method to be called when the function is executed, and takes the following form:
class_name.method_name
The External Name cannot have any extraneous spaces.
PARAMETER STYLE
JAVA - The function will use a parameter-passing convention that conforms to the Java language and SQL Routines specification. INOUT and OUT parameters will be passed as single entry arrays to facilitate returning values. Result sets are returned through additional parameters to the Java method of type java.sql.ResultSet[] that are passed single entry arrays.
Derby does not support long column types (for example Long Varchar, BLOB, and so on). An error will occur if you try to use one of these long column types.
NO SQL, CONTAINS SQL, READS SQL DATA
Indicates whether the function issues any SQL statements and, if so, what type.
CONTAINS SQL
Indicates that SQL statements that neither read nor modify SQL data can be executed by the function. Statements that are not supported in any function return a different error.
NO SQL
Indicates that the function cannot execute any SQL statements
READS SQL DATA
Indicates that some SQL statements that do not modify SQL data can be included in the function. Statements that are not supported in any stored function return a different error. This is the default value.
RETURNS NULL ON NULL INPUT or CALLED ON NULL INPUT
Specifies whether the function is called if any of the input arguments is null. The result is the null value.
RETURNS NULL ON NULL INPUT
Specifies that the function is not invoked if any of the input arguments is null. The result is the null value.
CALLED ON NULL INPUT
Specifies that the function is invoked if any or all input arguments are null. This specification means that the function must be coded to test for null argument values. The function can return a null or non-null value. This is the default setting.
The function elements may appear in any order, but each type of element can only appear once. A function definition must contain these elements:
 
LANGUAGE
 
PARAMETER STYLE
 
EXTERNAL NAME
Example
CREATE FUNCTION TO_DEGREES(RADIANS DOUBLE) RETURNS DOUBLE PARAMETER STYLE JAVA NO SQL LANGUAGE JAVA EXTERNAL NAME 'java.lang.Math.toDegrees'
CREATE INDEX statement
A CREATE INDEX statement creates an index on a table. Indexes can be on one or more columns in the table.
Syntax
CREATE [UNIQUE] INDEX index-Name ON table-Name ( Simple-column-Name [ ASC | DESC ] [ , Simple-column-Name [ ASC | DESC ]] * )
The maximum number of columns for an index key in Derby is 16.
An index name cannot exceed 128 characters.
A column must not be named more than once in a single CREATE INDEX statement. Different indexes can name the same column, however.
Derby can use indexes to improve the performance of data manipulation statements (see Tuning Derby ). In addition, UNIQUE indexes provide a form of data integrity checking.
Index names are unique within a schema. (Some database systems allow different tables in a single schema to have indexes of the same name, but Derby does not.) Both index and table are assumed to be in the same schema if a schema name is specified for one of the names, but not the other. If schema names are specified for both index and table, an exception will be thrown if the schema names are not the same. If no schema name is specified for either table or index, the current schema is used.
By default, Derby uses the ascending order of each column to create the index. Specifying ASC after the column name does not alter the default behavior. The DESC keyword after the column name causes Derby to use descending order for the column to create the index. Using the descending order for a column can help improve the performance of queries that require the results in mixed sort order or descending order and for queries that select the minimum or maximum value of an indexed column.
If a qualified index name is specified, the schema name cannot begin with SYS.
Indexes and constraints
Unique, primary key, and foreign key constraints generate indexes that enforce or "back" the constraint (and are thus sometimes called backing indexes). If a column or set of columns has a UNIQUE or PRIMARY KEY constraint on it, you can not create an index on those columns. Derby has already created it for you with a system-generated name. System-generated names for indexes that back up constraints are easy to find by querying the system tables if you name your constraint. For example, to find out the name of the index that backs a constraint called FLIGHTS_PK:
SELECT CONGLOMERATENAME FROM SYS.SYSCONGLOMERATES, SYS.SYSCONSTRAINTS WHERE SYS.SYSCONGLOMERATES.TABLEID = SYSCONSTRAINTS.TABLEID AND CONSTRAINTNAME = 'FLIGHTS_PK'
CREATE INDEX OrigIndex ON Flights(orig_airport); -- money is usually ordered from greatest to least, -- so create the index using the descending order CREATE INDEX PAY_DESC ON SAMP.EMPLOYEE (SALARY); -- use a larger page size for the index call SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.storage.pageSize','8192'); CREATE INDEX IXSALE ON SAMP.SALES (SALES); call SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.storage.pageSize',NULL);
Page size and key size
Note: The size of the key columns in an index must be equal to or smaller than half the page size. If the length of the key columns in an existing row in a table is larger than half the page size of the index, creating an index on those key columns for the table will fail. This error only occurs when creating an index if an existing row in the table fails the criteria. After an index is created, inserts may fail if the size of their associated key exceeds the criteria.
Statement dependency system
Prepared statements that involve SELECT, INSERT, UPDATE, UPDATE WHERE CURRENT, DELETE, and DELETE WHERE CURRENT on the table referenced by the CREATE INDEX statement are invalidated when the index is created. Open cursors on the table are not affected.
CREATE PROCEDURE statement
The CREATE PROCEDURE statement allows you to create Java stored procedures, which you can then call using the CALL PROCEDURE statement.
Syntax
procedure-Name
If schema-Name is not provided, the current schema is the default schema. If a qualified procedure name is specified, the schema name cannot begin with SYS.
ProcedureParameter
[ { IN | OUT | INOUT } ] [ parameter-Name ] DataType
The default value for a parameter is IN. ParameterName must be unique within a procedure.
The syntax of DataType is described in Data types .
Note: Long data-types such as LONG VARCHAR, LONG VARCHAR FOR BIT DATA, CLOB, and BLOB are not allowed as parameters in a CREATE PROCEDURE statement.
ProcedureElement
{ | [ DYNAMIC ] RESULT SETS INTEGER | LANGUAGE { JAVA } | EXTERNAL NAME string | PARAMETER STYLE JAVA | { NO SQL | MODIFIES SQL DATA | CONTAINS SQL | READS SQL DATA } }
DYNAMIC RESULT SETS integer
Indicates the estimated upper bound of returned result sets for the procedure. Default is no (zero) dynamic result sets.
LANGUAGE
JAVA- the database manager will call the procedure as a public static method in a Java class.
EXTERNAL NAME string
String describes the Java method to be called when the procedure is executed, and takes the following form:
class_name.method_name
The External Name cannot have any extraneous spaces.
PARAMETER STYLE
JAVA - The procedure will use a parameter-passing convention that conforms to the Java language and SQL Routines specification. INOUT and OUT parameters will be passed as single entry arrays to facilitate returning values. Result sets are returned through additional parameters to the Java method of type java.sql.ResultSet [] that are passed single entry arrays.
Derby does not support long column types (for example Long Varchar, BLOB, and so on). An error will occur if you try to use one of these long column types.
NO SQL, CONTAINS SQL, READS SQL DATA, MODIFIES SQL DATA
Indicates whether the stored procedure issues any SQL statements and, if so, what type.
CONTAINS SQL
Indicates that SQL statements that neither read nor modify SQL data can be executed by the stored procedure. Statements that are not supported in any stored procedure return a different error. MODIFIES SQL DATA is the default value.
NO SQL
Indicates that the stored procedure cannot execute any SQL statements
READS SQL DATA
Indicates that some SQL statements that do not modify SQL data can be included in the stored procedure. Statements that are not supported in any stored procedure return a different error.
MODIFIES SQL DATA
Indicates that the stored procedure can execute any SQL statement except statements that are not supported in stored procedures.
The procedure elements may appear in any order, but each type of element can only appear once. A procedure definition must contain these elements:
 
LANGUAGE
 
PARAMETER STYLE
 
EXTERNAL NAME
Example
CREATE PROCEDURE SALES.TOTAL_REVENUE(IN S_MONTH INTEGER, IN S_YEAR INTEGER, OUT TOTAL DECIMAL(10,2)) PARAMETER STYLE JAVA READS SQL DATA LANGUAGE JAVA EXTERNAL NAME 'com.acme.sales.calculateRevenueByMonth'
CREATE SCHEMA statement
A schema is a way to logically group objects in a single collection and provide a unique namespace for objects.
Syntax
CREATE SCHEMA schemaName
The CREATE SCHEMA statement is used to create a schema. A schema name cannot exceed 128 characters. Schema names must be unique within the database.
-- Create a schema for employee-related tables CREATE SCHEMA EMP; -- Create a schema for airline-related tables CREATE SCHEMA Flights -- Create a table called "Availability" in each schema CREATE TABLE FLIGHTS.AVAILABILITY (FLIGHT_ID CHAR(6) NOT NULL, SEGMENT_NUMBER INT NOT NULL, FLIGHT_DATE DATE NOT NULL, ECONOMY_SEATS_TAKEN INT, BUSINESS_SEATS_TAKEN INT, FIRSTCLASS_SEATS_TAKEN INT, CONSTRAINT FLT_AVAIL_PK PRIMARY KEY (FLIGHT_ID, SEGMENT_NUMBER, FLIGHT_DATE)); CREATE TABLE EMP.AVAILABILITY (HOTEL_ID INT NOT NULL, BOOKING_DATE DATE NOT NULL, ROOMS_TAKEN INT, CONSTRAINT HOTELAVAIL_PK PRIMARY KEY (HOTEL_ID, BOOKING_DATE));
CREATE SYNONYM statement
Use the CREATE SYNONYM statement to provide an alternate name for a table or a view that is present in the same schema or another schema. You can also create synonyms for other synonyms, resulting in nested synonyms. A synonym can be used instead of the original qualified table or view name in SELECT, INSERT, UPDATE, DELETE or LOCK TABLE statements. You can create a synonym for a table or a view that doesn't exist, but the target table or view must be present before the synonym can be used.
Synonyms share the same namespace as tables or views. You cannot create a synonym with the same name as a table that already exists in the same schema. Similarly, you cannot create a table or view with a name that matches a synonym already present.
A synonym can be defined for a table/view that does not exist when you create the synonym. If the table or view doesn't exist, you will receive a warning message (SQLSTATE 01522). The referenced object must be present when you use a synonym in a DML statement.
You can create a nested synonym (a synonym for another synonym), but any attempt to create a synonym that results in a circular reference will return an error message (SQLSTATE 42916).
Synonyms cannot be defined in system schemas. All schemas starting with 'SYS' are considered system schemas and are reserved by Derby.
A synonym cannot be defined on a temporary table. Attempting to define a synonym on a temporary table will return an error message (SQLSTATE XCL51).
Syntax
CREATE SYNONYM synonym-Name FOR { view-Name | table-Name }
The synonym-Name in the statement represents the synonym name you are giving the target table or view, while the view-Name or table-Name represents the original name of the target table or view.
Example
CREATE SYNONYM SAMP.T1 FOR SAMP.TABLEWITHLONGNAME
CREATE TABLE statement
A CREATE TABLE statement creates a table. Tables contain columns and constraints, rules to which data must conform. Table-level constraints specify a column or columns. Columns have a data type and can specify column constraints (column-level constraints).
For information about constraints, see CONSTRAINT clause .
You can specify a default value for a column. A default value is the value to be inserted into a column if no other value is specified. If not explicitly specified, the default value of a column is NULL. See Column default .
You can specify storage properties such as page size for a table by calling the SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY system procedure.
If a qualified table name is specified, the schema name cannot begin with SYS.
Example
CREATE TABLE HOTELAVAILABILITY (HOTEL_ID INT NOT NULL, BOOKING_DATE DATE NOT NULL, ROOMS_TAKEN INT DEFAULT 0, PRIMARY KEY (HOTEL_ID, BOOKING_DATE)); -- the table-level primary key definition allows you to -- include two columns in the primary key definition PRIMARY KEY (hotel_id, booking_date)) -- assign an identity column attribute to an INTEGER -- column, and also define a primary key constraint -- on the column CREATE TABLE PEOPLE (PERSON_ID INT NOT NULL GENERATED ALWAYS AS IDENTITY CONSTRAINT PEOPLE_PK PRIMARY KEY, PERSON VARCHAR(26)); -- assign an identity column attribute to a SMALLINT -- column with an initial value of 5 and an increment value -- of 5. CREATE TABLE GROUPS (GROUP_ID SMALLINT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 5, INCREMENT BY 5), ADDRESS VARCHAR(100), PHONE VARCHAR(15));
Note: For more examples of CREATE TABLE statements using the various constraints, see CONSTRAINT clause .
column-definition:
Simple-column-Name DataType [ Column-level-constraint ]* [ [ WITH ] DEFAULT { ConstantExpression | NULL } | generated-column-spec ] [ Column-level-constraint ]*
The syntax of Data-Type is described in Data types .
Column default
For the definition of a default value, a ConstantExpression is an expression that does not refer to any table. It can include constants, date-time special registers, current schemas, users, and null.
generated-column-spec:
[ GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY [ ( START WITH IntegerConstant [ ,INCREMENT BY IntegerConstant] ) ] ] ]
Identity column attributes
For SMALLINT, INT, and BIGINT columns with identity attributes, Derby automatically assigns increasing integer values to the column. Identity column attributes behave like other defaults in that when an insert statement does not specify a value for the column, Derby automatically provides the value. However, the value is not a constant; Derby automatically increments the default value at insertion time.
The IDENTITY keyword can only be specified if the data type associated with the column is one of the following exact integer types.
 
SMALLINT
 
INT
 
BIGINT
There are two kinds of identity columns in Derby: those which are GENERATED ALWAYS and those which are GENERATED BY DEFAULT.
GENERATED ALWAYS
An identity column that is GENERATED ALWAYS will increment the default value on every insertion and will store the incremented value into the column. Unlike other defaults, you cannot insert a value directly into or update an identity column that is GENERATED ALWAYS. Instead, either specify the DEFAULT keyword when inserting into the identity column, or leave the identity column out of the insertion column list altogether. For example:
create table greetings (i int generated always as identity, ch char(50)); insert into greetings values (DEFAULT, 'hello'); insert into greetings(ch) values ('bonjour');
Automatically generated values in a GENERATED ALWAYS identity column are unique. Creating an identity column does not create an index on the column.
GENERATED BY DEFAULT
An identity column that is GENERATED BY DEFAULT will only increment and use the default value on insertions when no explicit value is given. Unlike GENERATED ALWAYS columns, you can specify a particular value in an insertion statement to be used instead of the generated default value.
To use the generated default, either specify the DEFAULT keyword when inserting into the identity column, or just leave the identity column out of the insertion column list. To specify a value, included it in the insertion statement. For example:
create table greetings (i int generated by default as identity, ch char(50)); -- specify value "1": insert into greetings values (1, 'hi'); -- use generated default insert into greetings values (DEFAULT, 'salut'); -- use generated default insert into greetings(ch) values ('bonjour');
Note that unlike a GENERATED ALWAYS column, a GENERATED BY DEFAULT column does not guarantee uniqueness. Thus, in the above example, the hi and salut rows will both have an identity value of "1", because the generated column starts at "1" and the user-specified value was also "1". To prevent duplication, especially when loading or importing data, create the table using the START WITH value which corresponds to the first identity value that the system should assign. To check for this condition and disallow it, you can use a primary key or unique constraint on the GENERATED BY DEFAULT identity column.
By default, the initial value of an identity column is 1, and the amount of the increment is 1. You can specify non-default values for both the initial value and the interval amount when you define the column with the key words STARTS WITH and INCREMENT BY. And if you specify a negative number for the increment value, Derby decrements the value with each insert. If this value is 0, or positive, Derby increments the value with each insert.
The maximum and minimum values allowed in identity columns are determined by the data type of the column. Attempting to insert a value outside the range of values supported by the data type raises an exception.
Table1. Maximum and Minimum Values for Columns with Generated Column Specs
Data type
Maximum Value
Minimum Value
SMALLINT
32767 (java.lang.Short.MAX_VALUE)
-32768 (java.lang.Short.MIN_VALUE)
INT