Java DB Reference Manual
Version 10.4
Derby Document build:
April 21, 2008, 12:28:55 PM (EDT)




Version 10.4   Java DB Reference Manual
   
Contents
Copyright    
License    
Relationship between Java DB and Derby    
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    
CALL (PROCEDURE) statement    
CREATE statements    
DECLARE GLOBAL TEMPORARY TABLE statement    
DELETE statement    
DROP statements    
GRANT statement    
INSERT statement    
LOCK TABLE statement    
RENAME statements    
REVOKE statement    
SET statements    
SELECT statement    
UPDATE statement    
SQL clauses    
CONSTRAINT clause    
FOR UPDATE clause    
FROM clause    
GROUP BY clause    
HAVING clause    
ORDER BY clause    
WHERE clause    
WHERE CURRENT OF clause    
SQL expressions    
SelectExpression    
TableExpression    
VALUES expression    
Expression precedence    
Boolean expressions    
Dynamic parameters    
JOIN operations    
INNER JOIN operation    
LEFT OUTER JOIN operation    
RIGHT OUTER JOIN operation    
SQL queries    
Query    
ScalarSubquery    
TableSubquery    
Built-in functions    
Standard built-in functions    
Aggregates (set functions)    
ABS or ABSVAL function    
ACOS function    
ASIN function    
ATAN function    
AVG function    
BIGINT function    
CASE expressions    
CAST function    
CEIL or CEILING function    
CHAR function    
Concatenation operator    
COS function    
COSH function    
COT function    
COUNT function    
COUNT(*) function    
CURRENT DATE function    
CURRENT_DATE function    
CURRENT ISOLATION function    
CURRENT SCHEMA function    
CURRENT TIME function    
CURRENT_TIME function    
CURRENT TIMESTAMP function    
CURRENT_TIMESTAMP function    
CURRENT_USER function    
DATE function    
DAY function    
DEGREES function    
DOUBLE function    
EXP function    
FLOOR function    
HOUR function    
IDENTITY_VAL_LOCAL function    
INTEGER function    
LCASE or LOWER function    
LENGTH function    
LN or LOG function    
LOG10 function    
LOCATE function    
LTRIM function    
MAX function    
MIN function    
MINUTE function    
MOD function    
MONTH function    
NULLIF expressions    
PI function    
RADIANS function    
RANDOM function    
RAND function    
ROW_NUMBER function    
RTRIM function    
SECOND function    
SESSION_USER function    
SIGN function    
SIN function    
SINH function    
SMALLINT function    
SQRT function    
SUBSTR function    
SUM function    
TAN function    
TANH function    
TIME function    
TIMESTAMP function    
TRIM function    
UCASE or UPPER function    
USER function    
VARCHAR function    
XMLEXISTS operator    
XMLPARSE operator    
XMLQUERY operator    
XMLSERIALIZE operator    
YEAR function    
Built-in system functions    
SYSCS_UTIL.SYSCS_CHECK_TABLE system function    
SYSCS_UTIL.SYSCS_GET_DATABASE_PROPERTY system function    
SYSCS_UTIL.SYSCS_GET_RUNTIMESTATISTICS system function    
SYSCS_UTIL.SYSCS_GET_USER_ACCESS system function    
Built-in system procedures    
SYSCS_UTIL.SYSCS_BACKUP_DATABASE system procedure    
SYSCS_UTIL.SYSCS_BACKUP_DATABASE_NOWAIT system procedure    
SYSCS_UTIL.SYSCS_BACKUP_DATABASE_AND_ENABLE_LOG_ARCHIVE_MODE system procedure    
SYSCS_UTIL.SYSCS_BACKUP_DATABASE_AND_ENABLE_LOG_ARCHIVE_MODE_NOWAIT system procedure    
SYSCS_UTIL.SYSCS_EMPTY_STATEMENT_CACHE system procedure    
SYSCS_UTIL.SYSCS_CHECKPOINT_DATABASE system procedure    
SYSCS_UTIL.SYSCS_COMPRESS_TABLE system procedure    
SYSCS_UTIL.SYSCS_INPLACE_COMPRESS_TABLE system procedure    
SYSCS_UTIL.SYSCS_DISABLE_LOG_ARCHIVE_MODE system procedure    
SYSCS_UTIL.SYSCS_EXPORT_TABLE system procedure    
SYSCS_UTIL.SYSCS_EXPORT_TABLE_LOBS_TO_EXTFILE system procedure    
SYSCS_UTIL.SYSCS_EXPORT_QUERY system procedure    
SYSCS_UTIL.SYSCS_EXPORT_QUERY_LOBS_TO_EXTFILE system procedure    
SYSCS_UTIL.SYSCS_IMPORT_DATA system procedure    
SYSCS_UTIL.SYSCS_IMPORT_DATA_LOBS_FROM_EXTFILE system procedure    
SYSCS_UTIL.SYSCS_IMPORT_TABLE system procedure    
SYSCS_UTIL.SYSCS_IMPORT_TABLE_LOBS_FROM_EXTFILE system procedure    
SYSCS_UTIL.SYSCS_FREEZE_DATABASE system procedure    
SYSCS_UTIL.SYSCS_UNFREEZE_DATABASE system procedure    
SYSCS_UTIL.SYSCS_RELOAD_SECURITY_POLICY system procedure    
SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY system procedure    
SYSCS_UTIL.SYSCS_SET_RUNTIMESTATISTICS system procedure    
SYSCS_UTIL.SYSCS_SET_STATISTICS_TIMING system procedure    
SYSCS_UTIL.SYSCS_SET_USER_ACCESS system procedure    
SYSCS_DIAG diagnostic tables and functions    
Data types    
Built-In type overview    
Numeric types    
Data type assignments and comparison, sorting, and ordering    
BIGINT data type    
BLOB data type    
CHAR data type    
CHAR FOR BIT DATA data type    
CLOB data type    
DATE data type    
DECIMAL data type    
DOUBLE data type    
DOUBLE PRECISION data type    
FLOAT data type    
INTEGER data type    
LONG VARCHAR data type    
LONG VARCHAR FOR BIT DATA data type    
NUMERIC data type    
REAL data type    
SMALLINT data type    
TIME data type    
TIMESTAMP data type    
VARCHAR data type    
VARCHAR FOR BIT DATA data type    
XML data type    
SQL reserved words    
Derby support for SQL-92 features    
Derby system tables    
SYSALIASES system table    
SYSCHECKS system table    
SYSCOLPERMS system table    
SYSCOLUMNS system table    
SYSCONGLOMERATES system table    
SYSCONSTRAINTS system table    
SYSDEPENDS system table    
SYSFILES system table    
SYSFOREIGNKEYS system table    
SYSKEYS system table    
SYSROUTINEPERMS system table    
SYSSCHEMAS system table    
SYSSTATISTICS system table    
SYSSTATEMENTS system table    
SYSTABLEPERMS system table    
SYSTABLES system table    
SYSTRIGGERS system table    
SYSVIEWS system table    
Derby exception messages and SQL states    
SQL error messages and exceptions    
JDBC reference    
Core JDBC java.sql classes, interfaces, and methods    
java.sql.Driver interface    
java.sql.Driver.getPropertyInfo method    
java.sql.DriverManager.getConnection method    
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.Connection interface    
java.sql.Connection.setTransactionIsolation method    
java.sql.Connection.setReadOnly method    
java.sql.Connection.isReadOnly method    
Connection functionality not supported    
java.sql.DatabaseMetaData interface    
DatabaseMetaData result sets    
java.sql.DatabaseMetaData.getProcedureColumns method    
Parameters to getProcedureColumns    
Columns in the ResultSet returned by getProcedureColumns    
java.sql.DatabaseMetaData.getBestRowIdentifier method    
java.sql.Statement interface    
ResultSet objects    
java.sql.CallableStatement interface    
CallableStatements and OUT Parameters    
CallableStatements and INOUT Parameters    
java.sql.SQLException class    
java.sql.PreparedStatement interface    
Prepared statements and streaming columns    
java.sql.ResultSet interface    
ResultSets and streaming columns    
java.sql.ResultSetMetaData interface    
java.sql.SQLWarning class    
java.sql.SQLXML interface    
Mapping of java.sql.Types to SQL types    
Mapping of java.sql.Blob and java.sql.Clob interfaces    
JDBC 2.0 features    
java.sql.CallableStatement interface: supported JDBC 2.0 methods    
java.sql.Connection interface: supported JDBC 2.0 methods    
java.sql.DatabaseMetaData interface: supported JDBC 2.0 methods    
java.sql.PreparedStatement interface: supported JDBC 2.0 methods    
java.sql.ResultSet interface: supported JDBC 2.0 methods    
java.sql.ResultSetMetaData interface: supported JDBC 2.0 methods    
java.sql.Statement interface: supported JDBC 2.0 methods    
java.sql.BatchUpdateException class    
JDBC Package for Connected Device Configuration/Foundation Profile (JSR169)    
JDBC 3.0 features    
java.sql.Connection interface: supported JDBC 3.0 methods    
java.sql.DatabaseMetaData interface: supported JDBC 3.0 methods    
java.sql.ParameterMetaData interface: supported JDBC 3.0 methods    
java.sql.PreparedStatement interface: supported JDBC 3.0 methods    
java.sql.Savepoint interface    
java.sql.Statement interface: supported JDBC 3.0 methods    
JDBC 4.0-only features    
Refined subclasses of SQLException    
java.sql.Connection interface: JDBC 4.0 features    
java.sql.DatabaseMetaData interface: JDBC 4.0 features    
java.sql.Statement interface: JDBC 4.0 features    
javax.sql.DataSource interface: JDBC 4.0 features    
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 attribute    
collation=collation attribute    
create=true attribute    
createFrom=path attribute    
databaseName=nameofDatabase attribute    
dataEncryption=true attribute    
encryptionKey=key attribute    
encryptionProvider=providerName attribute    
encryptionAlgorithm=algorithm attribute    
failover=true attribute    
logDevice=logDirectoryPath attribute    
newEncryptionKey=key attribute    
newBootPassword=newPassword attribute    
password=userPassword attribute    
restoreFrom=path attribute    
rollForwardRecoveryFrom=path attribute    
securityMechanism=value attribute    
shutdown=true attribute    
slaveHost=hostname attribute    
slavePort=portValue attribute    
startMaster=true attribute    
startSlave=true attribute    
stopMaster=true attribute    
stopSlave=true attribute    
territory=ll_CC attribute    
traceDirectory=path attribute    
traceFile=path attribute    
traceFileAppend=true attribute    
traceLevel=value attribute    
upgrade=true attribute    
user=userName attribute    
ssl=sslMode attribute    
Creating a connection without specifying attributes    
J2EE Compliance: Java Transaction API and javax.sql Interfaces    
The JTA API    
Notes on Product Behavior    
javax.sql: JDBC Interfaces    
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    


Java DB Reference Manual
Apache Software FoundationJava DB Reference ManualApache Derby
Copyright
Copyright 2004-2008 The Apache Software Foundation
Copyright 2008 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A.
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.
Related information
License
The Apache License, Version 2.0
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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.
Relationship between Java(TM) DB and Derby
Java(TM) DB is a relational database management system that is based on the Java programming language and SQL. Java DB is a commercial release of the Apache Software Foundation's (ASF) open source relational database project. The Apache project is called Derby.
The Java DB product includes Derby without any modification whatsoever to the underlying source code.
Technical support is available for purchase for the Java DB product through Sun.
Because Java DB and Derby have the same functionality, the Java DB documentation refers to the core functionality as Derby.
Java DB Version 10.4 is based on the Derby Version 10.4 release. References to "Derby" in the Java DB documentation refer to the Version 10.4 release of Apache Derby.
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 Java DB.
Purpose of this document
This book, the Java DB 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 Java DB 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 Interfaces
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 expressions.
 
Comments can be either single- or multiline as per the SQL-92 standard. Singleline comments start with two dashes (--) and end with the newline character. Multiline comments are bracketed and start with forward slash star (/*), and end with star forward slash (*/). Note that bracketed comments may be nested. Any text between the starting and ending comment character sequence is ignored.
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 Java DB 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 Java DB 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 a column from 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 [ COLUMN ] column-name [ CASCADE | RESTRICT ] 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 DefaultConstantExpression ]
For details on DefaultConstantExpression, see Column default.
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 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 columns
ALTER TABLE DROP COLUMN allows you to drop a column from a table.
The keyword COLUMN is optional.
The keywords CASCADE and RESTRICT are also optional. If you specify neither CASCADE nor RESTRICT, the default is CASCADE.
If you specify RESTRICT, then the column drop will be rejected if it would cause a dependent schema object to become invalid.
If you specify CASCADE, then the column drop should additionally drop other schema objects which have become invalid.
The schema objects which can cause a DROP COLUMN RESTRICT to be rejected include: views, triggers, primary key constraints, foreign key constraints, unique key constraints, check constraints, and column privileges. If one of these types of objects depends on the column being dropped, DROP COLUMN RESTRICT will reject the statement.
You may not drop the last (only) column in a table.
DROP COLUMN is not allowed if sqlAuthorization is true (see DERBY-1909).
CASCADE/RESTRICT doesn't consider whether the column being dropped is used in any indexes. When a column is dropped, it is removed from any indexes which contain it. If that column was the only column in the index, the entire index is dropped.
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 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 Java DB.
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 the city_id column if there are no dependent objects: ALTER TABLE Cities DROP COLUMN city_id RESTRICT; -- Drop the city_id column, also dropping all dependent objects: ALTER TABLE Cities DROP COLUMN city_id CASCADE; -- 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.
CALL (PROCEDURE) statement
The CALL (PROCEDURE) statement is used to call procedures. A call to a procedure does not return any value.
Syntax
CALL procedure-Name ( [ expression [, expression]* ] )
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'; CALL SALES.TOTAL_REVENUE(?,?,?);
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
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.
ReturnDataType
TableType | DataType
The syntax of DataType is described in Data types.
TableType
This is the return type of a table function. Currently, only Derby-style table functions are supported. They are functions which return JDBC ResultSets. For more information, see "Programming Derby-style table functions" in the Java DB Developer's Guide.
At run-time, as values are read out of the user-supplied ResultSet, Derby coerces those values to the data types declared in the CREATE FUNCTION statement. This affects values typed as CHAR, VARCHAR, LONG VARCHAR, CHAR FOR BIT DATA, VARCHAR FOR BIT DATA, LONG VARCHAR FOR BIT DATA, and DECIMAL/NUMERIC. Values which are too long are truncated to the maximum length declared in the CREATE FUNCTION statement. In addition, if a String value is returned in the ResultSet for a column of CHAR type and the String is shorter than the declared length of the CHAR column, Derby pads the end of the String with blanks in order to stretch it out to the declared length.
ColumnElement
The syntax of DataType is described in Data types.
Note: XML is not allowed as the type of a column in the dataset returned by a table function.
FunctionElement
{ | LANGUAGE { JAVA } | EXTERNAL NAME string | PARAMETER STYLE ParameterStyle | { 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.
ParameterStyle
JAVA | DERBY_JDBC_RESULT_SET
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 can be 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.
The PARAMETER STYLE is DERBY_JDBC_RESULT_SET if and only if this is a Derby-style table function, that is, a function which returns TableType and which is mapped to a method which returns a JDBC ResultSet. Otherwise, the PARAMETER STYLE must be JAVA.
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 Java DB). 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. Adding a PRIMARY KEY or UNIQUE constraint when an existing UNIQUE index exists on the same set of columns will result in two physical indexes on the table for the same set of columns. One index is the original UNIQUE index and one is the backing index for the new constraint.
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.
The procedure owner and the database owner automatically gain the EXECUTE privilege on the procedure, and are able to grant this privilege to other users. The EXECUTE privileges cannot be revoked from the procedure and database owners.
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: Data-types such as BLOB, CLOB, LONG VARCHAR, LONG VARCHAR FOR BIT DATA, and XML 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 AUTHORIZATION user-name ] | [ schemaName ] | [ AUTHORIZATION user-name ] }
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.
The CREATE SCHEMA statement is subject to access control when the derby.database.sqlAuthorization property is set to true for the database or system. Only the database owner can create a schema with a name different from the current user name, and only the the database owner can specify
AUTHORIZATION user-name
with a user name other than the current user name. See Tuning Java DB for information about the derby.database.sqlAuthorization property.
CREATE SCHEMA examples
To create a schema for airline-related tables and give the authorization ID anita access to all of the objects that use the schema, use the following syntax:
CREATE SCHEMA FLIGHTS AUTHORIZATION anita
To create a schema employee-related tables, use the following syntax:
CREATE SCHEMA EMP
To create a schema that uses the same name as the authorization ID takumi, use the following syntax:
CREATE SCHEMA AUTHORIZATION takumi
To create a table called availability in the EMP and FLIGHTS schemas, use the following syntax:
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).
The table owner and the database owner automatically gain the following privileges on the table and are able to grant these privileges to other users:
 
