Derby Reference Manual
Version 10
Derby Document build:
December 11, 2006, 7:09:24 AM (PST)
© Copyright  2004, 2006:  Apache Software Foundation




Copyright
   
Contents
Copyright    
About this guide    
Purpose of this document    
Audience    
How this guide is organized    
SQL language reference    
Capitalization and special characters    
SQL identifiers    
Rules for SQL92 identifiers    
SQL92Identifier    
column-Name    
correlation-Name    
new-table-Name    
schemaName    
Simple-column-Name    
synonym-Name    
table-Name    
view-Name    
index-Name    
constraint-Name    
cursor-Name    
TriggerName    
AuthorizationIdentifier    
Statements    
Interaction with the dependency system    
ALTER TABLE statement    
CREATE statements    
DROP Statements    
GRANT statement    
RENAME statements    
REVOKE statement    
SET statements    
CALL (PROCEDURE)    
CONSTRAINT clause    
DECLARE GLOBAL TEMPORARY TABLE statement    
DELETE statement    
FOR UPDATE clause    
FROM clause    
GROUP BY clause    
HAVING clause    
INNER JOIN    
INSERT statement    
JOIN operation    
LEFT OUTER JOIN    
LOCK TABLE statement    
ORDER BY clause    
Query    
RIGHT OUTER JOIN    
ScalarSubquery    
SelectExpression    
SELECT statement    
TableExpression    
TableSubquery    
UPDATE statement    
VALUES expression    
WHERE clause    
WHERE CURRENT OF clause    
Built-in functions    
Standard built-in functions    
Aggregates (set functions)    
ABS or ABSVAL    
ACOS function    
ASIN function    
ATAN function    
AVG    
BIGINT    
CAST    
CEIL or CEILING function    
CHAR    
Concatenation    
COS function    
COUNT    
COUNT(*)    
CURRENT DATE    
CURRENT_DATE    
CURRENT ISOLATION    
CURRENT SCHEMA    
CURRENT TIME    
CURRENT_TIME    
CURRENT TIMESTAMP    
CURRENT_TIMESTAMP    
CURRENT_USER    
DATE    
DAY    
DEGREES function    
DOUBLE    
EXP function    
FLOOR function    
HOUR    
IDENTITY_VAL_LOCAL    
INTEGER    
LCASE or LOWER    
LENGTH    
LN or LOG function    
LOG10 function    
LOCATE    
LTRIM    
MAX    
MIN    
MINUTE    
MOD    
MONTH    
NULLIF and CASE expressions    
PI function    
RADIANS function    
RTRIM    
SECOND    
SESSION_USER    
SIN function    
SMALLINT    
SQRT    
SUBSTR    
TAN function    
SUM    
TIME    
TIMESTAMP    
UCASE or UPPER    
USER    
VARCHAR    
XMLEXISTS operator    
XMLPARSE operator    
XMLQUERY operator    
XMLSERIALIZE operator    
YEAR    
Built-in system functions    
SYSCS_UTIL.SYSCS_CHECK_TABLE    
SYSCS_UTIL.SYSCS_GET_RUNTIMESTATISTICS    
SYSCS_UTIL.SYSCS_GET_DATABASE_PROPERTY    
Built-in system procedures    
SYSCS_UTIL.SYSCS_COMPRESS_TABLE    
SYSCS_UTIL.SYSCS_INPLACE_COMPRESS_TABLE    
SYSCS_UTIL.SYSCS_SET_RUNTIMESTATISTICS    
SYSCS_UTIL.SYSCS_SET_STATISTICS_TIMING    
SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY    
SYSCS_UTIL.SYSCS_FREEZE_DATABASE    
SYSCS_UTIL.SYSCS_UNFREEZE_DATABASE    
SYSCS_UTIL.SYSCS_CHECKPOINT_DATABASE    
SYSCS_UTIL.SYSCS_BACKUP_DATABASE    
SYSCS_UTIL.SYSCS_BACKUP_DATABASE_NOWAIT    
SYSCS_UTIL.SYSCS_BACKUP_DATABASE_AND_ENABLE_LOG_ARCHIVE_MODE    
SYSCS_UTIL.SYSCS_BACKUP_DATABASE_AND_ENABLE_LOG_ARCHIVE_MODE_NOWAIT    
SYSCS_UTIL.SYSCS_DISABLE_LOG_ARCHIVE_MODE    
SYSCS_UTIL.SYSCS_EXPORT_TABLE    
SYSCS_UTIL.SYSCS_EXPORT_QUERY    
SYSCS_UTIL.SYSCS_IMPORT_TABLE    
SYSCS_UTIL.SYSCS_IMPORT_DATA    
Data types    
Built-In type overview    
Numeric types    
Data type assignments and comparison, sorting, and ordering    
BIGINT    
BLOB    
CHAR    
CHAR FOR BIT DATA    
CLOB    
DATE    
DECIMAL    
DOUBLE    
DOUBLE PRECISION    
FLOAT    
INTEGER    
LONG VARCHAR    
LONG VARCHAR FOR BIT DATA    
NUMERIC    
REAL    
SMALLINT    
TIME    
TIMESTAMP    
VARCHAR    
VARCHAR FOR BIT DATA    
XML data type    
SQL expressions    
Expression precedence    
Boolean expression    
Dynamic parameters    
SQL reserved words    
Derby support for SQL-92 features    
Derby System Tables    
SYSALIASES    
SYSCHECKS    
SYSCOLPERMS    
SYSCOLUMNS    
SYSCONGLOMERATES    
SYSCONSTRAINTS    
SYSDEPENDS    
SYSFILES    
SYSFOREIGNKEYS    
SYSKEYS    
SYSROUTINEPERMS    
SYSSCHEMAS    
SYSSTATISTICS    
SYSSTATEMENTS    
SYSTABLEPERMS    
SYSTABLES    
SYSTRIGGERS    
SYSVIEWS    
Derby exception messages and SQL states    
SQL error messages and exceptions    
JDBC Reference    
Core JDBC java.sql Classes, Interfaces, and Methods    
java.sql.Driver    
java.sql.DriverManager.getConnection    
Derby database connection URL syntax    
Syntax of database connection URLs for applications with embedded databases    
Additional SQL syntax    
Attributes of the Derby database connection URL    
java.sql.Driver.getPropertyInfo    
java.sql.Connection    
java.sql.Connection.setTransactionIsolation    
java.sql.Connection.setReadOnly    
java.sql.Connection.isReadOnly    
Connection functionality not supported    
java.sql.DatabaseMetaData    
DatabaseMetaData result sets    
getProcedureColumnsgetProcedureColumns    
Parameters to getProcedureColumns    
Columns in the ResultSet returned by getProcedureColumns    
DatabaseMetaData functionality not supported    
java.sql.Statement    
ResultSet objects    
java.sql.CallableStatement    
CallableStatements and OUT Parameters    
CallableStatements and INOUT Parameters    
java.sql.SQLException    
java.sql.PreparedStatement    
Prepared statements and streaming columns    
java.sql.ResultSet    
ResultSets and streaming columns    
java.sql.ResultSetMetaData    
java.sql.SQLWarning    
java.sql.SQLXML    
Mapping of java.sql.Types to SQL types    
java.sql.Blob and java.sql.Clob    
Notes    
java.sql.Connection    
java.sql.ResultSet    
java.sql.Statement    
java.sql.PreparedStatement    
java.sql.CallableStatement    
java.sql.DatabaseMetaData    
java.sql.ResultSetMetaData    
java.sql.BatchUpdateException    
JDBC Package for Connected Device Configuration/Foundation Profile (JSR169)    
JDBC 3.0-only features    
java.sql.Connection    
java.sql.DatabaseMetaData    
java.sql.ParameterMetaData    
java.sql.PreparedStatement    
java.sql.Savepoint    
java.sql.Statement    
JDBC 4.0-only features    
Refined subclasses of SQLException    
java.sql.Connection    
java.sql.DatabaseMetaData    
java.sql.Statement    
javax.sql.DataSource    
JDBC escape syntax    
JDBC escape keyword for call statements    
JDBC escape syntax    
JDBC escape syntax for LIKE clauses    
JDBC escape syntax for fn keyword    
JDBC escape syntax for outer joins    
JDBC escape syntax for time formats    
JDBC escape syntax for date formats    
JDBC escape syntax for timestamp formats    
Setting attributes for the database connection URL    
bootPassword=key    
create=true    
createFrom=Path    
databaseName=nameofDatabase    
dataEncryption=true    
encryptionKey=<key>    
encryptionProvider=providerName    
encryptionAlgorithm=algorithm    
logDevice=logDirectoryPath    
newEncryptionKey= <key>    
newBootPassword = <new password>    
password=userPassword    
restoreFrom=Path    
rollForwardRecoveryFrom=Path    
shutdown=true    
territory=ll_CC    
user=userName    
(no attributes)    
J2EE Compliance: Java Transaction API and javax.sql Extensions    
JVM and libraries for J2EE features    
The JTA API    
Notes on Product Behavior    
javax.sql: JDBC Extensions    
Derby API    
Stand-alone tools and utilities    
JDBC implementation classes    
JDBC driver    
Data Source Classes    
Miscellaneous utilities and interfaces    
Supported territories    
Derby limitations    
Limitations for database manager values    
DATE, TIME, and TIMESTAMP limitations    
Limitations on identifier length    
Numeric limitations    
String limitations    
XML limitations    
Trademarks    