INSERT
 
SELECT
 
REFERENCES
 
TRIGGER
 
UPDATE
These privileges cannot be revoked from the table and database owners.
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.
Syntax
There are two different variants of the CREATE TABLE statement, depending on whether you are specifying the column definitions and constraints, or whether you are modeling the columns after the results of a query expression:
CREATE TABLE table-Name { ( {column-definition | Table-level constraint} [ , {column-definition | Table-level constraint} ] * ) | [ ( column-name [ , column-name ] * ) ] AS query-expression WITH NO DATA }
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.
CREATE TABLE ... AS ...
With the alternate form of the CREATE TABLE statement, the column names and/or the column data types can be specified by providing a query. The columns in the query result are used as a model for creating the columns in the new table.
If no column names are specified for the new table, then all the columns in the result of the query expression are used to create same-named columns in the new table, of the corresponding data type(s). If one or more column names are specified for the new table, then the same number of columns must be present in the result of the query expression; the data types of those columns are used for the corresponding columns of the new table.
The WITH NO DATA clause specifies that the data rows which result from evaluating the query expression are not used; only the names and data types of the columns in the query result are used. The WITH NO DATA clause must be specified; in a future release, Derby may be modified to allow the WITH DATA clause to be provided, which would indicate that the results of the query expression should be inserted into the newly-created table. In the current release, however, only the WITH NO DATA form of the statement is accepted.
Example
-- create a new table using all the columns and data types -- from an existing table: CREATE TABLE T3 AS SELECT * FROM T1 WITH NO DATA; -- create a new table, providing new names for the columns, but -- using the data types from the columns of an existing table: CREATE TABLE T3 (A,B,C,D,E) AS SELECT * FROM T1 WITH NO DATA; -- create a new table, providing new names for the columns, -- using the data types from the indicated columns of an existing table: CREATE TABLE T3 (A,B,C) AS SELECT V,DP,I FROM T1 WITH NO DATA; -- This example shows that the columns in the result of the -- query expression may be unnamed expressions, but their data -- types can still be used to provide the data types for the -- corresponding named columns in the newly-created table: CREATE TABLE T3 (X,Y) AS SELECT 2*I,2.0*F FROM T1 WITH NO DATA;
column-definition:
Simple-column-NameDataType [ Column-level-constraint ]* [ [ WITH ] DEFAULT DefaultConstantExpression |generated-column-spec ] [ Column-level-constraint ]*
The syntax of DataType is described in Data types.
Column default
For the definition of a default value, a DefaultConstantExpression is an expression that does not refer to any table. It can include constants, date-time special registers, current schemas, users, and null:
DefaultConstantExpression: NULL | CURRENT { SCHEMA | SQLID } | USER | CURRENT_USER | SESSION_USER | DATE | TIME | TIMESTAMP | CURRENT DATE | CURRENT_DATE | CURRENT TIME | CURRENT_TIME | CURRENT TIMESTAMP | CURRENT_TIMESTAMP | literal
For details about Derby literal values, see Data types.
The values in a DefaultConstantExpression must be compatible in type with the column, but a DefaultConstantExpression has the following additional type restrictions:
 
If you specify USER, CURRENT_USER or SESSION_USER, the column must be a character column whose length is at least 8.
 
If you specify CURRENT SCHEMA or CURRENT SQLID, the column must be a character column whose length is at least 128.
 
If the column is an integer type, the default value must be an integer literal.
 
If the column is a decimal type, the scale and precision of the default value must be within those of the column.
generated-column-spec:
[ GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY [ ( START WITH IntegerConstant [ ,INCREMENT BY IntegerConstant] ) ] ] ]
Identity column attributes
A table can have at most one identity column.
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 START WITH and INCREMENT BY. And if you specify a negative number for the increment value, Derbydecrements the value with each insert. If this value is positive, Derby increments the value with each insert. A value of 0 raises a statement exception.
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.
Table 1. 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
2147483647 (java.lang.Integer.MAX_VALUE)
-2147483648 (java.lang.Integer.MIN_VALUE)
BIGINT
9223372036854775807 (java.lang.Long.MAX_VALUE)
-9223372036854775808 (java.lang.Long.MIN_VALUE)
Automatically generated values in an identity column are unique. Use a primary key or unique constraint on a column to guarantee uniqueness. Creating an identity column does not create an index on the column.
The IDENTITY_VAL_LOCAL function is a non-deterministic function that returns the most recently assigned value for an identity column. See IDENTITY_VAL_LOCAL function for more information.
Note: Specify the schema, table, and column name using the same case as those names are stored in the system tables--that is, all upper case unless you used delimited identifiers when creating those database objects.
Derby keeps track of the last increment value for a column in a cache. It also stores the value of what the next increment value will be for the column on disk in the AUTOINCREMENTVALUE column of the SYS.SYSCOLUMNS system table. Rolling back a transaction does not undo this value, and thus rolled-back transactions can leave "gaps" in the values automatically inserted into an identity column. Derby behaves this way to avoid locking a row in SYS.SYSCOLUMNS for the duration of a transaction and keeping concurrency high.
When an insert happens within a triggered-SQL-statement, the value inserted by the triggered-SQL-statement into the identity column is available from ConnectionInfo only within the trigger code. The trigger code is also able to see the value inserted by the statement that caused the trigger to fire. However, the statement that caused the trigger to fire is not able to see the value inserted by the triggered-SQL-statement into the identity column. Likewise, triggers can be nested (or recursive). An SQL statement can cause trigger T1 to fire. T1 in turn executes an SQL statement that causes trigger T2 to fire. If both T1 and T2 insert rows into a table that cause Derby to insert into an identity column, trigger T1 cannot see the value caused by T2's insert, but T2 can see the value caused by T1's insert. Each nesting level can see increment values generated by itself and previous nesting levels, all the way to the top-level SQL statement that initiated the recursive triggers. You can only have 16 levels of trigger recursion.
Example
create table greetings (i int generated by default as identity (START WITH 2, INCREMENT BY 1), 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');
CREATE TRIGGER statement
A trigger defines a set of actions that are executed when a database event occurs on a specified table. A database event is a delete, insert, or update operation. For example, if you define a trigger for a delete on a particular table, the trigger's action occurs whenever someone deletes a row or rows from the table.
Along with constraints, triggers can help enforce data integrity rules with actions such as cascading deletes or updates. Triggers can also perform a variety of functions such as issuing alerts, updating other tables, sending e-mail, and other useful actions.
You can define any number of triggers for a single table, including multiple triggers on the same table for the same event.
You can create a trigger in any schema where you are the schema owner. To create a trigger on a table that you do not own, you must be granted the TRIGGER privilege on that table. The database owner can also create triggers on any table in any schema.
The trigger does not need to reside in the same schema as the table on which the trigger is defined.
If a qualified trigger name is specified, the schema name cannot begin with SYS.
Syntax
CREATE TRIGGER TriggerName { AFTER | NO CASCADE BEFORE } { INSERT | DELETE | UPDATE [ OF column-Name [, column-Name]* ] } ON table-Name [ ReferencingClause ] [ FOR EACH { ROW | STATEMENT } ] [ MODE DB2SQL ] Triggered-SQL-statement
Before or after: when triggers fire
Triggers are defined as either Before or After triggers.
 
Before triggers fire before the statement's changes are applied and before any constraints have been applied. Before triggers can be either row or statement triggers (see Statement versus row triggers).
 
After triggers fire after all constraints have been satisfied and after the changes have been applied to the target table. After triggers can be either row or statement triggers (see Statement versus row triggers).
Insert, delete, or update: what causes the trigger to fire
A trigger is fired by one of the following database events, depending on how you define it (see Syntax above):
 
INSERT
 
UPDATE
 
DELETE
You can define any number of triggers for a given event on a given table. For update, you can specify columns.
Referencing old and new values: the referencing clause
Many triggered-SQL-statements need to refer to data that is currently being changed by the database event that caused them to fire. The triggered-SQL-statement might need to refer to the new (post-change or "after") values.
Derby provides you with a number of ways to refer to data that is currently being changed by the database event that caused the trigger to fire. Changed data can be referred to in the triggered-SQL-statement using transition variables or transition tables. The referencing clause allows you to provide a correlation name or alias for these transition variables by specifying OLD/NEW AS correlation-Name .
For example, if you add the following clause to the trigger definition:
REFERENCING OLD AS DELETEDROW
you can then refer to this correlation name in the triggered-SQL-statement:
DELETE FROM HotelAvailability WHERE hotel_id = DELETEDROW.hotel_id
The OLD and NEW transition variables map to a java.sql.ResultSet with a single row.
Note: Only row triggers (see Statement versus row triggers) can use the transition variables. INSERT row triggers cannot reference an OLD row. DELETE row triggers cannot reference a NEW row.
For statement triggers, transition tables serve as a table identifier for the triggered-SQL-statement or the trigger qualification. The referencing clause allows you to provide a correlation name or alias for these transition tables by specifying OLD_TABLE/NEW_TABLE AS correlation-Name
For example:
REFERENCING OLD_TABLE AS DeletedHotels
allows you to use that new identifier (DeletedHotels) in the triggered-SQL-statement:
DELETE FROM HotelAvailability WHERE hotel_id IN (SELECT hotel_id FROM DeletedHotels)
The old and new transition tables map to a java.sql.ResultSet with cardinality equivalent to the number of rows affected by the triggering event.
Note: Only statement triggers (see Statement versus row triggers) can use the transition tables. INSERT statement triggers cannot reference an OLD table. DELETE statement triggers cannot reference a NEW table.
The referencing clause can designate only one new correlation or identifier and only one old correlation or identifier. Row triggers cannot designate an identifier for a transition table and statement triggers cannot designate a correlation for transition variables.
Statement versus row triggers
You have the option to specify whether a trigger is a statement trigger or a row trigger. If it is not specified in the CREATE TRIGGER statement via FOR EACH clause, then the trigger is a statement trigger by default.
 
statement triggers
A statement trigger fires once per triggering event and regardless of whether any rows are modified by the insert, update, or delete event.
 
row triggers
A row trigger fires once for each row affected by the triggering event. If no rows are affected, the trigger does not fire.
Note: An update that sets a column value to the value that it originally contained (for example, UPDATE T SET C = C) causes a row trigger to fire, even though the value of the column is the same as it was prior to the triggering event.
Triggered-SQL-statement
The action defined by the trigger is called the triggered-SQL-statement (in Syntax above, see the last line). It has the following limitations:
 
It must not contain any dynamic parameters (?).
 
It must not create, alter, or drop the table upon which the trigger is defined.
 
It must not add an index to or remove an index from the table on which the trigger is defined.
 
It must not add a trigger to or drop a trigger from the table upon which the trigger is defined.
 
It must not commit or roll back the current transaction or change the isolation level.
 
Before triggers cannot have INSERT, UPDATE or DELETE statements as their action.
 
Before triggers cannot call procedures that modify SQL data as their action.
The triggered-SQL-statement can reference database objects other than the table upon which the trigger is declared. If any of these database objects is dropped, the trigger is invalidated. If the trigger cannot be successfully recompiled upon the next execution, the invocation throws an exception and the statement that caused it to fire will be rolled back.
For more information on triggered-SQL-statements, see the Java DB Developer's Guide.
Order of execution
When a database event occurs that fires a trigger, Derby performs actions in this order:
 
It fires No Cascade Before triggers.
 
It performs constraint checking (primary key, unique key, foreign key, check).
 
It performs the insert, update, or delete.
 
It fires After triggers.
When multiple triggers are defined for the same database event for the same table for the same trigger time (before or after), triggers are fired in the order in which they were created.
-- Statements and triggers: CREATE TRIGGER t1 NO CASCADE BEFORE UPDATE ON x FOR EACH ROW MODE DB2SQL values app.notifyEmail('Jerry', 'Table x is about to be updated'); CREATE TRIGGER FLIGHTSDELETE AFTER DELETE ON FLIGHTS REFERENCING OLD_TABLE AS DELETEDFLIGHTS FOR EACH STATEMENT DELETE FROM FLIGHTAVAILABILITY WHERE FLIGHT_ID IN (SELECT FLIGHT_ID FROM DELETEDFLIGHTS); CREATE TRIGGER FLIGHTSDELETE3 AFTER DELETE ON FLIGHTS REFERENCING OLD AS OLD FOR EACH ROW DELETE FROM FLIGHTAVAILABILITY WHERE FLIGHT_ID = OLD.FLIGHT_ID;
Note: You can find more examples in the Java DB Developer's Guide.
Trigger recursion
The maximum trigger recursion depth is 16.
Related information
Special system functions that return information about the current time or current user are evaluated when the trigger fires, not when it is created. Such functions include:
ReferencingClause:
REFERENCING { { OLD | NEW } [ ROW ] [ AS ] correlation-Name [ { OLD | NEW } [ ROW ] [ AS ] correlation-Name ] | { OLD TABLE | NEW TABLE } [ AS ] Identifier [ { OLD TABLE | NEW TABLE } [AS] Identifier ] | { OLD_TABLE | NEW_TABLE } [ AS ] Identifier [ { OLD_TABLE | NEW_TABLE } [AS] Identifier ] }
Note: The OLD_TABLE | NEW_TABLE syntax is deprecated since it is not SQL compliant and is intended for backward compatibility and DB2 compatibility.
CREATE VIEW statement
Views are virtual tables formed by a query. A view is a dictionary object that you can use until you drop it. Views are not updatable.
If a qualified view name is specified, the schema name cannot begin with SYS.
The view owner automatically gains the SELECT privilege on the view. The SELECT privilege cannot be revoked from the view owner. The database owner automatically gains the SELECT privilege on the view and is able to grant this privilege to other users. The SELECT privilege cannot be revoked from the database owner.
The view owner can only grant the SELECT privilege to other users if the view owner also owns the underlying objects.
If the underlying objects that the view references are not owned by the view owner, the view owner must be granted the appropriate privileges. For example, if the authorization ID user2 attempts to create a view called user2.v2 that references table user1.t1 and function user1.f_abs(), then user2 must have the SELECT privilege on table user1.t1 and the EXECUTE privilege on function user1.f_abs().
The privilege to grant the SELECT privilege cannot be revoked. If a required privilege on one of the underlying objects that the view references is revoked, then the view is dropped.
Syntax
A view definition can contain an optional view column list to explicitly name the columns in the view. If there is no column list, the view inherits the column names from the underlying query. All columns in a view must be uniquely named.
CREATE VIEW SAMP.V1 (COL_SUM, COL_DIFF) AS SELECT COMM + BONUS, COMM - BONUS FROM SAMP.EMPLOYEE; CREATE VIEW SAMP.VEMP_RES (RESUME) AS VALUES 'Delores M. Quintana', 'Heather A. Nicholls', 'Bruce Adamson'; CREATE VIEW SAMP.PROJ_COMBO (PROJNO, PRENDATE, PRSTAFF, MAJPROJ) AS SELECT PROJNO, PRENDATE, PRSTAFF, MAJPROJ FROM SAMP.PROJECT UNION ALL SELECT PROJNO, EMSTDATE, EMPTIME, EMPNO FROM SAMP.EMP_ACT WHERE EMPNO IS NOT NULL;
Statement dependency system
View definitions are dependent on the tables and views referenced within the view definition. DML (data manipulation language) statements that contain view references depend on those views, as well as the objects in the view definitions that the views are dependent on. Statements that reference the view depend on indexes the view uses; which index a view uses can change from statement to statement based on how the query is optimized. For example, given:
CREATE TABLE T1 (C1 DOUBLE PRECISION); CREATE FUNCTION SIN (DATA DOUBLE) RETURNS DOUBLE EXTERNAL NAME 'java.lang.Math.sin' LANGUAGE JAVA PARAMETER STYLE JAVA; CREATE VIEW V1 (C1) AS SELECT SIN(C1) FROM T1;
the following SELECT:
SELECT * FROM V1
is dependent on view V1, table T1, and external scalar function SIN.
DECLARE GLOBAL TEMPORARY TABLE statement
The DECLARE GLOBAL TEMPORARY TABLE statement defines a temporary table for the current connection.
These tables do not reside in the system catalogs and are not persistent. Temporary tables exist only during the connection that declared them and cannot be referenced outside of that connection. When the connection closes, the rows of the table are deleted, and the in-memory description of the temporary table is dropped.
Temporary tables are useful when:
 
The table structure is not known before using an application.
 
Other users do not need the same table structure.
 
Data in the temporary table is needed while using the application.
 
The table can be declared and dropped without holding the locks on the system catalog.
Syntax
DECLARE GLOBAL TEMPORARY TABLE table-Name { column-definition [ , column-definition ] * } [ ON COMMIT {DELETE | PRESERVE} ROWS ] NOT LOGGED [ON ROLLBACK DELETE ROWS]
table-Name
Names the temporary table. If a schema-Name other than SESSION is specified, an error will occur (SQLSTATE 428EK). If the schema-Name is not specified, SESSION is assigned. Multiple connections can define declared global temporary tables with the same name because each connection has its own unique table descriptor for it.
Using SESSION as the schema name of a physical table will not cause an error, but is discouraged. The SESSION schema name should be reserved for the temporary table schema.
column-definition
See column-definition for CREATE TABLE for more information on column-definition. DECLARE GLOBAL TEMPORARY TABLE does not allow generated-column-spec in the column-definition.
Data type
Supported data types are:
 
BIGINT
 
CHAR
 
DATE
 
DECIMAL
 
DOUBLE
 
DOUBLE PRECISION
 
FLOAT
 
INTEGER
 
NUMERIC
 
REAL
 
SMALLINT
 
TIME
 
TIMESTAMP
 
VARCHAR
ON COMMIT
Specifies the action taken on the global temporary table when a COMMIT operation is performed.
DELETE ROWS
All rows of the table will be deleted if no hold-able cursor is open on the table. This is the default value for ON COMMIT. If you specify ON ROLLBACK DELETE ROWS, this will delete all the rows in the table only if the temporary table was used. ON COMMIT DELETE ROWS will delete the rows in the table even if the table was not used (if the table does not have hold-able cursors open on it).
PRESERVE ROWS
The rows of the table will be preserved.
NOT LOGGED
Specifies the action taken on the global temporary table when a rollback operation is performed. When a ROLLBACK (or ROLLBACK TO SAVEPOINT) operation is performed, if the table was created in the unit of work (or savepoint), the table will be dropped. If the table was dropped in the unit of work (or savepoint), the table will be restored with no rows.
ON ROLLBACK DELETE ROWS
This is the default value for NOT LOGGED. NOT LOGGED [ON ROLLBACK DELETE ROWS ]] specifies the action that is to be taken on the global temporary table when a ROLLBACK or (ROLLBACK TO SAVEPOINT) operation is performed. If the table data has been changed, all the rows will be deleted.
Examples
set schema myapp; create table t1(c11 int, c12 date); declare global temporary table SESSION.t1(c11 int) not logged; -- The SESSION qualification is redundant here because temporary -- tables can only exist in the SESSION schema. declare global temporary table t2(c21 int) not logged; -- The temporary table is not qualified here with SESSION because temporary -- tables can only exist in the SESSION schema. insert into SESSION.t1 values (1); -- SESSION qualification is mandatory here if you want to use -- the temporary table, because the current schema is "myapp." select * from t1; -- This select statement is referencing the "myapp.t1" physical -- table since the table was not qualified by SESSION.
Note: Temporary tables can be declared only in the SESSION schema. You should never declare a physical schema with the SESSION name.
The following is a list of DB2 UDB DECLARE GLOBAL TEMPORARY TABLE functions that are not supported by Derby:
 
IDENTITY column-options
 
IDENTITY attribute in copy-options
 
AS (fullselect) DEFINITION ONLY
 
NOT LOGGED ON ROLLBACK PRESERVE ROWS
 
IN tablespace-name
 
PARTITIONING KEY
 
WITH REPLACE
Restrictions on Declared Global Temporary Tables
Derby does not support the following features on temporary tables. Some of these features are specific to temporary tables and some are specific to Derby.
Temporary tables cannot be specified in the following statements:
 
ALTER TABLE
 
CREATE INDEX
 
CREATE SYNONYM
 
CREATE TRIGGER
 
CREATE VIEW
 
GRANT
 
LOCK TABLE
 
RENAME
 
REVOKE
You cannot use the following features with temporary tables:
 
Synonyms, triggers and views on SESSION schema tables (including physical tables and temporary tables)
 
Caching statements that reference SESSION schema tables and views
 
Temporary tables cannot be specified in referential constraints and primary keys
 
Temporary tables cannot be referenced in a triggered-SQL-statement
 
Check constraints on columns
 
Generated-column-spec
 
Importing into temporary tables
If a statement that performs an insert, update, or delete to the temporary table encounters an error, all the rows of the temporary table are deleted.
The following data types cannot be used with Declared Global Temporary Tables:
 
BLOB
 
CHAR FOR BIT DATA
 
CLOB
 
LONG VARCHAR
 
LONG VARCHAR FOR BIT DATA
 
VARCHAR FOR BIT DATA
 
XML
DELETE statement
Syntax
{ DELETE FROM table-Name [[AS] correlation-Name] [WHERE clause] | DELETE FROM table-Name WHERE CURRENT OF }
The first syntactical form, called a searched delete, removes all rows identified by the table name and WHERE clause.
The second syntactical form, called a positioned delete, deletes the current row of an open, updatable cursor. For more information about updatable cursors, see SELECT statement.
Examples
DELETE FROM SAMP.IN_TRAY stmt.executeUpdate("DELETE FROM SAMP.IN_TRAY WHERE CURRENT OF " + resultSet.getCursorName());
Statement dependency system
A searched delete statement depends on the table being updated, all of its conglomerates (units of storage such as heaps or indexes), and any other table named in the WHERE clause. A CREATE or DROP INDEX statement for the target table of a prepared searched delete statement invalidates the prepared searched delete statement.
The positioned delete statement depends on the cursor and any tables the cursor references. You can compile a positioned delete even if the cursor has not been opened yet. However, removing the open cursor with the JDBC close method invalidates the positioned delete.
A CREATE or DROP INDEX statement for the target table of a prepared positioned delete invalidates the prepared positioned delete statement.
DROP statements
Use Drop statements with functions, indexes, procedures, schemas, synonyms, tables, triggers, and views.
DROP FUNCTION statement
Syntax
DROP FUNCTION function-name
Identifies the particular function to be dropped, and is valid only if there is exactly one function instance with the function-name in the schema. The identified function can have any number of parameters defined for it. If no function with the indicated name in the named or implied schema, an error (SQLSTATE 42704) will occur. An error will also occur if there is more than one specific instance of the function in the named or implied schema.
DROP INDEX statement
DROP INDEX removes the specified index.
Syntax
DROP INDEX index-Name
DROP INDEX OrigIndex DROP INDEX DestIndex
Statement dependency system
If there is an open cursor on the table from which the index is dropped, the DROP INDEX statement generates an error and does not drop the index. Otherwise, statements that depend on the index's table are invalidated.
DROP PROCEDURE statement
Syntax
DROP PROCEDURE procedure-Name
Identifies the particular procedure to be dropped, and is valid only if there is exactly one procedure instance with the procedure-name in the schema. The identified procedure can have any number of parameters defined for it. If no procedure with the indicated name in the named or implied schema, an error (SQLSTATE 42704) will occur. An error will also occur if there is more than one specific instance of the procedure in the named or implied schema.
DROP SCHEMA statement
The DROP SCHEMA statement drops a schema. The target schema must be empty for the drop to succeed.
Neither the APP schema (the default user schema) nor the SYS schema can be dropped.
Syntax
DROP SCHEMA schemaName RESTRICT
The RESTRICT keyword enforces the rule that no objects can be defined in the specified schema for the schema to be deleted from the database. The RESTRICT keyword is required
-- Drop the SAMP schema -- The SAMP schema may only be deleted from the database -- if no objects are defined in the SAMP schema. DROP SCHEMA SAMP RESTRICT
DROP SYNONYM statement
Drops the specified synonym from a table or view.
Syntax
DROP SYNONYM synonym-Name
DROP TABLE statement
DROP TABLE removes the specified table.
Syntax
DROP TABLE table-Name
Statement dependency system
Triggers, constraints (primary, unique, check and references from the table being dropped) and indexes on the table are silently dropped. The existence of an open cursor that references table being dropped cause the DROP TABLE statement to generate an error, and the table is not dropped.
Dropping a table invalidates statements that depend on the table. (Invalidating a statement causes it to be recompiled upon the next execution. See Interaction with the dependency system.)
DROP TRIGGER statement
DROP TRIGGER removes the specified trigger.
Syntax
DROP TRIGGER TriggerName
DROP TRIGGER TRIG1
Statement dependency system
When a table is dropped, all triggers on that table are automatically dropped. (You don't have to drop a table's triggers before dropping the table.)
DROP VIEW statement
Drops the specified view.
Syntax
DROP VIEW view-Name
DROP VIEW AnIdentifier
Statement dependency system
Any statements referencing the view are invalidated on a DROP VIEW statement. DROP VIEW is disallowed if there are any views or open cursors dependent on the view. The view must be dropped before any objects that it is dependent on can be dropped.
GRANT statement
Use the GRANT statement to give permissions to a specific user or all users to perform actions on database objects.
The following types of permissions can be granted:
 
Delete data from a specific table.
 
Insert data into a specific table.
 
Create a foreign key reference to the named table or to a subset of columns from a table.
 
Select data from a table, view, or a subset of columns in a table.
 
Create a trigger on a table.
 
Update data in a table or in a subset of columns in a table.
 
Run a specified function or procedure.
Before you issue a GRANT statement, check that the derby.database.sqlAuthorization property is set to true. The derby.database.sqlAuthorization property enables the SQL Authorization mode.
You can grant privileges to database objects that you are authorized to grant. See the CREATE statement for the database object that you want to grant privileges on for more information.
The syntax that you use for the GRANT statement depends on whether you are granting privileges to a table or to a routine.
Syntax for tables
GRANT privilege-type ON [TABLE] { table-Name | view-Name } TO grantees
Syntax for routines
GRANT EXECUTE ON { FUNCTION | PROCEDURE } routine-designator TO grantees
privilege-types
ALL PRIVILEGES | privilege-list
privilege-list
table-privilege {, table-privilege }*
table-privilege
DELETE | INSERT | REFERENCES [column list] | SELECT [column list] | TRIGGER | UPDATE [column list]
column list
( column-identifier {, column-identifier}* )
Use the ALL PRIVILEGES privilege type to grant all of the permissions to the user for the specified table. You can also grant one or more table privileges by specifying a privilege-list.
Use the DELETE privilege type to grant permission to delete rows from the specified table.
Use the INSERT privilege type to grant permission to insert rows into the specified table.
Use the REFERENCES privilege type to grant permission to create a foreign key reference to the specified table. If a column list is specified with the REFERENCES privilege, the permission is valid on only the foreign key reference to the specified columns.
Use the SELECT privilege type to grant permission to perform SELECT statements on a table or view. If a column list is specified with the SELECT privilege, the permission is valid on only those columns. If no column list is specified, then the privilege is valid on all of the columns in the table.
Use the TRIGGER privilege type to grant permission to create a trigger on the specified table.
Use the UPDATE privilege type to grant permission to use the UPDATE statement on the specified table. If a column list is specified, the permission applies only to the specified columns. To update a row using a statement that includes a WHERE clause, you must have SELECT permission on the columns in the row that you want to update.
grantees
{ authorization ID | PUBLIC } [,{ authorization ID | PUBLIC } ] *
You can grant privileges for specific users or for all users. Use the keyword PUBLIC to specify all users. When PUBLIC is specified, the privileges affect all current and future users. The privileges granted to PUBLIC and to individual users are independent privileges. For example, a SELECT privilege on table t is granted to both PUBLIC and to the authorization ID harry. The SELECT privilege is later revoked from the authorization ID harry, but Harry can access the table t through the PUBLIC privilege.
routine-designator
{ function-name | procedure-name }
Examples
To grant the SELECT privilege on table t to the authorization IDs maria and harry, use the following syntax:
GRANT SELECT ON TABLE t TO maria,harry
To grant the UPDATE and TRIGGER privileges on table t to the authorization IDs anita and zhi, use the following syntax:
GRANT UPDATE, TRIGGER ON TABLE t TO anita,zhi
To grant the SELECT privilege on table s.v to all users, use the following syntax:
GRANT SELECT ON TABLE s.v to PUBLIC
To grant the EXECUTE privilege on procedure p to the authorization ID george, use the following syntax:
GRANT EXECUTE ON PROCEDURE p TO george
INSERT statement
An INSERT statement creates a row or rows and stores them in the named table. The number of values assigned in an INSERT statement must be the same as the number of specified or implied columns.
Syntax
INSERT INTO table-Name [ (Simple-column-Name [ , Simple-column-Name]* ) ] Query
Query can be:
 
 
a VALUES list
 
a multiple-row VALUES expression
Single-row and multiple-row lists can include the keyword DEFAULT. Specifying DEFAULT for a column inserts the column's default value into the column. Another way to insert the default value into the column is to omit the column from the column list and only insert values into other columns in the table. For more information see VALUES Expression.
 
UNION expressions
For more information about Query, see Query.
INSERT INTO COUNTRIES VALUES ('Taiwan', 'TW', 'Asia') -- Insert a new department into the DEPARTMENT table, -- but do not assign a manager to the new department INSERT INTO DEPARTMENT (DEPTNO, DEPTNAME, ADMRDEPT) VALUES ('E31', 'ARCHITECTURE', 'E01') -- Insert two new departments using one statement -- into the DEPARTMENT table as in the previous example, -- but do not assign a manager to the new department. INSERT INTO DEPARTMENT (DEPTNO, DEPTNAME, ADMRDEPT) VALUES ('B11', 'PURCHASING', 'B01'), ('E41', 'DATABASE ADMINISTRATION', 'E01') -- Create a temporary table MA_EMP_ACT with the -- same columns as the EMP_ACT table. -- Load MA_EMP_ACT with the rows from the EMP_ACT -- table with a project number (PROJNO) -- starting with the letters 'MA'. CREATE TABLE MA_EMP_ACT ( EMPNO CHAR(6) NOT NULL, PROJNO CHAR(6) NOT NULL, ACTNO SMALLINT NOT NULL, EMPTIME DEC(5,2), EMSTDATE DATE, EMENDATE DATE ); INSERT INTO MA_EMP_ACT SELECT * FROM EMP_ACT WHERE SUBSTR(PROJNO, 1, 2) = 'MA'; -- Insert the DEFAULT value for the LOCATION column INSERT INTO DEPARTMENT VALUES ('E31', 'ARCHITECTURE', '00390', 'E01', DEFAULT)
Statement dependency system
The INSERT statement depends on the table being inserted into, all of the conglomerates (units of storage such as heaps or indexes) for that table, and any other table named in the statement. Any statement that creates or drops an index or a constraint for the target table of a prepared INSERT statement invalidates the prepared INSERT statement.
LOCK TABLE statement
The LOCK TABLE statement allows you to explicitly acquire a shared or exclusive table lock on the specified table. The table lock lasts until the end of the current transaction.
To lock a table, you must either be the database owner or the table owner.
Explicitly locking a table is useful to:
 