Copyright
Apache Software FoundationDerby Reference ManualApache Derby
Copyright
Copyright 2004, 2006 The Apache Software Foundation or its licensors, as applicable.
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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 including 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 SQL92Identifiers.
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/View '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)
 
change the increment value and start value of the identity column
 
change the nullability constraint for a column
 
change the default value for a column
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 ] column-alteration | LOCKSIZE { ROW | TABLE } }
column-definition
Simple-column-NameDataType [ Column-level-constraint ]* [ [ WITH ] DEFAULT {ConstantExpression | NULL } ]
column-alteration
column-Name SET DATA TYPE VARCHAR(integer) | column-name SET INCREMENT BY integer-constant | column-name RESTART WITH integer-constant | column-name [ NOT ] NULL | column-name [ WITH ] DEFAULT default-value
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.
RESTART WITH integer-constant specifies the next value to be generated for the identity column. RESTART WITH is useful for a table that has an identity column that was defined as GENERATED BY DEFAULT and that has a unique key defined on that identity column. Because GENERATED BY DEFAULT allows both manual inserts and system generated values, it is possible that manually inserted values can conflict with system generated values. To work around such conflicts, use the RESTART WITH syntax to specify the next value that will be generated for the identity column. Consider the following example, which involves a combination of automatically generated data and manually inserted data:
CREATE TABLE tauto(i INT GENERATED BY DEFAULT AS IDENTITY, k INT) CREATE UNIQUE INDEX tautoInd ON tauto(i) INSERT INTO tauto(k) values 1,2
The system will automatically generate values for the identity column.  But now you need to manually insert some data into the identity column:
INSERT INTO tauto VALUES (3,3) INSERT INTO tauto VALUES (4,4) INSERT INTO tauto VALUES (5,5)
The identity column has used values 1 through 5 at this point.  If you now want the system to generate a value, the system will generate a 3, which will result in a unique key exception because the value 3 has already been manually inserted.  To compensate for the manual inserts, issue an ALTER TABLE statement for the identity column with RESTART WITH 6:
ALTER TABLE tauto ALTER COLUMN i RESTART WITH 6
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.
 
Modifying the nullability constraint of a column.
You can add the NOT NULL constraint to an existing column. To do so there must not be existing NULL values for the column in the table.
You can remove the NOT NULL constraint from an existing column. To do so the column must not be used in a PRIMARY KEY or UNIQUE constraint.
 
Changing the default value for a column.
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; -- Remove the NOT NULL constraint from the MANAGER column ALTER TABLE Employees ALTER COLUMN Manager NULL; -- Add the NOT NULL constraint to the SSN column ALTER TABLE Employees ALTER COLUMN ssn NOT NULL; -- Change the default value for the SALARY column ALTER TABLE Employees ALTER COLUMN Salary DEFAULT 1000.0
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.
The function owner and the database owner automatically gain the EXECUTE privilege on the function, and are able to grant this privilege to other users. The EXECUTE privileges cannot be revoked from the function and database owners.
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: Data-types such as BLOB, CLOB, LONG VARCHAR, LONG VARCHAR FOR BIT DATA, and XML 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</