Avoid the overhead of multiple row locks on a table (in other words, user-initiated lock escalation)
 
Avoid deadlocks
You cannot lock system tables with this statement.
Syntax
LOCK TABLE table-Name IN { SHARE | EXCLUSIVE } MODE
After a table is locked in either mode, a transaction does not acquire any subsequent row-level locks on a table. For example, if a transaction locks the entire Flights table in share mode in order to read data, a particular statement might need to lock a particular row in exclusive mode in order to update the row. However, the previous table-level lock on the Flights table forces the exclusive lock to be table-level as well.
If the specified lock cannot be acquired because another connection already holds a lock on the table, a statement-level exception is raised (SQLState X0X02) after the deadlock timeout period.
Examples
To lock the entire Flights table in share mode to avoid a large number of row locks, use the following statement:
LOCK TABLE Flights IN SHARE MODE; SELECT * FROM Flights WHERE orig_airport > 'OOO';
You have a transaction with multiple UPDATE statements. Since each of the individual statements acquires only a few row-level locks, the transaction will not automatically upgrade the locks to a table-level lock. However, collectively the UPDATE statements acquire and release a large number of locks, which might result in deadlocks. For this type of transaction, you can acquire an exclusive table-level lock at the beginning of the transaction. For example:
LOCK TABLE FlightAvailability IN EXCLUSIVE MODE; UPDATE FlightAvailability SET economy_seats_taken = (economy_seats_taken + 2) WHERE flight_id = 'AA1265' AND flight_date = DATE('2004-03-31'); UPDATE FlightAvailability SET economy_seats_taken = (economy_seats_taken + 2) WHERE flight_id = 'AA1265' AND flight_date = DATE('2004-04-11'); UPDATE FlightAvailability SET economy_seats_taken = (economy_seats_taken + 2) WHERE flight_id = 'AA1265' AND flight_date = DATE('2004-04-12'); UPDATE FlightAvailability SET economy_seats_taken = (economy_seats_taken + 2) WHERE flight_id = 'AA1265' AND flight_date = DATE('2004-04-15');
If a transaction needs to look at a table before updating the table, acquire an exclusive lock before selecting to avoid deadlocks. For example:
LOCK TABLE Maps IN EXCLUSIVE MODE; SELECT MAX(map_id) + 1 FROM Maps; -- INSERT INTO Maps . . .
RENAME statements
Use the Rename statements with indexes, columns, and tables.
RENAME COLUMN statement
Use the RENAME COLUMN statement to rename a column in a table.
The RENAME COLUMN statement allows you to rename an existing column in an existing table in any schema (except the schema SYS).
To rename a column, you must either be the database owner or the table owner.
Other types of table alterations are possible; see ALTER TABLE statement for more information.
Examples
To rename the manager column in table employee to supervisor, use the following syntax:
RENAME COLUMN EMPLOYEE.MANAGER TO SUPERVISOR
You can combine ALTER TABLE and RENAME COLUMN to modify a column's data type. To change column c1 of table t to the new data type NEWTYPE:
ALTER TABLE t ADD COLUMN c1_newtype NEWTYPE UPDATE t SET c1_newtype = c1 ALTER TABLE t DROP COLUMN c1 RENAME COLUMN t.c1_newtype TO c1
Usage notes
Note: If there is a view, trigger, check constraint, or foreign key constraint that references the column, attempts to rename it will generate an error.
Note: The RENAME COLUMN statement is not allowed if there are any open cursors that reference the column that is being altered.
Note: If there is an index defined on the column, the column can still be renamed; the index is automatically updated to refer to the column by its new name
RENAME INDEX statement
This statement allows you to rename an index in the current schema. Users cannot rename indexes in the SYS schema.
Syntax
RENAME INDEX index-Name TO new-index-Name
RENAME INDEX DESTINDEX TO ARRIVALINDEX
Statement dependency system
RENAME INDEX is not allowed if there are any open cursors that reference the index being renamed.
RENAME TABLE statement
RENAME TABLE allows you to rename an existing table in any schema (except the schema SYS).
To rename a table, you must either be the database owner or the table owner.
Syntax
RENAME TABLE table-Name TO new-Table-Name
If there is a view or foreign key that references the table, attempts to rename it will generate an error. In addition, if there are any check constraints or triggers on the table, attempts to rename it will also generate an error.
RENAME TABLE SAMP.EMP_ACT TO EMPLOYEE_ACT
Also see ALTER TABLE statement for more information.
Statement dependency system
If there is an index defined on the table, the table can be renamed.
The RENAME TABLE statement is not allowed if there are any open cursors that reference the table that is being altered.
REVOKE statement
Use the REVOKE statement to remove permissions from a specific user or from all users to perform actions on database objects.
The following types of permissions can be revoked:
 
Delete data from a specific table.
 
Insert data into a specific table.
 
Create a foreign key reference to the named table or to a subset of columns from a table.
 
Select data from a table, view, or a subset of columns in a table.
 
Create a trigger on a table.
 
Update data in a table or in a subset of columns in a table.
 
Run a specified routine (function or procedure).
Before you issue a REVOKE statement, check that the derby.database.sqlAuthorization property is set to true. The derby.database.sqlAuthorization property enables the SQL Authorization mode.
You can revoke privileges from an object if you are the owner of the object or the database owner.
The syntax that you use for the REVOKE statement depends on whether you are revoking privileges to a table or to a routine.
Syntax for tables
REVOKE privilege-type ON [ TABLE ] { table-Name | view-Name } FROM grantees
Revoking a privilege without specifying a column list revokes the privilege for all of the columns in the table.
Syntax for routines
REVOKE EXECUTE ON { FUNCTION | PROCEDURE } routine-designator FROM grantees RESTRICT
You must use the RESTRICT clause on REVOKE statements for routines. The RESTRICT clause specifies that the EXECUTE privilege cannot be revoked if the specified routine is used in a view, trigger, or constraint, and the privilege is being revoked from the owner of the view, trigger, or constraint.
privilege-types
ALL PRIVILEGES | privilege-list
privilege-list
table-privilege {, table-privilege }*
table-privilege
DELETE | INSERT | REFERENCES [column list] | SELECT [column list] | TRIGGER | UPDATE [column list]
column list
( column-identifier {, column-identifier}* )
Use the ALL PRIVILEGES privilege type to revoke all of the permissions from the user for the specified table. You can also revoke one or more table privileges by specifying a privilege-list.
Use the DELETE privilege type to revoke permission to delete rows from the specified table.
Use the INSERT privilege type to revoke permission to insert rows into the specified table.
Use the REFERENCES privilege type to revoke permission to create a foreign key reference to the specified table. If a column list is specified with the REFERENCES privilege, the permission is revoked on only the foreign key reference to the specified columns.
Use the SELECT privilege type to revoke permission to perform SELECT statements on a table or view. If a column list is specified with the SELECT privilege, the permission is revoked on only those columns. If no column list is specified, then the privilege is valid on all of the columns in the table.
Use the TRIGGER privilege type to revoke permission to create a trigger on the specified table.
Use the UPDATE privilege type to revoke permission to use the UPDATE statement on the specified table. If a column list is specified, the permission is revoked only on the specified columns.
grantees
{ authorization ID | PUBLIC } [,{ authorization ID | PUBLIC } ] *
You can revoke the privileges from specific users or from all users. Use the keyword PUBLIC to specify all users. The privileges revoked from PUBLIC and from individual users are independent privileges. For example, a SELECT privilege on table t is granted to both PUBLIC and to the authorization ID harry. The SELECT privilege is later revoked from the authorization ID harry, but the authorization ID harry can access the table t through the PUBLIC privilege.
Restriction: You cannot revoke the privileges of the owner of an object.
routine-designator
{ qualified-name [ signature ] }
Cascading object dependencies
For views, triggers, and constraints, if the privilege on which the object depends on is revoked, the object is automatically dropped. Derby does not try to determine if you have other privileges that can replace the privileges that are being revoked. For more information, see "SQL standard authorization" in the Java DB Developer's Guide.
Limitations
The following limitations apply to the REVOKE statement:
Table-level privileges
All of the table-level privilege types for a specified grantee and table ID are stored in one row in the SYSTABLEPERMS system table. For example, when user2 is granted the SELECT and DELETE privileges on table user1.t1, a row is added to the SYSTABLEPERMS table. The GRANTEE field contains user2 and the TABLEID contains user1.t1. The SELECTPRIV and DELETEPRIV fields are set to Y. The remaining privilege type fields are set to N.
When a grantee creates an object that relies on one of the privilege types, the Derby engine tracks the dependency of the object on the specific row in the SYSTABLEPERMS table. For example, user2 creates the view v1 by using the statement SELECT * FROM user1.t1, the dependency manager tracks the dependency of view v1 on the row in SYSTABLEPERMS for GRANTEE(user2), TABLEID(user1.t1). The dependency manager knows only that the view is dependent on a privilege type in that specific row, but does not track exactly which privilege type the view is dependent on.
When a REVOKE statement for a table-level privilege is issued for a grantee and table ID, all of the objects that are dependent on the grantee and table ID are dropped. For example, if user1 revokes the DELETE privilege on table t1 from user2, the row in SYSTABLEPERMS for GRANTEE(user2), TABLEID(user1.t1) is modified by the REVOKE statement. The dependency manager sends a revoke invalidation message to the view user2.v1 and the view is dropped even though the view is not dependent on the DELETE privilege for GRANTEE(user2), TABLEID(user1.t1).
Column-level privileges
Only one type of privilege for a specified grantee and table ID are stored in one row in the SYSCOLPERMS system table. For example, when user2 is granted the SELECT privilege on table user1.t1 for columns c12 and c13, a row is added to the SYSCOLPERMS. The GRANTEE field contains user2, the TABLEID contains user1.t1, the TYPE field contains S, and the COLUMNS field contains c12, c13.
When a grantee creates an object that relies on the privilege type and the subset of columns in a table ID, the Derby engine tracks the dependency of the object on the specific row in the SYSCOLPERMS table. For example, user2 creates the view v1 by using the statement SELECT c11 FROM user1.t1, the dependency manager tracks the dependency of view v1 on the row in SYSCOLPERMS for GRANTEE(user2), TABLEID(user1.t1), TYPE(S). The dependency manager knows that the view is dependent on the SELECT privilege type, but does not track exactly which columns the view is dependent on.
When a REVOKE statement for a column-level privilege is issued for a grantee, table ID, and type, all of the objects that are dependent on the grantee, table ID, and type are dropped. For example, if user1 revokes the SELECT privilege on column c12 on table user1.t1 from user2, the row in SYSCOLPERMS for GRANTEE(user2), TABLEID(user1.t1), TYPE(S) is modified by the REVOKE statement. The dependency manager sends a revoke invalidation message to the view user2.v1 and the view is dropped even though the view is not dependent on the column c12 for GRANTEE(user2), TABLEID(user1.t1), TYPE(S).
Revoke examples
To revoke the SELECT privilege on table t from the authorization IDs maria and harry, use the following syntax:
REVOKE SELECT ON TABLE t FROM maria,harry
To revoke the UPDATE and TRIGGER privileges on table t from the authorization IDs anita and zhi, use the following syntax:
REVOKE UPDATE, TRIGGER ON TABLE t FROM anita,zhi
To revoke the SELECT privilege on table s.v from all users, use the following syntax:
REVOKE SELECT ON TABLE s.v FROM PUBLIC
To revoke the UPDATE privilege on columns c1 and c2 of table s.v from all users, use the following syntax:
REVOKE UPDATE (c1,c2) ON TABLE s.v FROM PUBLIC
To revoke the EXECUTE privilege on procedure p from the authorization ID george, use the following syntax:
REVOKE EXECUTE ON PROCEDURE p FROM george RESTRICT
SET statements
Use the Set statements with schemas and to set the current isolation level.
SET ISOLATION statement
The SET ISOLATION statement allows a user to change the isolation level for the user's connection. Valid levels are SERIALIZABLE, REPEATABLE READ, READ COMMITTED, and READ UNCOMMITTED.
Issuing this statement always commits the current transaction. The JDBC java.sql.Connection.setTransactionIsolation method behaves almost identically to this command, with one exception: if you are using the embedded driver, and if the call to java.sql.Connection.setTransactionIsolation does not actually change the isolation level (that is, if it sets the isolation level to its current value), the current transaction is not committed.
For information about isolation levels, see "Locking, concurrency, and isolation" in the Java DB Developer's Guide. For information about the JDBC java.sql.Connection.setTransactionIsolation method, see java.sql.Connection.setTransactionIsolation method.
Syntax
SET [ CURRENT ] ISOLATION [ = ] { UR | DIRTY READ | READ UNCOMMITTED CS | READ COMMITTED | CURSOR STABILITY RS | RR | REPEATABLE READ | SERIALIZABLE RESET }
set isolation serializable;
SET SCHEMA statement
The SET SCHEMA statement sets the default schema for a connection's session to the designated schema. The default schema is used as the target schema for all statements issued from the connection that do not explicitly specify a schema name.
The target schema must exist for the SET SCHEMA statement to succeed. If the schema doesn't exist an error is returned. See CREATE SCHEMA statement.
The SET SCHEMA statement is not transactional: If the SET SCHEMA statement is part of a transaction that is rolled back, the schema change remains in effect.
Syntax
SET [CURRENT] SCHEMA [=] { schemaName| USER | ? | '<string-constant>' } | SET CURRENT SQLID [=] { schemaName| USER | ? | '<string-constant>' }
schemaName is an identifier with a maximum length of 128. It is case insensitive unless enclosed in double quotes. (For example, SYS is equivalent to sYs, SYs, sys, etcetera.)
USER is the current user. If no current user is defined, the current schema defaults the APP schema. (If a user name was specified upon connection, the user's name is the default schema for the connection, if a schema with that name exists.)
? is a dynamic parameter specification that can be used in prepared statements. The SET SCHEMA statement can be prepared once and then executed with different schema values. The schema values are treated as string constants so they are case sensitive. For example, to designate the APP schema, use the string "APP" rather than "app".
-- the following are all equivalent and will work -- assuming a schema called HOTEL SET SCHEMA HOTEL SET SCHEMA hotel SET CURRENT SCHEMA hotel SET CURRENT SQLID hotel SET SCHEMA = hotel SET CURRENT SCHEMA = hotel SET CURRENT SQLID = hotel SET SCHEMA "HOTEL" -- quoted identifier SET SCHEMA 'HOTEL' -- quoted string--This example produces an error because --lower case hotel won't be found SET SCHEMA = 'hotel' --This example produces an error because SQLID is not --allowed without CURRENT SET SQLID hotel -- This sets the schema to the current user id SET CURRENT SCHEMA USER // Here's an example of using set schema in an Java program PreparedStatement ps = conn.PrepareStatement("set schema ?"); ps.setString(1,"HOTEL"); ps.executeUpdate(); ... do some work ps.setString(1,"APP"); ps.executeUpdate(); ps.setString(1,"app"); //error - string is case sensitive // no app will be found ps.setNull(1, Types.VARCHAR); //error - null is not allowed
SELECT statement
Syntax
Query [ORDER BY clause] [FOR UPDATE clause] WITH {RR|RS|CS|UR}
A SELECT statement consists of a query with an optional ORDER BY clause and an optional FOR UPDATE clause. The SELECT statement is so named because the typical first word of the query construct is SELECT. (Query includes the VALUES expression and UNION, INTERSECT, and EXCEPT expressions as well as SELECT expressions).
The ORDER BY clause guarantees the ordering of the ResultSet. The FOR UPDATE clause makes the result set's cursor updatable. The SELECT statement supports the FOR FETCH ONLY clause. The FOR FETCH ONLY clause is synonymous with the FOR READ ONLY clause.
You can set the isolation level in a SELECT statement using the WITH {RR|RS|CS|UR} syntax.
Example
-- lists the names of the expression -- SAL+BONUS+COMM as TOTAL_PAY and -- orders by the new name TOTAL_PAY SELECT FIRSTNME, SALARY+BONUS+COMM AS TOTAL_PAY FROM EMPLOYEE ORDER BY TOTAL_PAY -- creating an updatable cursor with a FOR UPDATE clause -- to update the start date (PRSTDATE) and the end date (PRENDATE) -- columns in the PROJECT table SELECT PROJNO, PRSTDATE, PRENDATE FROM PROJECT FOR UPDATE OF PRSTDATE, PRENDATE -- set the isolation level to RR for this statement only SELECT * FROM Flights WHERE flight_id BETWEEN 'AA1111' AND 'AA1112' WITH RR
A SELECT statement returns a ResultSet. A cursor is a pointer to a specific row in ResultSet. In Java applications, all ResultSets have an underlying associated SQL cursor, often referred to as the result set's cursor. The cursor can be updatable, that is, you can update or delete rows as you step through the ResultSet if the SELECT statement that generated it and its underlying query meet cursor updatability requirements, as detailed below. The FOR UPDATE clause can be used to ensure a compilation check that the SELECT statement meets the requiremments of a updatable cursors, or to limit the columns that can be updated.
Note: The ORDER BY clause allows you to order the results of the SELECT. Without the ORDER BY clause, the results are returned in random order.
Requirements for updatable cursors and updatable ResultSets
Only simple, single-table SELECT cursors can be updatable. The SELECT statement for updatable ResultSets has the same syntax as the SELECT statement for updatable cursors. To generate updatable cursors:
 
The SELECT statement must not include an ORDER BY clause.
 
The underlying Query must be a SelectExpression.
 
The SelectExpression in the underlying Query must not include:
 
DISTINCT
 
Aggregates
 
GROUP BY clause
 
HAVING clause
 
ORDER BY clause
 
The FROM clause in the underlying Query must not have:
 
more than one table in its FROM clause
 
anything other than one table name
 
 
subqueries
Note: Cursors are read-only by default. To produce an updatable cursor besides meeting the requirements listed above, the concurrency mode for the ResultSet must be ResultSet.CONCUR_UPDATABLE or the SELECT statement must have FOR UPDATE in the FOR clause (see FOR UPDATE clause).
There is no SQL language statement to assign a name to a cursor. Instead, one can use the JDBC API to assign names to cursors or retrieve system-generated names. For more information, see Naming or accessing the name of a cursor in the Java DB Developer's Guide.
Statement dependency system
The SELECT depends on all the tables and views named in the query and the conglomerates (units of storage such as heaps and indexes) chosen for access paths on those tables. CREATE INDEX does not invalidate a prepared SELECT statement. A DROP INDEX statement invalidates a prepared SELECT statement if the index is an access path in the statement. If the SELECT includes views, it also depends on the dictionary objects on which the view itself depends (see CREATE VIEW statement).
Any prepared UPDATE WHERE CURRENT or DELETE WHERE CURRENT statement against a cursor of a SELECT depends on the SELECT. Removing a SELECT through a java.sql.Statement.close request invalidates the UPDATE WHERE CURRENT or DELETE WHERE CURRENT.
The SELECT depends on all aliases used in the query. Dropping an alias invalidates a prepared SELECT statement if the statement uses the alias.
UPDATE statement
Syntax
{ UPDATE table-Name [[AS] correlation-Name] SET column-Name = Value [ , column-Name = Value} ]* [WHERE clause] | UPDATE table-Name SET column-Name = Value [ , column-Name = Value ]* WHERE CURRENT OF }
where Value is defined as follows:
Expression | DEFAULT
The first syntactical form, called a searched update, updates the value of one or more columns for all rows of the table for which the WHERE clause evaluates to TRUE.
The second syntactical form, called a positioned update, updates one or more columns on the current row of an open, updatable cursor. If columns were specified in the FOR UPDATE clause of the SELECT statement used to generate the cursor, only those columns can be updated. If no columns were specified or the select statement did not include a FOR UPDATE clause, all columns may be updated.
Specifying DEFAULT for the update value sets the value of the column to the default defined for that table.
Example
-- All the employees except the manager of -- department (WORKDEPT) 'E21' have been temporarily reassigned. -- Indicate this by changing their job (JOB) to NULL and their pay -- (SALARY, BONUS, COMM) values to zero in the EMPLOYEE table. UPDATE EMPLOYEE SET JOB=NULL, SALARY=0, BONUS=0, COMM=0 WHERE WORKDEPT = 'E21' AND JOB <> 'MANAGER' -- PROMOTE the job (JOB) of employees without a specific job title to MANAGER UPDATE EMPLOYEE SET JOB = 'MANAGER' WHERE JOB IS NULL; // Increase the project staffing (PRSTAFF) by 1.5 for all projects stmt.executeUpdate("UPDATE PROJECT SET PRSTAFF = " "PRSTAFF + 1.5" + "WHERE CURRENT OF" + ResultSet.getCursorName()); -- Change the job (JOB) of employee number (EMPNO) '000290' in the EMPLOYEE table -- to its DEFAULT value which is NULL UPDATE EMPLOYEE SET JOB = DEFAULT WHERE EMPNO = '000290'
Statement dependency system
A searched update statement depends on the table being updated, all of its conglomerates (units of storage such as heaps or indexes), all of its constraints, and any other table named in the WHERE clause or SET expressions. A CREATE or DROP INDEX statement or an ALTER TABLE statement for the target table of a prepared searched update statement invalidates the prepared searched update statement.
The positioned update statement depends on the cursor and any tables the cursor references. You can compile a positioned update even if the cursor has not been opened yet. However, removing the open cursor with the JDBC close method invalidates the positioned update.
A CREATE or DROP INDEX statement or an ALTER TABLE statement for the target table of a prepared positioned update invalidates the prepared positioned update statement.
Dropping an alias invalidates a prepared update statement if the latter statement uses the alias.
Dropping or adding triggers on the target table of the update invalidates the update statement.
SQL clauses
CONSTRAINT clause
A CONSTRAINT clause is an optional part of a CREATE TABLE statement or ALTER TABLE statement. A constraint is a rule to which data must conform. Constraint names are optional.
A CONSTRAINT can be one of the following:
 
a column-level constraint
Column-level constraints refer to a single column in the table and do not specify a column name (except check constraints). They refer to the column that they follow.
 
a table-level constraint
Table-level constraints refer to one or more columns in the table. Table-level constraints specify the names of the columns to which they apply. Table-level CHECK constraints can refer to 0 or more columns in the table.
Column constraints include:
 
NOT NULL
Specifies that this column cannot hold NULL values (constraints of this type are not nameable).
 
PRIMARY KEY
Specifies the column that uniquely identifies a row in the table. The identified columns must be defined as NOT NULL.
Note: If you attempt to add a primary key using ALTER TABLE and any of the columns included in the primary key contain null values, an error will be generated and the primary key will not be added. See ALTER TABLE statement for more information.
 
UNIQUE
Specifies that values in the column must be unique.
 
FOREIGN KEY
Specifies that the values in the column must correspond to values in a referenced primary key or unique key column or that they are NULL.
 
CHECK
Specifies rules for values in the column.
Table constraints include:
 
PRIMARY KEY
Specifies the column or columns that uniquely identify a row in the table. NULL values are not allowed.
 
UNIQUE
Specifies that values in the columns must be unique.
 
FOREIGN KEY
Specifies that the values in the columns must correspond to values in referenced primary key or unique columns or that they are NULL.
Note: If the foreign key consists of multiple columns, and any column is NULL, the whole key is considered NULL. The insert is permitted no matter what is on the non-null columns.
 
CHECK
Specifies a wide range of rules for values in the table.
Column constraints and table constraints have the same function; the difference is in where you specify them. Table constraints allow you to specify more than one column in a PRIMARY KEY, UNIQUE, CHECK, or FOREIGN KEY constraint definition. Column-level constraints (except for check constraints) refer to only one column.
Syntax
Primary key constraints
A primary key defines the set of columns that uniquely identifies rows in a table.
When you create a primary key constraint, none of the columns included in the primary key can have NULL constraints; that is, they must not permit NULL values.
ALTER TABLE ADD PRIMARY KEY allows you to include existing columns in a primary key if they were first defined as NOT NULL. NULL values are not allowed. If the column(s) contain NULL values, the system will not add the primary key constraint. See ALTER TABLE statement for more information.
A table can have at most one PRIMARY KEY constraint.
Unique constraints
A UNIQUE constraint defines a set of columns that uniquely identify rows in a table only if all the key values are not NULL. If one or more key parts are NULL, duplicate keys are allowed.
For example, if there is a UNIQUE constraint on col1 and col2 of a table, the combination of the values held by col1 and col2 will be unique as long as these values are not NULL. If one of col1 and col2 holds a NULL value, there can be another identical row in the table.
A table can have multiple UNIQUE constraints.
Foreign key constraints
Foreign keys provide a way to enforce the referential integrity of a database. A foreign key is a column or group of columns within a table that references a key in some other table (or sometimes, though rarely, the same table). The foreign key must always include the columns of which the types exactly match those in the referenced primary key or unique constraint.
For a table-level foreign key constraint in which you specify the columns in the table that make up the constraint, you cannot use the same column more than once.
If there is a column list in the ReferencesSpecification (a list of columns in the referenced table), it must correspond either to a unique constraint or to a primary key constraint in the referenced table. The ReferencesSpecification can omit the column list for the referenced table if that table has a declared primary key.
If there is no column list in the ReferencesSpecification and the referenced table has no primary key, a statement exception is thrown. (This means that if the referenced table has only unique keys, you must include a column list in the ReferencesSpecification.)
A foreign key constraint is satisfied if there is a matching value in the referenced unique or primary key column. If the foreign key consists of multiple columns, the foreign key value is considered NULL if any of its columns contains a NULL.
Note: It is possible for a foreign key consisting of multiple columns to allow one of the columns to contain a value for which there is no matching value in the referenced columns, per the SQL-92 standard. To avoid this situation, create NOT NULL constraints on all of the foreign key's columns.
Foreign key constraints and DML
When you insert into or update a table with an enabled foreign key constraint, Derby checks that the row does not violate the foreign key constraint by looking up the corresponding referenced key in the referenced table. If the constraint is not satisfied, Derby rejects the insert or update with a statement exception.
When you update or delete a row in a table with a referenced key (a primary or unique constraint referenced by a foreign key), Derby checks every foreign key constraint that references the key to make sure that the removal or modification of the row does not cause a constraint violation. If removal or modification of the row would cause a constraint violation, the update or delete is not permitted and Derby throws a statement exception.
Derby performs constraint checks at the time the statement is executed, not when the transaction commits.
Backing indexes
UNIQUE, PRIMARY KEY, and FOREIGN KEY constraints generate indexes that enforce or "back" the constraint (and are sometimes called backing indexes). PRIMARY KEY constraints generate unique indexes. FOREIGN KEY constraints generate non-unique indexes. UNIQUE constraints generate unique indexes if all the columns are non-nullable, and they generate non-unique indexes if one or more columns are nullable. Therefore, if a column or set of columns has a UNIQUE, PRIMARY KEY, or FOREIGN KEY constraint on it, you do not need to create an index on those columns for performance. Derby has already created it for you. See Indexes and constraints.
These indexes are available to the optimizer for query optimization (see CREATE INDEX statement) and have system-generated names.
You cannot drop backing indexes with a DROP INDEX statement; you must drop the constraint or the table.
Check constraints
A check constraint can be used to specify a wide range of rules for the contents of a table. A search condition (which is a boolean expression) is specified for a check constraint. This search condition must be satisfied for all rows in the table. The search condition is applied to each row that is modified on an INSERT or UPDATE at the time of the row modification. The entire statement is aborted if any check constraint is violated.
Requirements for search condition
If a check constraint is specified as part of a column-definition, a column reference can only be made to the same column. Check constraints specified as part of a table definition can have column references identifying columns previously defined in the CREATE TABLE statement.
The search condition must always return the same value if applied to the same values. Thus, it cannot contain any of the following:
 
Dynamic parameters (?)
 
Date/Time Functions (CURRENT_DATE, CURRENT_TIME, CURRENT_TIMESTAMP)
 
Subqueries
 
User Functions (such as USER, SESSION_USER, CURRENT_USER)
Referential actions
You can specify an ON DELETE clause and/or an ON UPDATE clause, followed by the appropriate action (CASCADE, RESTRICT, SET NULL, or NO ACTION) when defining foreign keys. These clauses specify whether Derby should modify corresponding foreign key values or disallow the operation, to keep foreign key relationships intact when a primary key value is updated or deleted from a table.
You specify the update and delete rule of a referential constraint when you define the referential constraint.
The update rule applies when a row of either the parent or dependent table is updated. The choices are NO ACTION and RESTRICT.
When a value in a column of the parent table's primary key is updated and the update rule has been specified as RESTRICT, Derby checks dependent tables for foreign key constraints. If any row in a dependent table violates a foreign key constraint, the transaction is rolled back.
If the update rule is NO ACTION, Derby checks the dependent tables for foreign key constraints after all updates have been executed but before triggers have been executed. If any row in a dependent table violates a foreign key constraint, the statement is rejected.
When a value in a column of the dependent table is updated, and that value is part of a foreign key, NO ACTION is the implicit update rule. NO ACTION means that if a foreign key is updated with a non-null value, the update value must match a value in the parent table's primary key when the update statement is completed. If the update does not match a value in the parent table's primary key, the statement is rejected.
The delete rule applies when a row of the parent table is deleted and that row has dependents in the dependent table of the referential constraint. If rows of the dependent table are deleted, the delete operation on the parent table is said to be propagated to the dependent table. If the dependent table is also a parent table, the action specified applies, in turn, to its dependents.
The choices are NO ACTION, RESTRICT, CASCADE, or SET NULL. SET NULL can be specified only if some column of the foreign key allows null values.
If the delete rule is:
NO ACTION, Derby checks the dependent tables for foreign key constraints after all deletes have been executed but before triggers have been executed. If any row in a dependent table violates a foreign key constraint, the statement is rejected.
RESTRICT, Derby checks dependent tables for foreign key constraints. If any row in a dependent table violates a foreign key constraint, the transaction is rolled back.
CASCADE, the delete operation is propagated to the dependent table (and that table's dependents, if applicable).
SET NULL, each nullable column of the dependent table's foreign key is set to null. (Again, if the dependent table also has dependent tables, nullable columns in those tables' foreign keys are also set to null.)
Each referential constraint in which a table is a parent has its own delete rule; all applicable delete rules are used to determine the result of a delete operation. Thus, a row cannot be deleted if it has dependents in a referential constraint with a delete rule of RESTRICT or NO ACTION. Similarly, a row cannot be deleted if the deletion cascades to any of its descendants that are dependents in a referential constraint with the delete rule of RESTRICT or NO ACTION.
Deleting a row from the parent table involves other tables. Any table involved in a delete operation on the parent table is said to be delete-connected to the parent table. The delete can affect rows of these tables in the following ways:
 
If the delete rule is RESTRICT or NO ACTION, a dependent table is involved in the operation but is not affected by the operation. (That is, Derby checks the values within the table, but does not delete any values.)
 
If the delete rule is SET NULL, a dependent table's rows can be updated when a row of the parent table is the object of a delete or propagated delete operation.
 
If the delete rule is CASCADE, a dependent table's rows can be deleted when a parent table is the object of a delete.
 
If the dependent table is also a parent table, the actions described in this list apply, in turn, to its dependents.
Examples
-- column-level primary key constraint named OUT_TRAY_PK: CREATE TABLE SAMP.OUT_TRAY ( SENT TIMESTAMP, DESTINATION CHAR(8), SUBJECT CHAR(64) NOT NULL CONSTRAINT OUT_TRAY_PK PRIMARY KEY, NOTE_TEXT VARCHAR(3000) ); -- the table-level primary key definition allows you to -- include two columns in the primary key definition: CREATE TABLE SAMP.SCHED ( CLASS_CODE CHAR(7) NOT NULL, DAY SMALLINT NOT NULL, STARTING TIME, ENDING TIME, PRIMARY KEY (CLASS_CODE, DAY) ); -- Use a column-level constraint for an arithmetic check -- Use a table-level constraint -- to make sure that a employee's taxes does not -- exceed the bonus CREATE TABLE SAMP.EMP ( EMPNO CHAR(6) NOT NULL CONSTRAINT EMP_PK PRIMARY KEY, FIRSTNME CHAR(12) NOT NULL, MIDINIT vARCHAR(12) NOT NULL, LASTNAME VARCHAR(15) NOT NULL, SALARY DECIMAL(9,2) CONSTRAINT SAL_CK CHECK (SALARY >= 10000), BONUS DECIMAL(9,2), TAX DECIMAL(9,2), CONSTRAINT BONUS_CK CHECK (BONUS > TAX) ); -- use a check constraint to allow only appropriate -- abbreviations for the meals CREATE TABLE FLIGHTS ( FLIGHT_ID CHAR(6) NOT NULL , SEGMENT_NUMBER INTEGER NOT NULL , ORIG_AIRPORT CHAR(3), DEPART_TIME TIME, DEST_AIRPORT CHAR(3), ARRIVE_TIME TIME, MEAL CHAR(1) CONSTRAINT MEAL_CONSTRAINT CHECK (MEAL IN ('B', 'L', 'D', 'S')), PRIMARY KEY (FLIGHT_ID, SEGMENT_NUMBER) ); CREATE TABLE METROPOLITAN ( HOTEL_ID INT NOT NULL CONSTRAINT HOTELS_PK PRIMARY KEY, HOTEL_NAME VARCHAR(40) NOT NULL, CITY_ID INT CONSTRAINT METRO_FK REFERENCES CITIES ); -- create a table with a table-level primary key constraint -- and a table-level foreign key constraint CREATE TABLE FLTAVAIL ( 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 FLTAVAIL_PK PRIMARY KEY (FLIGHT_ID, SEGMENT_NUMBER), CONSTRAINT FLTS_FK FOREIGN KEY (FLIGHT_ID, SEGMENT_NUMBER) REFERENCES Flights (FLIGHT_ID, SEGMENT_NUMBER) ); -- add a unique constraint to a column ALTER TABLE SAMP.PROJECT ADD CONSTRAINT P_UC UNIQUE (PROJNAME); -- create a table whose city_id column references the -- primary key in the Cities table -- using a column-level foreign key constraint CREATE TABLE CONDOS ( CONDO_ID INT NOT NULL CONSTRAINT hotels_PK PRIMARY KEY, CONDO_NAME VARCHAR(40) NOT NULL, CITY_ID INT CONSTRAINT city_foreign_key REFERENCES Cities ON DELETE CASCADE ON UPDATE RESTRICT );
Statement dependency system
INSERT and UPDATE statements depend on all constraints on the target table. DELETEs depend on unique, primary key, and foreign key constraints. These statements are invalidated if a constraint is added to or dropped from the target table.
Column-level-constraint
{ NOT NULL | [ [CONSTRAINT constraint-Name] { CHECK (searchCondition) | { PRIMARY KEY | UNIQUE | REFERENCES clause } } }
Table-level constraint
[CONSTRAINT constraint-Name] { CHECK (searchCondition) | { PRIMARY KEY ( Simple-column-Name [ , Simple-column-Name ]* ) | UNIQUE ( Simple-column-Name [ , Simple-column-Name ]* ) | FOREIGN KEY ( Simple-column-Name [ , Simple-column-Name ]* ) REFERENCES clause } }
References specification
REFERENCES table-Name [ ( Simple-column-Name [ , Simple-column-Name ]* ) ] [ ON DELETE {NO ACTION | RESTRICT | CASCADE | SET NULL}] [ ON UPDATE {NO ACTION | RESTRICT }] | [ ON UPDATE {NO ACTION | RESTRICT }] [ ON DELETE {NO ACTION | RESTRICT | CASCADE | SET NULL}]
searchCondition
A searchCondition is any Boolean expression that meets the requirements specified in Requirements for search condition.
If a constraint-Name is not specified, Derby generates a unique constraint name (for either column or table constraints).
FOR UPDATE clause
The FOR UPDATE clause is an optional part of a SELECT statement. Cursors are read-only by default. The FOR UPDATE clause specifies that the cursor should be updatable, and enforces a check during compilation that the SELECT statement meets the requirements for an updatable cursor. For more information about updatability, see Requirements for Updatable Cursors.
Syntax
FOR { READ ONLY | FETCH ONLY | UPDATE [ OF Simple-column-Name [ , Simple-column-Name]* ] }
Simple-column-Name refers to the names visible for the table specified in the FROM clause of the underlying query.
Note: The use of the FOR UPDATE clause is not mandatory to obtain an updatable JDBC ResultSet. As long as the statement used to generate the JDBC ResultSet meets the requirements for updatable cursor, it is sufficient for the JDBC Statement that generates the JDBC ResultSet to have concurrency mode ResultSet.CONCUR_UPDATABLE for the ResultSet to be updatable.
The optimizer is able to use an index even if the column in the index is being updated. For more information about how indexes affect cursors, see Tuning Java DB.
SELECT RECEIVED, SOURCE, SUBJECT, NOTE_TEXT FROM SAMP.IN_TRAY FOR UPDATE
FROM clause
The FROM clause is a mandatory clause in a SelectExpression. It specifies the tables (TableExpression) from which the other clauses of the query can access columns for use in expressions.
Syntax
FROM TableExpression [ , TableExpression ] *
SELECT Cities.city_id FROM Cities WHERE city_id < 5 -- other types of TableExpressions SELECT TABLENAME, ISINDEX FROM SYS.SYSTABLES T, SYS.SYSCONGLOMERATES C WHERE T.TABLEID = C.TABLEID ORDER BY TABLENAME, ISINDEX -- force the join order SELECT * FROM Flights, FlightAvailability WHERE FlightAvailability.flight_id = Flights.flight_id AND FlightAvailability.segment_number = Flights.segment_number AND Flights.flight_id < 'AA1115' -- a TableExpression can be a joinOperation. Therefore -- you can have multiple join operations in a FROM clause SELECT COUNTRIES.COUNTRY, CITIES.CITY_NAME, FLIGHTS.DEST_AIRPORT FROM COUNTRIES LEFT OUTER JOIN CITIES ON COUNTRIES.COUNTRY_ISO_CODE = CITIES.COUNTRY_ISO_CODE LEFT OUTER JOIN FLIGHTS ON Cities.AIRPORT = FLIGHTS.DEST_AIRPORT
GROUP BY clause
A GROUP BY clause, part of a SelectExpression, groups a result into subsets that have matching values for one or more columns. In each group, no two rows have the same value for the grouping column or columns. NULLs are considered equivalent for grouping purposes.
You typically use a GROUP BY clause in conjunction with an aggregate expression.
Syntax
GROUP BY column-Name [ , column-Name ] *
column-Name must be a column from the current scope of the query; there can be no columns from a query block outside the current scope. For example, if a GROUP BY clause is in a subquery, it cannot refer to columns in the outer query.
SelectItems in the SelectExpression with a GROUP BY clause must contain only aggregates or grouping columns.
-- find the average flying_times of flights grouped by -- airport SELECT AVG (flying_time), orig_airport FROM Flights GROUP BY orig_airport SELECT MAX(city_name), region FROM Cities, Countries WHERE Cities.country_ISO_code = Countries.country_ISO_code GROUP BY region -- group by an a smallint SELECT ID, AVG(SALARY) FROM SAMP.STAFF GROUP BY ID -- Get the AVGSALARY and EMPCOUNT columns, and the DEPTNO column using the AS clause -- And group by the WORKDEPT column using the correlation name OTHERS SELECT OTHERS.WORKDEPT AS DEPTNO, AVG(OTHERS.SALARY) AS AVGSALARY, COUNT(*) AS EMPCOUNT FROM SAMP.EMPLOYEE OTHERS GROUP BY OTHERS.WORKDEPT
HAVING clause
A HAVING clause restricts the results of a GROUP BY in a SelectExpression. The HAVING clause is applied to each group of the grouped table, much as a WHERE clause is applied to a select list. If there is no GROUP BY clause, the HAVING clause is applied to the entire result as a single group. The SELECT clause cannot refer directly to any column that does not have a GROUP BY clause. It can, however, refer to constants, aggregates, and special registers.
Syntax
HAVING searchCondition
The searchCondition, which is a specialized booleanExpression, can contain only grouping columns (see GROUP BY clause), columns that are part of aggregate expressions, and columns that are part of a subquery. For example, the following query is illegal, because the column SALARY is not a grouping column, it does not appear within an aggregate, and it is not within a subquery:
-- SELECT COUNT(*) -- FROM SAMP.STAFF -- GROUP BY ID -- HAVING SALARY > 15000
Aggregates in the HAVING clause do not need to appear in the SELECT list. If the HAVING clause contains a subquery, the subquery can refer to the outer query block if and only if it refers to a grouping column.
-- Find the total number of economy seats taken on a flight, -- grouped by airline, -- only when the group has at least 2 records. SELECT SUM(ECONOMY_SEATS_TAKEN), AIRLINE_FULL FROM FLIGHTAVAILABILITY, AIRLINES WHERE SUBSTR(FLIGHTAVAILABILITY.FLIGHT_ID, 1, 2) = AIRLINE GROUP BY AIRLINE_FULL HAVING COUNT(*) > 1
ORDER BY clause
The ORDER BY clause is an optional element of a SELECT statement. An ORDER BY clause allows you to specify the order in which rows appear in the ResultSet.
Syntax
ORDER BY { column-Name | ColumnPosition | Expression } [ ASC | DESC ] [ , column-Name | ColumnPosition | Expression [ ASC | DESC ] ] *
column-Name
Refers to the names visible from the SelectItems in the underlying query of the SELECT statement. The column-Name that you specify in the ORDER BY clause does not need to be the SELECT list.
ColumnPosition
An integer that identifies the number of the column in the SelectItems in the underlying query of the SELECT statement. ColumnPosition must be greater than 0 and not greater than the number of columns in the result table. In other words, if you want to order by a column, that column must be specified in the SELECT list.
Expression
A sort key expression, such as numeric, string, and datetime expressions. Expression can also be a row value expression such as a scalar subquery or case expression.
ASC
Specifies that the results should be returned in ascending order. If the order is not specified, ASC is the default.
DESC
Specifies that the results should be returned in descending order.
Notes
 
If SELECT DISTINCT is specified or if the SELECT statement contains a GROUP BY clause, the ORDER BY columns must be in the SELECT list.
 
An ORDER BY clause prevents a SELECT statement from being an updatable cursor. For more information, see Requirements for updatable cursors and updatable ResultSets. For example, if an INTEGER column contains integers, NULL is considered greater than 1 for purposes of sorting. In other words, NULL values are sorted high.
Example using a correlation name
You can sort the result set by a correlation name, if the correlation name is specified in the select list. For example, to return from the CITIES database all of the entries in the CITY_NAME and COUNTRY columns, where the COUNTRY column has the correlation name NATION, you specify this SELECT statement:
SELECT CITY_NAME, COUNTRY AS NATION FROM CITIES ORDER BY NATION
Example using a numeric expression
You can sort the result set by a numeric expression, for example:
SELECT name, salary, bonus FROM employee ORDER BY salary+bonus
In this example, the salary and bonus columns are DECIMAL data types.
Example using a function
You can sort the result set by invoking a function, for example:
SELECT i, len FROM measures ORDER BY sin(i)
WHERE clause
A WHERE clause is an optional part of a SelectExpression,DELETE statement, or UPDATE statement. The WHERE clause lets you select rows based on a boolean expression. Only rows for which the expression evaluates to TRUE are returned in the result, or, in the case of a DELETE statement, deleted, or, in the case of an UPDATE statement, updated.
Syntax
Boolean expressions are allowed in the WHERE clause. Most of the general expressions listed in Table of general expressions, can result in a boolean value.
In addition, there are the more common boolean expressions. Specific boolean operators listed in Table 10, take one or more operands; the expressions return a boolean value.
Example
-- find the flights where no business-class seats have -- been booked SELECT * FROM FlightAvailability WHERE business_seats_taken IS NULL OR business_seats_taken = 0 -- Join the EMP_ACT and EMPLOYEE tables -- select all the columns from the EMP_ACT table and -- add the employee's surname (LASTNAME) from the EMPLOYEE table -- to each row of the result. SELECT SAMP.EMP_ACT.*, LASTNAME FROM SAMP.EMP_ACT, SAMP.EMPLOYEE WHERE EMP_ACT.EMPNO = EMPLOYEE.EMPNO -- Determine the employee number and salary of sales representatives -- along with the average salary and head count of their departments. -- This query must first create a new-column-name specified in the AS clause -- which is outside the fullselect (DINFO) -- in order to get the AVGSALARY and EMPCOUNT columns, -- as well as the DEPTNO column that is used in the WHERE clause SELECT THIS_EMP.EMPNO, THIS_EMP.SALARY, DINFO.AVGSALARY, DINFO.EMPCOUNT FROM EMPLOYEE THIS_EMP, (SELECT OTHERS.WORKDEPT AS DEPTNO, AVG(OTHERS.SALARY) AS AVGSALARY, COUNT(*) AS EMPCOUNT FROM EMPLOYEE OTHERS GROUP BY OTHERS.WORKDEPT )AS DINFO WHERE THIS_EMP.JOB = 'SALESREP' AND THIS_EMP.WORKDEPT = DINFO.DEPTNO
WHERE CURRENT OF clause
The WHERE CURRENT OF clause is a clause in some UPDATE and DELETE statements. It allows you to perform positioned updates and deletes on updatable cursors. For more information about updatable cursors, see SELECT statement.
Syntax
WHERE CURRENT OF cursor-Name
Statement s = conn.createStatement(); s.setCursorName("AirlinesResults"); ResultSet rs = conn.executeQuery( "SELECT Airline, basic_rate " + "FROM Airlines FOR UPDATE OF basic_rate"); Statement s2 = conn.createStatement(); s2.executeUpdate("UPDATE Airlines SET basic_rate = basic_rate " + "+ .25 WHERE CURRENT OF AirlinesResults");
SQL expressions
Syntax for many statements and expressions includes the term Expression, or a term for a specific kind of expression such as TableSubquery. Expressions are allowed in these specified places within statements.
Some locations allow only a specific type of expression or one with a specific property. If not otherwise specified, an expression is permitted anywhere the word Expression appears in the syntax. This includes:
Of course, many other statements include these elements as building blocks, and so allow expressions as part of these elements.
The following tables list all the possible SQL expressions and indicate where the expressions are allowed.
General expressions
General expressions are expressions that might result in a value of any type.
Table 2. Table of general expressions
Expression Type
Explanation
Column reference
A column-Name that references the value of the column made visible to the expression containing the Column reference.
You must qualify the column-Name by the table name or correlation name if it is ambiguous.
The qualifier of a column-Name must be the correlation name, if a correlation name is given to a table that is in a FROM clause. The table name is no longer visible as a column-Name qualifier once it has been aliased by a correlation name.
Allowed in SelectExpressions, UPDATE statements, and the WHERE clauses of data manipulation statements.
Constant
Most built-in data types typically have constants associated with them (as shown in Data types).
NULL
NULL is an untyped constant representing the unknown value.
Allowed in CAST expressions or in INSERT VALUES lists and UPDATE SET clauses. Using it in a CAST expression gives it a specific data type.
Dynamic parameter
A dynamic parameter is a parameter to an SQL statement for which the value is not specified when the statement is created. Instead, the statement has a question mark (?) as a placeholder for each dynamic parameter. See Dynamic parameters.
Dynamic parameters are permitted only in prepared statements. You must specify values for them before the prepared statement is executed. The values specified must match the types expected.
Allowed anywhere in an expression where the data type can be easily deduced. See Dynamic parameters.
CAST expression
Lets you specify the type of NULL or of a dynamic parameter or convert a value to another type. See CAST function.
Scalar subquery
Subquery that returns a single row with a single column. See ScalarSubquery.
Table subquery
Subquery that returns more than one column and more than one row. See TableSubquery.
Allowed as a tableExpression in a FROM clause and with EXISTS, IN, and quantified comparisons.
Conditional expression
A conditional expression chooses an expression to evaluate based on a boolean test.
Boolean expressions
Boolean expressions are expressions that result in boolean values. Most general expressions can result in boolean values. Boolean expressions commonly used in a WHERE clause are made of operands operated on by SQL operators. See SQL Boolean Operators.
Numeric expressions
Numeric expressions are expressions that result in numeric values. Most of the general expressions can result in numeric values. Numeric values have one of the following types:
 
BIGINT
 
DECIMAL
 
DOUBLE PRECISION
 
INTEGER
 
REAL
 
SMALLINT
Table 3. Table of numeric expressions
Expression Type
Explanation
+, -, *, /, unary + and - expressions
Evaluate the expected math operation on the operands. If both operands are the same type, the result type is not promoted, so the division operator on integers results in an integer that is the truncation of the actual numeric result. When types are mixed, they are promoted as described in Data types.
Unary + is a noop (i.e., +4 is the same as 4). Unary - is the same as multiplying the value by -1, effectively changing its sign.
AVG
Returns the average of a set of numeric values. AVG function
SUM
Returns the sum of a set of numeric values. SUM function
LENGTH
Returns the number of characters in a character or bit string. See LENGTH function.
LOWER
COUNT
Returns the count of a set of values. See COUNT function, COUNT(*) function.
Character expressions
Character expressions are expressions that result in a CHAR or VARCHAR value. Most general expressions can result in a CHAR or VARCHAR value.
Table 4. Table of character expressions
Expression Type
Explanation
A CHAR or VARCHAR value that uses wildcards.
The wildcards % and _ make a character string a pattern against which the LIKE operator can look for a match.
Concatenation expression
In a concatenation expression, the concatenation operator, "||", concatenates its right operand to the end of its left operand. Operates on character and bit strings. See Concatenation operator.
Built-in string functions
The built-in string functions act on a String and return a string. See LTRIM function, LCASE or LOWER function, RTRIM function, TRIM function, SUBSTR function, and UCASE or UPPER function.
USER functions
User functions return information about the current user as a String. See CURRENT_USER function, SESSION_USER function, and .
Date and time expressions
A date or time expression results in a DATE, TIME, or TIMESTAMP value. Most of the general expressions can result in a date or time value.
Table 5. Table of date and time expressions
Expression type
Explanation
CURRENT_DATE
Returns the current date. See CURRENT_DATE function.
CURRENT_TIME
Returns the current time. See CURRENT_TIME function.
CURRENT_TIMESTAMP
Returns the current timestamp. See CURRENT_TIMESTAMP function.
SelectExpression
A SelectExpression is the basic SELECT-FROM-WHERE construct used to build a table value based on filtering and projecting values from other tables.
Syntax
SELECT [ DISTINCT | ALL ] SelectItem [ , SelectItem ]* FROM clause [ WHERE clause] [ GROUP BY clause ] [ HAVING clause ]
SelectItem:
{ * | { table-Name | correlation-Name } .* | Expression [AS Simple-column-Name] }
The SELECT clause contains a list of expressions and an optional quantifier that is applied to the results of the FROM clause and the WHERE clause. If DISTINCT is specified, only one copy of any row value is included in the result. Nulls are considered duplicates of one another for the purposes of DISTINCT. If no quantifier, or ALL, is specified, no rows are removed from the result in applying the SELECT clause (ALL is the default).
A SelectItem projects one or more result column values for a table result being constructed in a SelectExpression.
The result of the FROM clause is the cross product of the FROM items. The WHERE clause can further qualify this result.
The WHERE clause causes rows to be filtered from the result based on a boolean expression. Only rows for which the expression evaluates to TRUE are returned in the result.
The GROUP BY clause groups rows in the result into subsets that have matching values for one or more columns. GROUP BY clauses are typically used with aggregates.
If there is a GROUP BY clause, the SELECT clause must contain only aggregates or grouping columns. If you want to include a non-grouped column in the SELECT clause, include the column in an aggregate expression. For example:
-- List head count of each department, -- the department number (WORKDEPT), and the average departmental salary (SALARY) -- for all departments in the EMPLOYEE table. -- Arrange the result table in ascending order by average departmental salary. SELECT COUNT(*),WORK_DEPT,AVG(SALARY) FROM EMPLOYEE GROUP BY WORK_DEPT ORDER BY 3
If there is no GROUP BY clause, but a SelectItem contains an aggregate not in a subquery, the query is implicitly grouped. The entire table is the single group.
The HAVING clause restricts a grouped table, specifying a search condition (much like a WHERE clause) that can refer only to grouping columns or aggregates from the current scope. The HAVING clause is applied to each group of the grouped table. If the HAVING clause evaluates to TRUE, the row is retained for further processing. If the HAVING clause evaluates to FALSE or NULL, the row is discarded. If there is a HAVING clause but no GROUP BY, the table is implicitly grouped into one group for the entire table.
Derby processes a SelectExpression in the following order:
 
FROM clause
 
WHERE clause
 
GROUP BY (or implicit GROUP BY)
 
HAVING clause
 
SELECT clause
The result of a SelectExpression is always a table.
When a query does not have a FROM clause (when you are constructing a value, not getting data out of a table), you use a VALUES expression, not a SelectExpression. For example:
VALUES CURRENT_TIMESTAMP
The * wildcard
* expands to all columns in the tables in the associated FROM clause.
table-Name.* and correlation-Name.* expand to all columns in the identified table. That table must be listed in the associated FROM clause.
Naming columns
You can name a SelectItem column using the AS clause. If a column of a SelectItem is not a simple ColumnReference expression or named with an AS clause, it is given a generated unique name.
These column names are useful in several cases:
 
They are made available on the JDBC ResultSetMetaData.
 
They are used as the names of the columns in the resulting table when the SelectExpression is used as a table subquery in a FROM clause.
 
They are used in the ORDER BY clause as the column names available for sorting.
-- this example shows SELECT-FROM-WHERE -- with an ORDER BY clause -- and correlation-Names for the tables SELECT CONSTRAINTNAME, COLUMNNAME FROM SYS.SYSTABLES t, SYS.SYSCOLUMNS col, SYS.SYSCONSTRAINTS cons, SYS.SYSCHECKS checks WHERE t.TABLENAME = 'FLIGHTS' AND t.TABLEID = col. REFERENCEID AND t.TABLEID = cons.TABLEID AND cons.CONSTRAINTID = checks.CONSTRAINTID ORDER BY CONSTRAINTNAME -- This example shows the use of the DISTINCT clause SELECT DISTINCT ACTNO FROM EMP_ACT -- This example shows how to rename an expression -- Using the EMPLOYEE table, list the department number (WORKDEPT) and -- maximum departmental salary (SALARY) renamed as BOSS -- for all departments whose maximum salary is less than the -- average salary in all other departments. SELECT WORKDEPT AS DPT, MAX(SALARY) AS BOSS FROM EMPLOYEE EMP_COR GROUP BY WORKDEPT HAVING MAX(SALARY) < (SELECT AVG(SALARY) FROM EMPLOYEE WHERE NOT WORKDEPT = EMP_COR.WORKDEPT) ORDER BY BOSS
TableExpression
A TableExpression specifies a table, view, or function in a FROM clause. It is the source from which a SelectExpression selects a result.
A correlation name can be applied to a table in a TableExpression so that its columns can be qualified with that name. If you do not supply a correlation name, the table name qualifies the column name. When you give a table a correlation name, you cannot use the table name to qualify columns. You must use the correlation name when qualifying column names.
No two items in the FROM clause can have the same correlation name, and no correlation name can be the same as an unqualified table name specified in that FROM clause.
In addition, you can give the columns of the table new names in the AS clause. Some situations in which this is useful:
 
When a VALUES expression is used as a TableSubquery, since there is no other way to name the columns of a VALUES expression.
 
When column names would otherwise be the same as those of columns in other tables; renaming them means you don't have to qualify them.
The Query in a TableSubquery appearing in a FromItem can contain multiple columns and return multiple rows. See TableSubquery.
For information about the optimizer overrides you can specify, see Tuning Java DB.
Syntax
{ TableViewOrFunctionExpression | JOIN operation }
Example
-- SELECT from a Join expression SELECT E.EMPNO, E.LASTNAME, M.EMPNO, M.LASTNAME FROM EMPLOYEE E LEFT OUTER JOIN DEPARTMENT INNER JOIN EMPLOYEE M ON MGRNO = M.EMPNO ON E.WORKDEPT = DEPTNO
TableViewOrFunctionExpression
TableFunctionInvocation:
TABLE function-name( [ [ function-arg ] [, function-arg ]* ] )
Note that when you invoke a table function, you must bind it to a correlation name. For example:
SELECT s.* FROM TABLE( externalEmployees( 42 ) ) s
VALUES expression
The VALUES expression allows construction of a row or a table from other values. A VALUES expression can be used in all the places where a query can, and thus can be used in any of the following ways:
 
As a statement that returns a ResultSet
 
Within expressions and statements wherever subqueries are permitted
 
As the source of values for an INSERT statement (in an INSERT statement, you normally use a VALUES expression when you do not use a SelectExpression)
Syntax
{ VALUES ( Value {, Value }* ) [ , ( Value {, Value }* ) ]* | VALUES Value [ , Value ]* }
where Value is defined as
Expression | DEFAULT
The first form constructs multi-column rows. The second form constructs single-column rows, each expression being the value of the column of the row.
The DEFAULT keyword is allowed only if the VALUES expression is in an INSERT statement. Specifying DEFAULT for a column inserts the column's default value into the column. Another way to insert the default value into the column is to omit the column from the column list and only insert values into other columns in the table.
Examples
-- 3 rows of 1 column VALUES (1),(2),(3) -- 3 rows of 1 column VALUES 1, 2, 3 -- 1 row of 3 columns VALUES (1, 2, 3) -- 3 rows of 2 columns VALUES (1,21),(2,22),(3,23) -- constructing a derived table VALUES ('orange', 'orange'), ('apple', 'red'), ('banana', 'yellow') -- Insert two new departments using one statement into the DEPARTMENT table, -- but do not assign a manager to the new department. INSERT INTO DEPARTMENT (DEPTNO, DEPTNAME, ADMRDEPT) VALUES ('B11', 'PURCHASING', 'B01'), ('E41', 'DATABASE ADMINISTRATION', 'E01') -- insert a row with a DEFAULT value for the MAJPROJ column INSERT INTO PROJECT (PROJNO, PROJNAME, DEPTNO, RESPEMP, PRSTDATE, MAJPROJ) VALUES ('PL2101', 'ENSURE COMPAT PLAN', 'B01', '000020', CURRENT_DATE, DEFAULT) -- using a built-in function VALUES CURRENT_DATE -- getting the value of an arbitrary expression VALUES (3*29, 26.0E0/3) -- getting a value returned by a built-in function values char(1)
Expression precedence
Precedence of operations from highest to lowest is:
 
(), ?, Constant (including sign), NULL, ColumnReference, ScalarSubquery, CAST
 
LENGTH, CURRENT_DATE, CURRENT_TIME, CURRENT_TIMESTAMP, and other built-ins
 
unary + and -
 
*, /, || (concatenation)
 
binary + and -
 
comparisons, quantified comparisons, EXISTS, IN, IS NULL, LIKE, BETWEEN, IS
 
NOT
 
AND
 
OR
You can explicitly specify precedence by placing expressions within parentheses. An expression within parentheses is evaluated before any operations outside the parentheses are applied to it.
Example
(3+4)*9 (age < 16 OR age > 65) AND employed = TRUE
Boolean expressions
Boolean expressions are allowed in WHERE clauses and in check constraints. Boolean expressions in check constraints have limitations not noted here; see CONSTRAINT clause for more information. Boolean expressions in a WHERE clause have a highly liberal syntax; see WHERE clause, for example.
A boolean expression can include a boolean operator or operators. These are listed in SQL Boolean Operators.
Table 6. SQL Boolean Operators
Operator
Explanation and Example
Syntax
AND, OR, NOT
Evaluate any operand(s) that are boolean expressions
(orig_airport = 'SFO') OR (dest_airport = 'GRU') -- returns true
{ Expression AND Expression | Expression OR Expression | NOT Expression }
Comparisons
<, =, >, <=, >=, <> are applicable to all of the built-in types.
DATE('1998-02-26') < DATE('1998-03-01') -- returns true
Expression { < | = | > | <= | >= | <> } Expression
IS NULL, IS NOT NULL
Test whether the result of an expression is null or not.
WHERE MiddleName IS NULL
Expression IS [ NOT ] NULL
LIKE
Attempts to match a character expression to a character pattern, which is a character string that includes one or more wildcards.
% matches any number (zero or more) of characters in the corresponding position in first character expression.
_ matches one character in the corresponding position in the character expression.
Any other character matches only that character in the corresponding position in the character expression.
city LIKE 'Sant_'
To treat % or _ as constant characters, escape the character with an optional escape character, which you specify with the ESCAPE clause.
SELECT a FROM tabA WHERE a LIKE '%=_' ESCAPE '='
Note: When LIKE comparisons are used,Derby compares one character at a time for non-metacharacters. This is different than the way Derby processes = comparisons. The comparisons with the = operator compare the entire character string on left side of the = operator with the entire character string on the right side of the = operator. For more information, see Character-based collation in Derby in the Java DB Developer's Guide.
CharacterExpression [ NOT ] LIKE CharacterExpression WithWildCard [ ESCAPE 'escapeCharacter']
BETWEEN
Tests whether the first operand is between the second and third operands. The second operand must be less than the third operand. Applicable only to types to which <= and >= can be applied.
WHERE booking_date BETWEEN DATE('1998-02-26') AND DATE('1998-03-01')
Expression [ NOT ] BETWEEN Expression AND Expression
IN
Operates on table subquery or list of values. Returns TRUE if the left expression's value is in the result of the table subquery or in the list of values. Table subquery can return multiple rows but must return a single column.
WHERE booking_date NOT IN (SELECT booking_date FROM HotelBookings WHERE rooms_available = 0)
{ Expression [ NOT ] IN TableSubquery | Expression [ NOT ] IN ( Expression [, Expression ]* ) }
EXISTS
Operates on a table subquery. Returns TRUE if the table subquery returns any rows, and FALSE if it returns no rows. Table subquery can return multiple columns (only if you use * to denote multiple columns) and rows.
WHERE EXISTS (SELECT * FROM Flights WHERE dest_airport = 'SFO' AND orig_airport = 'GRU')
[NOT] EXISTS TableSubquery
Quantified comparison
A quantified comparison is a comparison operator (<, =, >, <=, >=, <>) with ALL or ANY or SOME applied.
Operates on table subqueries, which can return multiple rows but must return a single column.
If ALL is used, the comparison must be true for all values returned by the table subquery. If ANY or SOME is used, the comparison must be true for at least one value of the table subquery. ANY and SOME are equivalent.
WHERE normal_rate < ALL (SELECT budget/550 FROM Groups)
Expression ComparisonOperator { ALL | ANY | SOME } TableSubquery
Dynamic parameters
You can prepare statements that are allowed to have parameters for which the value is not specified when the statement is prepared using PreparedStatement methods in the JDBC API. These parameters are called dynamic parameters and are represented by a ?.
The JDBC API documents refer to dynamic parameters as IN, INOUT, or OUT parameters. In SQL, they are always IN parameters.
New: Derby supports the interface ParameterMetaData, new in JDBC 3.0. This interface describes the number, type, and properties of prepared statement parameters. See the Java DB Developer's Guide for more information.
You must specify values for them before executing the statement. The values specified must match the types expected.
Dynamic parameters example
PreparedStatement ps2 = conn.prepareStatement( "UPDATE HotelAvailability SET rooms_available = " + "(rooms_available - ?) WHERE hotel_id = ? " + "AND booking_date BETWEEN ? AND ?"); -- this sample code sets the values of dynamic parameters -- to be the values of program variables ps2.setInt(1, numberRooms); ps2.setInt(2, theHotel.hotelId); ps2.setDate(3, arrival); ps2.setDate(4, departure); updateCount = ps2.executeUpdate();
Where dynamic parameters are allowed
You can use dynamic parameters anywhere in an expression where their data type can be easily deduced.
1.
 
Use as the first operand of BETWEEN is allowed if one of the second and third operands is not also a dynamic parameter. The type of the first operand is assumed to be the type of the non-dynamic parameter, or the union result of their types if both are not dynamic parameters.
WHERE ? BETWEEN DATE('1996-01-01') AND ? -- types assumed to be DATE
2.
 
Use as the second or third operand of BETWEEN is allowed. Type is assumed to be the type of the left operand.
WHERE DATE('1996-01-01') BETWEEN ? AND ? -- types assumed to be DATE
3.
 
Use as the left operand of an IN list is allowed if at least one item in the list is not itself a dynamic parameter. Type for the left operand is assumed to be the union result of the types of the non-dynamic parameters in the list.
WHERE ? NOT IN (?, ?, 'Santiago') -- types assumed to be CHAR
4.
 
Use in the values list in an IN predicate is allowed if the first operand is not a dynamic parameter or its type was determined in the previous rule. Type of the dynamic parameters appearing in the values list is assumed to be the type of the left operand.
WHERE FloatColumn IN (?, ?, ?) -- types assumed to be FLOAT
5.
 
For the binary operators +, -, *, /, AND, OR, <, >, =, <>, <=, and >=, use of a dynamic parameter as one operand but not both is permitted. Its type is taken from the other side.
WHERE ? < CURRENT_TIMESTAMP -- type assumed to be a TIMESTAMP
6.
 
Use in a CAST is always permitted. This gives the dynamic parameter a type.
CALL valueOf(CAST (? AS VARCHAR(10)))
7.
 
Use on either or both sides of LIKE operator is permitted. When used on the left, the type of the dynamic parameter is set to the type of the right operand, but with the maximum allowed length for the type. When used on the right, the type is assumed to be of the same length and type as the left operand. (LIKE is permitted on CHAR and VARCHAR types; see Concatenation operator for more information.)
WHERE ? LIKE 'Santi%' -- type assumed to be CHAR with a length of -- java.lang.Integer.MAX_VALUE
8.
 
A ? parameter is allowed by itself on only one side of the || operator. That is, "? || ?" is not allowed. The type of a ? parameter on one side of a || operator is determined by the type of the expression on the other side of the || operator. If the expression on the other side is a CHAR or VARCHAR, the type of the parameter is VARCHAR with the maximum allowed length for the type. If the expression on the other side is a CHAR FOR BIT DATA or VARCHAR FOR BIT DATA type, the type of the parameter is VARCHAR FOR BIT DATA with the maximum allowed length for the type.
SELECT BITcolumn || ? FROM UserTable -- Type assumed to be CHAR FOR BIT DATA of length specified for BITcolumn
9.
 
In a conditional expression, which uses a ?, use of a dynamic parameter (which is also represented as a ?) is allowed. The type of a dynamic parameter as the first operand is assumed to be boolean. Only one of the second and third operands can be a dynamic parameter, and its type will be assumed to be the same as that of the other (that is, the third and second operand, respectively).
SELECT c1 IS NULL ? ? : c1 -- allows you to specify a "default" value at execution time -- dynamic parameter assumed to be the type of c1 -- you cannot have dynamic parameters on both sides -- of the :
10.
 
A dynamic parameter is allowed as an item in the values list or select list of an INSERT statement. The type of the dynamic parameter is assumed to be the type of the target column.
INSERT INTO t VALUES (?) -- dynamic parameter assumed to be the type -- of the only column in table t INSERT INTO t SELECT ? FROM t2 -- not allowed
11.
 
A ? parameter in a comparison with a subquery takes its type from the expression being selected by the subquery. For example:
SELECT * FROM tab1 WHERE ? = (SELECT x FROM tab2) SELECT * FROM tab1 WHERE ? = ANY (SELECT x FROM tab2) -- In both cases, the type of the dynamic parameter is -- assumed to be the same as the type of tab2.x.
12.
 
A dynamic parameter is allowed as the value in an UPDATE statement. The type of the dynamic parameter is assumed to be the type of the column in the target table.
UPDATE t2 SET c2 =? -- type is assumed to be type of c2
13.
 
Dynamic parameters are allowed as the operand of the unary operators - or +. For example:
CREATE TABLE t1 (c11 INT, c12 SMALLINT, c13 DOUBLE, c14 CHAR(3)) SELECT * FROM t1 WHERE c11 BETWEEN -? AND +? -– The type of both of the unary operators is INT -- based on the context in which they are used (that is, -- because c11 is INT, the unary parameters also get the -- type INT.
14.
 
LENGTH allow a dynamic parameter. The type is assumed to be a maximum length VARCHAR type.
SELECT LENGTH(?)
15.
 
Qualified comparisons.
? = SOME (SELECT 1 FROM t) -- is valid. Dynamic parameter assumed to be INTEGER type 1 = SOME (SELECT ? FROM t) -- is valid. Dynamic parameter assumed to be INTEGER type.
16.
 
A dynamic parameter is allowed as the left operand of an IS expression and is assumed to be a boolean.
Once the type of a dynamic parameter is determined based on the expression it is in, that expression is allowed anywhere it would normally be allowed if it did not include a dynamic parameter.
JOIN operations
The JOIN operations, which are among the possible TableExpressions in a FROM clause, perform joins between two tables. (You can also perform a join between two tables using an explicit equality test in a WHERE clause, such as "WHERE t1.col1 = t2.col2".)
Syntax
JOIN Operation
The JOIN operations are:
 
INNER JOIN operation
Specifies a join between two tables with an explicit join clause. See INNER JOIN operation.
 
LEFT OUTER JOIN operation
Specifies a join between two tables with an explicit join clause, preserving unmatched rows from the first table. See LEFT OUTER JOIN operation.
 
RIGHT OUTER JOIN operation
Specifies a join between two tables with an explicit join clause, preserving unmatched rows from the second table. See RIGHT OUTER JOIN operation.
In all cases, you can specify additional restrictions on one or both of the tables being joined in outer join clauses or in the WHERE clause.
JOIN expressions and query optimization
For information on which types of joins are optimized, see Tuning Java DB.
INNER JOIN operation
An INNER JOIN is a JOIN operation that allows you to specify an explicit join clause.
Syntax
TableExpression [ INNER ] JOIN TableExpression { ON booleanExpression }
You can specify the join clause by specifying ON with a boolean expression.
The scope of expressions in the ON clause includes the current tables and any tables in outer query blocks to the current SELECT. In the following example, the ON clause refers to the current tables:
SELECT * FROM SAMP.EMPLOYEE INNER JOIN SAMP.STAFF ON EMPLOYEE.SALARY < STAFF.SALARY
The ON clause can reference tables not being joined and does not have to reference either of the tables being joined (though typically it does).
-- Join the EMP_ACT and EMPLOYEE tables -- select all the columns from the EMP_ACT table and -- add the employee's surname (LASTNAME) from the EMPLOYEE table -- to each row of the result SELECT SAMP.EMP_ACT.*, LASTNAME FROM SAMP.EMP_ACT JOIN SAMP.EMPLOYEE ON EMP_ACT.EMPNO = EMPLOYEE.EMPNO -- Join the EMPLOYEE and DEPARTMENT tables, -- select the employee number (EMPNO), -- employee surname (LASTNAME), -- department number (WORKDEPT in the EMPLOYEE table and DEPTNO in the -- DEPARTMENT table) -- and department name (DEPTNAME) -- of all employees who were born (BIRTHDATE) earlier than 1930. SELECT EMPNO, LASTNAME, WORKDEPT, DEPTNAME FROM SAMP.EMPLOYEE JOIN SAMP.DEPARTMENT ON WORKDEPT = DEPTNO AND YEAR(BIRTHDATE) < 1930 -- Another example of "generating" new data values, -- using a query which selects from a VALUES clause (which is an -- alternate form of a fullselect). -- This query shows how a table can be derived called "X" -- having 2 columns "R1" and "R2" and 1 row of data SELECT * FROM (VALUES (3, 4), (1, 5), (2, 6)) AS VALUESTABLE1(C1, C2) JOIN (VALUES (3, 2), (1, 2), (0, 3)) AS VALUESTABLE2(c1, c2) ON VALUESTABLE1.c1 = VALUESTABLE2.c1 -- This results in: -- C1 |C2 |C1 |2 -- ----------------------------------------------- -- 3 |4 |3 |2 -- 1 |5 |1 |2 -- List every department with the employee number and -- last name of the manager SELECT DEPTNO, DEPTNAME, EMPNO, LASTNAME FROM DEPARTMENT INNER JOIN EMPLOYEE ON MGRNO = EMPNO -- List every employee number and last name -- with the employee number and last name of their manager SELECT E.EMPNO, E.LASTNAME, M.EMPNO, M.LASTNAME FROM EMPLOYEE E INNER JOIN DEPARTMENT INNER JOIN EMPLOYEE M ON MGRNO = M.EMPNO ON E.WORKDEPT = DEPTNO
LEFT OUTER JOIN operation
A LEFT OUTER JOIN is one of the JOIN operations that allow you to specify a join clause. It preserves the unmatched rows from the first (left) table, joining them with a NULL row in the shape of the second (right) table.
Syntax
TableExpression LEFT [ OUTER ] JOIN TableExpression { ON booleanExpression }
The scope of expressions in either the ON clause includes the current tables and any tables in query blocks outer to the current SELECT. The ON clause can reference tables not being joined and does not have to reference either of the tables being joined (though typically it does).
Example 1
--match cities to countries in Asia SELECT CITIES.COUNTRY, CITIES.CITY_NAME, REGION FROM Countries LEFT OUTER JOIN Cities ON CITIES.COUNTRY_ISO_CODE = COUNTRIES.COUNTRY_ISO_CODE WHERE REGION = 'Asia' -- use the synonymous syntax, LEFT JOIN, to achieve exactly -- the same results as in the example above SELECT COUNTRIES.COUNTRY, CITIES.CITY_NAME,REGION FROM COUNTRIES LEFT JOIN CITIES ON CITIES.COUNTRY_ISO_CODE = COUNTRIES.COUNTRY_ISO_CODE WHERE REGION = 'Asia'
Example 2
-- Join the EMPLOYEE and DEPARTMENT tables, -- select the employee number (EMPNO), -- employee surname (LASTNAME), -- department number (WORKDEPT in the EMPLOYEE table -- and DEPTNO in the DEPARTMENT table) -- and department name (DEPTNAME) -- of all employees who were born (BIRTHDATE) earlier than 1930 SELECT EMPNO, LASTNAME, WORKDEPT, DEPTNAME FROM SAMP.EMPLOYEE LEFT OUTER JOIN SAMP.DEPARTMENT ON WORKDEPT = DEPTNO AND YEAR(BIRTHDATE) < 1930 -- List every department with the employee number and -- last name of the manager, -- including departments without a manager SELECT DEPTNO, DEPTNAME, EMPNO, LASTNAME FROM DEPARTMENT LEFT OUTER JOIN EMPLOYEE ON MGRNO = EMPNO
RIGHT OUTER JOIN operation
A RIGHT OUTER JOIN is one of the JOIN operations that allow you to specify a JOIN clause. It preserves the unmatched rows from the second (right) table, joining them with a NULL in the shape of the first (left) table. A LEFT OUTER JOIN B is equivalent to B RIGHT OUTER JOIN A, with the columns in a different order.
Syntax
TableExpression RIGHT [ OUTER ] JOIN TableExpression { ON booleanExpression }
The scope of expressions in the ON clause includes the current tables and any tables in query blocks outer to the current SELECT. The ON clause can reference tables not being joined and does not have to reference either of the tables being joined (though typically it does).
Example 1
-- get all countries and corresponding cities, including -- countries without any cities SELECT COUNTRIES.COUNTRY, CITIES.CITY_NAME FROM CITIES RIGHT OUTER JOIN COUNTRIES ON CITIES.COUNTRY_ISO_CODE = COUNTRIES.COUNTRY_ISO_CODE -- get all countries in Africa and corresponding cities, including -- countries without any cities SELECT COUNTRIES.COUNTRY, CITIES.CITY_NAME FROM CITIES RIGHT OUTER JOIN COUNTRIES ON CITIES.COUNTRY_ISO_CODE = COUNTRIES.COUNTRY_ISO_CODE WHERE Countries.region = 'Africa' -- use the synonymous syntax, RIGHT JOIN, to achieve exactly -- the same results as in the example above SELECT COUNTRIES.COUNTRY, CITIES.CITY_NAME FROM CITIES RIGHT JOIN COUNTRIES ON CITIES.COUNTRY_ISO_CODE = COUNTRIES.COUNTRY_ISO_CODE WHERE Countries.region = 'Africa'
Example 2
-- a TableExpression can be a joinOperation. Therefore -- you can have multiple join operations in a FROM clause -- List every employee number and last name -- with the employee number and last name of their manager SELECT E.EMPNO, E.LASTNAME, M.EMPNO, M.LASTNAME FROM EMPLOYEE E RIGHT OUTER JOIN DEPARTMENT RIGHT OUTER JOIN EMPLOYEE M ON MGRNO = M.EMPNO ON E.WORKDEPT = DEPTNO
SQL queries
Query
A query creates a virtual table based on existing tables or constants built into tables.
Syntax
{ ( Query ) | Query INTERSECT [ ALL | DISTINCT ] Query | Query EXCEPT [ ALL | DISTINCT ] Query | Query UNION [ ALL | DISTINCT ] Query | SelectExpression | VALUES Expression }
You can arbitrarily put parentheses around queries, or use the parentheses to control the order of evaluation of the INTERSECT, EXCEPT, or UNION operations. These operations are evaluated from left to right when no parentheses are present, with the exception of INTERSECT operations, which would be evaluated before any UNION or EXCEPT operations.
Duplicates in UNION, INTERSECT, and EXCEPT ALL results
The ALL and DISTINCT keywords determine whether duplicates are eliminated from the result of the operation. If you specify the DISTINCT keyword, then the result will have no duplicate rows. If you specify the ALL keyword, then there may be duplicates in the result, depending on whether there were duplicates in the input. DISTINCT is the default, so if you don't specify ALL or DISTINCT, the duplicates will be eliminated. For example, UNION builds an intermediate ResultSet with all of the rows from both queries and eliminates the duplicate rows before returning the remaining rows. UNION ALL returns all rows from both queries as the result.
Depending on which operation is specified, if the number of copies of a row in the left table is L and the number of copies of that row in the right table is R, then the number of duplicates of that particular row that the output table contains (assuming the ALL keyword is specified) is:
 
UNION: ( L + R ).
 
EXCEPT: the maximum of ( L – R ) and 0 (zero).
 
INTERSECT: the minimum of L and R.
Examples
-- a Select expression SELECT * FROM ORG -- a subquery SELECT * FROM (SELECT CLASS_CODE FROM CL