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.
• | 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 Java Database Connectivity (JDBC) API. | |
• | Setting attributes for the database connection URL Information
about the supported attributes to Derby's
JDBC database connection URL. | |
• | Derby property reference Information about Derby
properties. | |
• | J2EE Compliance: Java Transaction API and javax.sql Interfaces Information
about Derby's support for the
Java EE platform, in particular support for the Java Transaction API and the
JDBC API. | |
• | Derby API Notes
about proprietary APIs for Derby. | |
• | Supported territories Territories
supported by Derby. | |
• | Derby limitations Limitations
of Derby. |
• | 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:
| |
• | 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. |
"A.B"
"A"."B"
• | 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) |
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.SELECT c11 AS col1, c12 AS col2, c13 FROM t1 FOR UPDATE of c11,c13
-- C.Country is a column-Name qualified with a -- correlation-Name. SELECT C.Country FROM APP.Countries C
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.SELECT c11 AS col1, c12 AS col2, c13 FROM t1 FOR UPDATE of c11,c13
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.
• | 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 or VARCHAR FOR BIT DATA 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 |
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 } }
Simple-column-Name [ DataType ] [ Column-level-constraint ]* [ [ WITH ] DEFAULT DefaultConstantExpression | generation-clause ]
column-Name SET DATA TYPE VARCHAR(integer) | column-Name SET DATA TYPE VARCHAR FOR BIT DATA(integer) | column-name SET INCREMENT BY integer-constant | column-name RESTART WITH integer-constant | column-name [ NOT ] NULL | column-name [ WITH | SET ] DEFAULT default-value | column-name DROP DEFAULT
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
INSERT INTO tauto VALUES (3,3) INSERT INTO tauto VALUES (4,4) INSERT INTO tauto VALUES (5,5)
ALTER TABLE tauto ALTER COLUMN i RESTART WITH 6
• | 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. |
• | Increasing the width of an existing VARCHAR or VARCHAR FOR BIT DATA 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.
You can use DEFAULT default-value to change a column default. To disable a
previously set default, use DROP DEFAULT (alternatively, you can specify NULL as
the default-value). |
-- 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 ALTER TABLE Employees ALTER COLUMN Salary DROP DEFAULT
CREATE FUNCTION function-name ( [ FunctionParameter [, FunctionParameter] ] * ) RETURNS ReturnDataType [ FunctionElement ] *
{ | LANGUAGE { JAVA } | DeterministicCharacteristic | EXTERNAL NAME string | PARAMETER STYLE ParameterStyle | { NO SQL | CONTAINS SQL | READS SQL DATA } | { RETURNS NULL ON NULL INPUT | CALLED ON NULL INPUT } }
The External Name cannot have any extraneous spaces.class_name.method_name
DETERMINISTIC | NOT DETERMINISTIC
• | LANGUAGE | |
• | PARAMETER STYLE | |
• | EXTERNAL NAME |
CREATE [UNIQUE] INDEX index-Name ON table-Name ( Simple-column-Name [ ASC | DESC ] [ , Simple-column-Name [ ASC | DESC ]] * )
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);
CREATE PROCEDURE procedure-Name ( [ ProcedureParameter [, ProcedureParameter] ] * ) [ ProcedureElement ] *
{ | [ DYNAMIC ] RESULT SETS INTEGER | LANGUAGE { JAVA } | DeterministicCharacteristic | EXTERNAL NAME string | PARAMETER STYLE JAVA | { NO SQL | MODIFIES SQL DATA | CONTAINS SQL | READS SQL DATA } }
The External Name cannot have any extraneous spaces.class_name.method_name
DETERMINISTIC | NOT DETERMINISTIC
CREATE SCHEMA { [ schemaName AUTHORIZATION user-name ] | [ schemaName ] | [ AUTHORIZATION user-name ] }
with a user name other than the current user name. See "derby.database.sqlAuthorization" for information about the derby.database.sqlAuthorization property.AUTHORIZATION user-name
CREATE SCHEMA FLIGHTS AUTHORIZATION anita
CREATE SCHEMA EMP
CREATE SCHEMA AUTHORIZATION takumi
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))
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.CREATE SYNONYM synonym-Name FOR { view-Name | table-Name }
• | INSERT | |
• | SELECT | |
• | REFERENCES | |
• | TRIGGER | |
• | UPDATE |
CREATE TABLE table-Name { ( {column-definition | Table-level constraint} [ , {column-definition | Table-level constraint} ] * ) | [ ( column-name [ , column-name ] * ) ] AS query-expression WITH NO DATA }
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));
-- 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;
Simple-column-Name [ DataType ] [ Column-level-constraint ]* [ [ WITH ] DEFAULT DefaultConstantExpression | generated-column-spec | generation-clause ] [ Column-level-constraint ]*
DefaultConstantExpression: NULL | CURRENT { SCHEMA | SQLID } | USER | CURRENT_USER | SESSION_USER | CURRENT_ROLE | DATE | TIME | TIMESTAMP | CURRENT DATE | CURRENT_DATE | CURRENT TIME | CURRENT_TIME | CURRENT TIMESTAMP | CURRENT_TIMESTAMP | literal
• | If you specify USER, CURRENT_USER, SESSION_USER, or CURRENT_ROLE, 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 { ALWAYS | BY DEFAULT } AS IDENTITY [ ( START WITH IntegerConstant [ ,INCREMENT BY IntegerConstant] ) ] ] ]
• | SMALLINT | |
• | INT | |
• | BIGINT |
Automatically generated values in a GENERATED ALWAYS identity column are unique. Creating an identity column does not create an index on the column.create table greetings (i int generated always as identity, ch char(50)); insert into greetings values (DEFAULT, 'hello'); 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.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');
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) |
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');
GENERATED ALWAYS AS ( value-expression )
• | The functions must not read or write SQL data. | |||||||||||||||||||||||||
• | The functions must have been declared DETERMINISTIC. | |||||||||||||||||||||||||
• | The functions must not invoke any of the following possibly
non-deterministic system functions:
|
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 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 | |
• | UPDATE | |
• | DELETE |
REFERENCING OLD AS DELETEDROW
DELETE FROM HotelAvailability WHERE hotel_id = DELETEDROW.hotel_id
REFERENCING OLD_TABLE AS DeletedHotels
DELETE FROM HotelAvailability WHERE hotel_id IN (SELECT hotel_id FROM DeletedHotels)
• | 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. |
• | 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 NEW variable of a Before trigger cannot reference a generated column.
|
• | 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. |
-- 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;
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 ] }
CREATE VIEW view-Name [ ( Simple-column-Name [, Simple-column-Name] * ) ] AS Query
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;
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;
SELECT * FROM V1
• | 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. |
DECLARE GLOBAL TEMPORARY TABLE table-Name { column-definition [ , column-definition ] * } [ ON COMMIT {DELETE | PRESERVE} ROWS ] NOT LOGGED [ON ROLLBACK DELETE ROWS]
• | BIGINT | |
• | CHAR | |
• | DATE | |
• | DECIMAL | |
• | DOUBLE | |
• | DOUBLE PRECISION | |
• | FLOAT | |
• | INTEGER | |
• | NUMERIC | |
• | REAL | |
• | SMALLINT | |
• | TIME | |
• | TIMESTAMP | |
• | VARCHAR |
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.
• | 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 |
• | ALTER TABLE | |
• | CREATE INDEX | |
• | CREATE SYNONYM | |
• | CREATE TRIGGER | |
• | CREATE VIEW | |
• | GRANT | |
• | LOCK TABLE | |
• | RENAME | |
• | REVOKE |
• | 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 |
• | BLOB | |
• | CHAR FOR BIT DATA | |
• | CLOB | |
• | LONG VARCHAR | |
• | LONG VARCHAR FOR BIT DATA | |
• | VARCHAR FOR BIT DATA | |
• | XML |
{ DELETE FROM table-Name [[AS] correlation-Name] [WHERE clause] | DELETE FROM table-Name WHERE CURRENT OF }
DELETE FROM SAMP.IN_TRAY stmt.executeUpdate("DELETE FROM SAMP.IN_TRAY WHERE CURRENT OF " + resultSet.getCursorName());
DROP FUNCTION function-name
• | If no function with the indicated name exists in the named or implied schema
(the error is SQLSTATE 42704) | |
• | If there is more than one specific instance of the function in the named or
implied schema | |
• | If you try to drop a user-defined function that is invoked in the
generation-clause of a generated column | |
• | If you try to drop a user-defined function that is invoked in a view |
DROP PROCEDURE procedure-Name
DROP SCHEMA schemaName RESTRICT
• | 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. |
DELETE | INSERT | REFERENCES [column list] | SELECT [column list] | TRIGGER | UPDATE [column list]
{ AuthorizationIdentifier | roleName | PUBLIC } [, { AuthorizationIdentifier | roleName | PUBLIC } ] *
GRANT SELECT ON TABLE t TO maria,harry
GRANT UPDATE, TRIGGER ON TABLE t TO anita,zhi
GRANT SELECT ON TABLE s.v to PUBLIC
GRANT EXECUTE ON PROCEDURE p TO george
GRANT purchases_reader_role TO george,maria
GRANT SELECT ON TABLE t TO purchases_reader_role
INSERT INTO table-Name [ (Simple-column-Name [ , Simple-column-Name]* ) ] Query
• | ||
• | 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. The DEFAULT literal is the only value which you can directly
insert into a generated column. | |
• | UNION expressions |
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)
• | Avoid the overhead of multiple row locks on a table (in other words, user-initiated
lock escalation) | |
• | Avoid deadlocks |
LOCK TABLE table-Name IN { SHARE | EXCLUSIVE } MODE
LOCK TABLE Flights IN SHARE MODE; SELECT * FROM Flights WHERE orig_airport > 'OOO';
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');
LOCK TABLE Maps IN EXCLUSIVE MODE; SELECT MAX(map_id) + 1 FROM Maps; -- INSERT INTO Maps . . .
RENAME COLUMN EMPLOYEE.MANAGER TO SUPERVISOR
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
RENAME TABLE table-Name TO new-Table-Name
• | 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). |
REVOKE privilege-type ON [ TABLE ] { table-Name | view-Name } FROM grantees
REVOKE EXECUTE ON { FUNCTION | PROCEDURE } routine-designator FROM grantees RESTRICT
DELETE | INSERT | REFERENCES [column list] | SELECT [column list] | TRIGGER | UPDATE [column list]
{ AuthorizationIdentifier | roleName | PUBLIC } [,{ AuthorizationIdentifier | roleName | PUBLIC } ] *
REVOKE SELECT ON TABLE t FROM maria,harry
REVOKE UPDATE, TRIGGER ON TABLE t FROM anita,zhi
REVOKE SELECT ON TABLE s.v FROM PUBLIC
REVOKE UPDATE (c1,c2) ON TABLE s.v FROM PUBLIC
REVOKE EXECUTE ON PROCEDURE p FROM george RESTRICT
REVOKE purchases_reader_role FROM george,maria
REVOKE SELECT ON TABLE t FROM purchases_reader_role
• | The privileges granted to that role | |
• | The union of privileges of roles contained in that role (for a definition of
role containment, see "Syntax for roles" in GRANT statement)
|
• | The privileges granted to the current user | |
• | The privileges granted to PUBLIC | |
• | The privileges identified by the current role, if set |
SET ROLE reader;
// These examples show the use of SET ROLE in JDBC statements. // The case normal form is visible in the SYS.SYSROLES system table. stmt.execute("SET ROLE admin"); -- case normal form: ADMIN stmt.execute("SET ROLE \"admin\""); -- case normal form: admin stmt.execute("SET ROLE none"); -- special case PreparedStatement ps = conn.prepareStatement("SET ROLE ?"); ps.setString(1, " admin "); -- on execute: case normal form: ADMIN ps.setString(1, "\"admin\""); -- on execute: case normal form: admin ps.setString(1, "none"); -- on execute: syntax error ps.setString(1, "\"none\""); -- on execute: case normal form: none
SET [CURRENT] SCHEMA [=] { schemaName| USER | ? | '<string-constant>' } | SET CURRENT SQLID [=] { schemaName| USER | ? | '<string-constant>' }
-- 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
Query [ORDER BY clause] [result offset clause] [fetch first clause] [FOR UPDATE clause] [WITH {RR|RS|CS|UR}]
-- 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
• | 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:
| ||||||||||||||||
• | The FROM clause in the underlying Query must not have:
| ||||||||||||||||
• | If the underlying Query has a WHERE clause, the WHERE clause must not
have subqueries. |
{ 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 }
Expression | DEFAULT
-- 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'
• | 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. |
• | 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. |
• | 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. |
• | Dynamic parameters (?) | |
• | Date/Time Functions (CURRENT_DATE, CURRENT_TIME, CURRENT_TIMESTAMP) | |
• | Subqueries | |
• | User Functions (such as USER, SESSION_USER, CURRENT_USER) |
• | 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. |
-- 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 );
{ NOT NULL | [ [CONSTRAINT constraint-Name] { CHECK (searchCondition) | { PRIMARY KEY | UNIQUE | REFERENCES clause } } }
[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 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}]
FOR { READ ONLY | FETCH ONLY | UPDATE [ OF Simple-column-Name [ , Simple-column-Name]* ] }
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 column-Name [ , column-Name ] *
-- 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 searchCondition
-- SELECT COUNT(*) -- FROM SAMP.STAFF -- GROUP BY ID -- HAVING SALARY > 15000
-- 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 { column-Name | ColumnPosition | Expression } [ ASC | DESC ] [ , column-Name | ColumnPosition | Expression [ ASC | DESC ] ] *
• | 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. |
SELECT CITY_NAME, COUNTRY AS NATION FROM CITIES ORDER BY NATION
OFFSET integer-literal {ROW | ROWS}
FETCH { FIRST | NEXT } [integer-literal] {ROW | ROWS} ONLY
-- Fetch the first row of T SELECT * FROM T FETCH FIRST ROW ONLY -- Sort T using column I, then fetch rows 11 through 20 of the sorted -- rows (inclusive) SELECT * FROM T ORDER BY I OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY -- Skip the first 100 rows of T -- If the table has fewer than 101 records, an empty result set is -- returned SELECT * FROM T OFFSET 100 ROWS
WHERE Boolean expression
-- 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
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");
• | ||
• | ||
• | UPDATE statement (SET
portion) | |
• | ||
• |
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. |
• | BIGINT | |
• | DECIMAL | |
• | DOUBLE PRECISION | |
• | INTEGER | |
• | REAL | |
• | SMALLINT |
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. |
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 . |
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. |
SELECT [ DISTINCT | ALL ] SelectItem [ , SelectItem ]* FROM clause [ WHERE clause] [ GROUP BY clause ] [ HAVING clause ]
{ * | { table-Name | correlation-Name } .* | Expression [AS Simple-column-Name] }
-- 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
• | FROM clause | |
• | WHERE clause | |
• | GROUP BY (or implicit GROUP BY) | |
• | HAVING clause | |
• | SELECT clause |
VALUES CURRENT_TIMESTAMP
• | 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
• | 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. |
{table-Name |view-Name | TableFunctionInvocation} [ [ AS ] correlation-Name [ (Simple-column-Name [ , Simple-column-Name]* ) ] ] ]
• | 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) |
{ VALUES ( Value {, Value }* ) [ , ( Value {, Value }* ) ]* | VALUES Value [ , Value ]* }
Expression | DEFAULT
-- 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)
• | (), ?, 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 |
Operator | Explanation and Example | Syntax |
AND, OR, NOT | Evaluate any operand(s) that are boolean expressions
|
|
Comparisons | <, =, >, <=, >=, <> are applicable to
all of the built-in types.
|
|
IS NULL, IS NOT NULL | Test whether the result of an expression is null or not.
|
|
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.
To
treat % or _ as constant characters, escape the character with an optional
escape character, which you specify with the ESCAPE clause.
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. |
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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();
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.
| |
2.
| Use as the second or third operand of BETWEEN is allowed. Type is assumed
to be the type of the left operand.
| |
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.
| |
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.
| |
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.
| |
6.
| Use in a CAST is always permitted. This gives the dynamic parameter a
type.
| |
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.)
| |
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.
| |
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).
| |
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.
| |
11.
| A ? parameter in a comparison with a subquery takes its type from the
expression being selected by the subquery. For example:
| |
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.
| |
13.
| Dynamic parameters are allowed as the operand of the unary operators -
or +. For example:
| |
14.
| LENGTH allow a dynamic parameter. The type is assumed to be a maximum
length VARCHAR type.
| |
15.
| Qualified comparisons.
| |
16.
| A dynamic parameter is allowed as the left operand of an IS expression
and is assumed to be a boolean. |
JOIN Operation
• | 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. |
TableExpression [ INNER ] JOIN TableExpression { ON booleanExpression }
SELECT * FROM SAMP.EMPLOYEE INNER JOIN SAMP.STAFF ON EMPLOYEE.SALARY < STAFF.SALARY
-- 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
TableExpression LEFT [ OUTER ] JOIN TableExpression { ON booleanExpression }
--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'
-- 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
TableExpression RIGHT [ OUTER ] JOIN TableExpression { ON booleanExpression }
-- 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'
-- 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
{ ( Query ) | Query INTERSECT [ ALL | DISTINCT ] Query | Query EXCEPT [ ALL | DISTINCT ] Query | Query UNION [ ALL | DISTINCT ] Query | SelectExpression | VALUES Expression }
• | UNION: ( L + R ). | |
• | EXCEPT: the maximum of ( L – R ) and 0 (zero). | |
• | INTERSECT: the minimum of L and R. |
-- a Select expression SELECT * FROM ORG -- a subquery SELECT * FROM (SELECT CLASS_CODE FROM CL_SCHED) AS CS -- a subquery SELECT * FROM (SELECT CLASS_CODE FROM CL_SCHED) AS CS (CLASS_CODE) -- a UNION -- returns all rows from columns DEPTNUMB and MANAGER -- in table ORG -- and (1,2) and (3,4) -- DEPTNUMB and MANAGER are smallint columns SELECT DEPTNUMB, MANAGER FROM ORG UNION ALL VALUES (1,2), (3,4) -- a values expression VALUES (1,2,3) -- List the employee numbers (EMPNO) of all employees in the EMPLOYEE table -- whose department number (WORKDEPT) either begins with 'E' or -- who are assigned to projects in the EMP_ACT table -- whose project number (PROJNO) equals 'MA2100', 'MA2110', or 'MA2112' SELECT EMPNO FROM EMPLOYEE WHERE WORKDEPT LIKE 'E%' UNION SELECT EMPNO FROM EMP_ACT WHERE PROJNO IN('MA2100', 'MA2110', 'MA2112') -- Make the same query as in the previous example -- and "tag" the rows from the EMPLOYEE table with 'emp' and -- the rows from the EMP_ACT table with 'emp_act'. -- Unlike the result from the previous example, -- this query may return the same EMPNO more than once, -- identifying which table it came from by the associated "tag" SELECT EMPNO, 'emp' FROM EMPLOYEE WHERE WORKDEPT LIKE 'E%' UNION SELECT EMPNO, 'emp_act' FROM EMP_ACT WHERE PROJNO IN('MA2100', 'MA2110', 'MA2112') -- Make the same query as in the previous example, -- only use UNION ALL so that no duplicate rows are eliminated SELECT EMPNO FROM EMPLOYEE WHERE WORKDEPT LIKE 'E%' UNION ALL SELECT EMPNO FROM EMP_ACT WHERE PROJNO IN('MA2100', 'MA2110', 'MA2112') -- Make the same query as in the previous example, -- only include an additional two employees currently not in any table and -- tag these rows as "new" SELECT EMPNO, 'emp' FROM EMPLOYEE WHERE WORKDEPT LIKE 'E%' UNION SELECT EMPNO, 'emp_act' FROM EMP_ACT WHERE PROJNO IN('MA2100', 'MA2110', 'MA2112') UNION VALUES ('NEWAAA', 'new'), ('NEWBBB', 'new')
-- avg always returns a single value, so the subquery is -- a ScalarSubquery SELECT NAME, COMM FROM STAFF WHERE EXISTS (SELECT AVG(BONUS + 800) FROM EMPLOYEE WHERE COMM < 5000 AND EMPLOYEE.LASTNAME = UPPER(STAFF.NAME) ) -- Introduce a way 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 R1,R2 FROM (VALUES('GROUP 1','GROUP 2')) AS X(R1,R2)
• | as a TableExpression in
a FROM clause | |
• | with EXISTS, IN, or quantified comparisons. |
-- a subquery used as a TableExpression in a FROM clause SELECT VirtualFlightTable.flight_ID FROM (SELECT flight_ID, orig_airport, dest_airport FROM Flights WHERE (orig_airport = 'SFO' OR dest_airport = 'SCL') ) AS VirtualFlightTable -- a subquery (values expression) used as a TableExpression -- in a FROM clause SELECT mycol1 FROM (VALUES (1, 2), (3, 4)) AS mytable (mycol1, mycol2) -- a subquery used with EXISTS SELECT * FROM Flights WHERE EXISTS (SELECT * FROM Flights WHERE dest_airport = 'SFO' AND orig_airport = 'GRU') -- a subquery used with IN SELECT flight_id, segment_number FROM Flights WHERE flight_id IN (SELECT flight_ID FROM Flights WHERE orig_airport = 'SFO' OR dest_airport = 'SCL') -- a subquery used with a quantified comparison SELECT NAME, COMM FROM STAFF WHERE COMM > (SELECT AVG(BONUS + 800) FROM EMPLOYEE WHERE COMM < 5000)
Function Name | All Types | Numeric Built-in Data Types |
COUNT | X | X |
MIN | X | |
MAX | X | |
AVG | X | |
SUM | X |
• | A SelectItem in a SelectExpression. | |
• | ||
• | An ORDER BY clause (using an alias
name) if the aggregate appears in the result of the relevant query block.
That is, an alias for an aggregate is permitted in an ORDER BY clause if
and only if the aggregate appears in a SelectItem in a SelectExpression. |
-- not valid SELECT MIN(flying_time), flight_id FROM Flights
SELECT c1 FROM t1 GROUP BY c1 HAVING c2 > (SELECT t2.x FROM t2 WHERE t2.y = SUM(t1.c3))
• | If the specified number is NULL, the result of this function is NULL. | |
• | If the absolute value of the specified number is greater than 1, an exception
is returned that indicates that the value is out of range (SQL state 22003). |
• | If the specified number is NULL, the result of this function is NULL. | |
• | If the specified number is zero (0), the result of this function is zero
with the same sign as the specified number. | |
• | If the absolute value of the specified number is greater than 1, an exception
is returned that indicates that the value is out of range (SQL state 22003). |
• | If the specified number is NULL, the result of this function is NULL. | |
• | If the specified number is zero (0), the result of this function is zero
with the same sign as the specified number. |
• | If either argument is NULL, the result of the function is NULL. | |
• | If the first argument is zero and the second argument is positive, the
result of the function is zero. | |
• | If the first argument is zero and the second argument is negative, the
result of the function is the double value closest to pi. | |
• | If the first argument is positive and the second argument is zero, the
result is the double value closest to pi/2. | |
• | If the first argument is negative and the second argument is zero, the
result is the double value closest to -pi/2. |
AVG ( [ DISTINCT | ALL ] Expression )
SELECT AVG (DISTINCT flying_time), SUM (DISTINCT miles) FROM Flights
SELECT AVG(c1) FROM (VALUES (1), (1), (1), (1), (2)) AS myTable (c1)
SELECT AVG(CAST (c1 AS DOUBLE PRECISION)) FROM (VALUES (1), (1), (1), (1), (2)) AS myTable (c1)
BIGINT (CharacterExpression | NumericExpression )
CASE WHEN booleanExpression THEN thenExpression [ WHEN booleanExpression THEN thenExpression ]... ELSE elseExpression END
-- returns 3 VALUES CASE WHEN 1=1 THEN 3 ELSE 4 END
-- returns 7 VALUES CASE WHEN 1 = 2 THEN 3 WHEN 4 = 5 THEN 6 ELSE 7 END
CAST ( [ Expression | NULL | ? ] AS Datatype)
Types |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
SMALLINT | Y | Y | Y | Y | Y | Y | Y | Y | - | - | - | - | - | - | - | - | - | - | - |
INTEGER | Y | Y | Y | Y | Y | Y | Y | Y | - | - | - | - | - | - | - | - | - | - | - |
BIGINT | Y | Y | Y | Y | Y | Y | Y | Y | - | - | - | - | - | - | - | - | - | - | - |
DECIMAL | Y | Y | Y | Y | Y | Y | Y | Y | - | - | - | - | - | - | - | - | - | - | - |
REAL | Y | Y | Y | Y | Y | Y | Y | - | - | - | - | - | - | - | - | - | - | - | - |
DOUBLE | Y | Y | Y | Y | Y | Y | Y | - | - | - | - | - | - | - | - | - | - | - | - |
FLOAT | Y | Y | Y | Y | Y | Y | Y | - | - | - | - | - | - | - | - | - | - | - | - |
CHAR | Y | Y | Y | Y | - | - | - | Y | Y | Y | - | - | - | Y | - | Y | Y | Y | - |
VARCHAR | Y | Y | Y | Y | - | - | - | Y | Y | Y | - | - | - | Y | - | Y | Y | Y | - |
LONG VARCHAR | - | - | - | - | - | - | - | Y | Y | Y | - | - | - | Y | - | - | - | - | - |
CHAR FOR BIT DATA | - | - | - | - | - | - | - | - | - | - | Y | Y | Y | Y | Y | - | - | - | - |
VARCHAR FOR BIT DATA | - | - | - | - | - | - | - | - | - | - | Y | Y | Y | Y | Y | - | - | - | - |
LONG VARCHAR FOR BIT DATA | - | - | - | - | - | - | - | - | - | - | Y | Y | Y | Y | Y | - | - | - | - |
CLOB | - | - | - | - | - | - | - | Y | Y | Y | - | - | - | Y | - | - | - | - | - |
BLOB | - | - | - | - | - | - | - | - | - | - | - | - | - | - | Y | - | - | - | - |
DATE | - | - | - | - | - | - | - | Y | Y | - | - | - | - | - | - | Y | - | - | - |
TIME | - | - | - | - | - | - | - | Y | Y | - | - | - | - | - | - | - | Y | - | - |
TIMESTAMP | - | - | - | - | - | - | - | Y | Y | - | - | - | - | - | - | Y | Y | Y | - |
XML | - | - | - | - | - | - | - | - | - | - | - | - | - | - | - | - | - | - | Y |
SELECT CAST (miles AS INT) FROM Flights -- convert timestamps to text INSERT INTO mytable (text_column) VALUES (CAST (CURRENT_TIMESTAMP AS VARCHAR(100))) -- you must cast NULL as a data type to use it SELECT airline FROM Airlines UNION ALL VALUES (CAST (NULL AS CHAR(2))) -- cast a double as a decimal SELECT CAST (FLYING_TIME AS DECIMAL(5,2)) FROM FLIGHTS -- cast a SMALLINT to a BIGINT VALUES CAST (CAST (12 as SMALLINT) as BIGINT)
• | If the specified number is NULL, the result of these functions is NULL. | |
• | If the specified number is equal to a mathematical integer, the result
of these functions is the same as the specified number. | |
• | If the specified number is zero (0), the result of these functions is
zero. | |
• | If the specified number is less than zero but greater than -1.0, then
the result of these functions is zero. |
• | A character string, if the first argument is any type of character string. | |
• | A datetime value, if the first argument is a date, time, or timestamp. | |
• | A decimal number, if the first argument is a decimal number. | |
• | A double-precision floating-point number, if the first argument is a DOUBLE
or REAL. | |
• | An integer number, if the first argument is a SMALLINT, INTEGER, or BIGINT. |
CHAR (CharacterExpression [, integer] )
CHAR (IntegerExpression )
• | If the first argument is a small integer: The length of the result is
6. If the number of characters in the result is less than 6, then the result
is padded on the right with blanks to length 6. | |
• | If the first argument is a large integer: The length of the result is
11. If the number of characters in the result is less than 11, then the result
is padded on the right with blanks to length 11. | |
• | If the first argument is a big integer: The length of the result is 20.
If the number of characters in the result is less than 20, then the result
is padded on the right with blanks to length 20. |
CHAR (DatetimeExpression )
• | date: The result is the character representation of the date. The
length of the result is 10. | |
• | time: The result is the character representation of the time. The
length of the result is 8. | |
• | timestamp: The result is the character string representation of
the timestamp. The length of the result is 26. |
CHAR (DecimalExpression )
{ { CharacterExpression || CharacterExpression } | { BitExpression || BitExpression } }
• | If the specified number is NULL, the result of this function is NULL. |
• | If the specified number is NULL, the result of this function is NULL. | |
• | If the specified number is zero (0), the result of this function is one (1.0). |
• | If the specified number is NULL, the result of this function is NULL. |
COUNT ( [ DISTINCT | ALL ] Expression )
-- query not allowed SELECT COUNT (DISTINCT flying_time), SUM (DISTINCT miles) FROM Flights
-- Set the name column default to the current schema: CREATE TABLE mytable (id int, name VARCHAR(128) DEFAULT CURRENT SQLID) -- Inserts default value of current schema value into the table: INSERT INTO mytable(id) VALUES (1) -- Returns the rows with the same name as the current schema: SELECT name FROM mytable WHERE name = CURRENT SCHEMA
• | If the argument is a date, timestamp, or valid string representation of
a date or timestamp: The result is the date part of the value. | |
• | If the argument is a number: The result is the date that is n-1 days after
January 1, 0001, where n is the integral part of the number. | |
• | If the argument is a string with a length of 7: The result is the date
represented by the string. |
• | number if the argument is a numeric expression. | |
• | character string representation of a number if the argument is a string
expression. |
DOUBLE [PRECISION] (NumericExpression )
DOUBLE (StringExpression )
• | If the specified number is NULL, the result of this function is NULL. | |
• | If the specified number is equal to a mathematical integer, the result
of this function is the same as the specified number. | |
• | If the specified number is zero (0), the result of this function is zero. |
• | A single row INSERT statement with a VALUES clause for a table without
an identity column | |
• | A multiple row INSERT statement with a VALUES clause | |
• | An INSERT statement with a fullselect |
ij> create table t1(c1 int generated always as identity, c2 int); 0 rows inserted/updated/deleted ij> insert into t1(c2) values (8); 1 row inserted/updated/deleted ij> values IDENTITY_VAL_LOCAL(); 1 ------------------------------- 1 1 row selected ij> select IDENTITY_VAL_LOCAL()+1, IDENTITY_VAL_LOCAL()-1 from t1; 1 |2 ------------------------------------------------------------------- 2 |0 1 row selected ij> insert into t1(c2) values (IDENTITY_VAL_LOCAL()); 1 row inserted/updated/deleted ij> select * from t1; C1 |C2 ------------------------------- 1 |8 2 |1 2 rows selected ij> values IDENTITY_VAL_LOCAL(); 1 ------------------------------- 2 1 row selected ij> insert into t1(c2) values (8), (9); 2 rows inserted/updated/deleted ij> -- multi-values insert, return value of the function should not change values IDENTITY_VAL_LOCAL(); 1 ------------------------------- 2 1 row selected ij> select * from t1; C1 |C2 ------------------------------- 1 |8 2 |1 3 |8 4 |9 4 rows selected ij> insert into t1(c2) select c1 from t1; 4 rows inserted/updated/deleted -- insert with sub-select, return value should not change ij> values IDENTITY_VAL_LOCAL(); 1 ------------------------------- 2 1 row selected ij> select * from t1; C1 |C2 ------------------------------- 1 |8 2 |1 3 |8 4 |9 5 |1 6 |2 7 |3 8 |4 8 rows selected
INT[EGER] (NumericExpression | CharacterExpression )
SELECT INTEGER (SALARY / EDLEVEL), SALARY, EDLEVEL, EMPNO FROM EMPLOYEE ORDER BY 1 DESC
LCASE or LOWER ( CharacterExpression )
• | If the specified number is NULL, the result of these functions is NULL. | |
• | If the specified number is zero or a negative number, an exception is
returned that indicates that the value is out of range (SQL state 22003). |
• | If the specified number is NULL, the result of this function is NULL. | |
• | If the specified number is zero or a negative number, an exception is
returned that indicates that the value is out of range (SQL state 22003). |
• | The first CharacterExpression specifies the string to
search for. | |
• | The second CharacterExpression specifies
the string in which to search. | |
• | The third argument is the startPosition, and specifies
the position in the second argument at which the search is
to start. If the third argument is not provided, the LOCATE
function starts its search at the beginning of the second
argument. |
-- returns 2, since 'love' is found at index position 2: VALUES LOCATE('love', 'clover')
-- returns 0, since 'stove' is not found in 'clover': VALUES LOCATE('stove', 'clover')
-- returns 5 (note the start position is 4): VALUES LOCATE('iss', 'Mississippi', 4)
-- returns 1, because the empty string is a special case: VALUES LOCATE('', 'ABC')
-- returns 0, because 'AAA' is not found in '': VALUES LOCATE('AAA', '')
-- returns 3 VALUES LOCATE('', '', 3)
MAX ( [ DISTINCT | ALL ] Expression )
SELECT COUNT (DISTINCT flying_time), MAX (DISTINCT miles) FROM Flights
-- find the latest date in the FlightAvailability table SELECT MAX (flight_date) FROM FlightAvailability -- find the longest flight originating from each airport, -- but only when the longest flight is over 10 hours SELECT MAX(flying_time), orig_airport FROM Flights GROUP BY orig_airport HAVING MAX(flying_time) > 10
MIN ( [ DISTINCT | ALL ] Expression )
SELECT COUNT (DISTINCT flying_time), MIN (DISTINCT miles) FROM Flights
mod(integer_type, integer_type)
• | SMALLINT if both arguments are SMALLINT. | |
• | INTEGER if one argument is INTEGER and the other is INTEGER or SMALLINT. | |
• | BIGINT if one integer is BIGINT and the other argument is BIGINT, INTEGER,
or SMALLINT. |
• | Derby does not currently allow the named or unnamed window specification to be specified in the OVER() clause, but requires an empty parenthesis. This means the function is evaluated over the entire result set. | |
• | The ROW_NUMBER function cannot currently be used in a WHERE clause. | |
• | Derby does not currently support ORDER BY in subqueries, so there is currently no way to guarantee the order of rows in the SELECT subquery. An optimizer override can be used to force the optimizer to use an index ordered on the desired column(s) if ordering is a firm requirement. |
• | If the specified number is NULL, the result of this function is NULL. | |
• | If the specified number is zero (0), the result of this function is zero (0). | |
• | If the specified number is greater than zero (0), the result of this function is plus one (+1). | |
• | If the specified number is less than zero (0), the result of this function is minus one (-1). |
• | If the specified number is NULL, the result of this function is NULL. | |
• | If the specified number is zero (0), the result of this function is zero. |
• | If the specified number is NULL, the result of this function is NULL. | |
• | If the specified number is zero (0), the result of this function is zero. |
SMALLINT ( NumericExpression | CharacterExpression )
SUBSTR({ CharacterExpression }, StartPosition [, LengthOfString ] )
The result is 'ello'.VALUES SUBSTR('hello', 2)
The result is 'he'.VALUES SUBSTR('hello',1,2)
SUM ( [ DISTINCT | ALL ] Expression )
SELECT AVG (DISTINCT flying_time), SUM (DISTINCT miles) FROM Flights
• | If the specified number is NULL, the result of this function is NULL. | |
• | If the specified number is zero (0), the result of this function is zero. |
• | If the specified number is NULL, the result of this function is NULL. | |
• | If the specified number is zero (0), the result of this function is zero. |
• | If the argument is a time: The result is that time. | |
• | If the argument is a timestamp: The result is the time part of the timestamp. | |
• | If the argument is a string: The result is the time represented by the
string. |
• | If only one argument is specified: It must be a timestamp, a valid string
representation of a timestamp, or a string of length 14 that is not a CLOB,
LONG VARCHAR, or XML value. A string of length 14 must be a string of digits
that represents a valid date and time in the form yyyyxxddhhmmss, where yyyy is
the year, xx is the month, dd is the day, hh is the hour, mm is
the minute, and ss is the seconds. | |
• | If both arguments are specified: The first argument must be a date or
a valid string representation of a date and the second argument must be a
time or a valid string representation of a time. |
• | If both arguments are specified: The result is a timestamp with the date
specified by the first argument and the time specified by the second argument.
The microsecond part of the timestamp is zero. | |
• | If only one argument is specified and it is a timestamp: The result is
that timestamp. | |
• | If only one argument is specified and it is a string: The result is the
timestamp represented by that string. If the argument is a string of length
14, the timestamp has a microsecond part of zero. |
SELECT TIMESTAMP(col2, col3) FROM records_table
VALUES TIMESTAMP('1998-12-25', '17.12.30'); 1 -------------------------- 1998-12-25 17:12:30.0
TRIM( [ trimOperands ] trimSource)
trimOperands ::= { trimType [ trimCharacter ] FROM | trimCharacter FROM } trimType ::= { LEADING | TRAILING | BOTH } trimCharacter ::= CharacterExpression trimSource ::= CharacterExpression
• | a character string whose length is exactly one, or. | |
• | NULL |
• | If trimType is LEADING, the result will be the trimSource value with all leading occurrences of trimChar removed. | |
• | If trimType is TRAILING, the result will be the trimSource value with all trailing occurrences of trimChar removed. | |
• | If trimType is BOTH, the result will be the trimSource value with all leading *and* trailing occurrences of trimChar removed. |
-- returns 'derby' (no spaces) VALUES TRIM(' derby ')
-- returns 'derby' (no spaces) VALUES TRIM(BOTH ' ' FROM ' derby ')
-- returns 'derby ' (with a space at the end) VALUES TRIM(LEADING ' ' FROM ' derby ')
-- returns ' derby' (with two spaces at the beginning) VALUES TRIM(TRAILING ' ' FROM ' derby ')
-- returns NULL VALUES TRIM(cast (null as char(1)) FROM ' derby ')
-- returns NULL VALUES TRIM(' ' FROM cast(null as varchar(30)))
-- returns ' derb' (with a space at the beginning) VALUES TRIM('y' FROM ' derby')
-- results in an error because trimCharacter can only be 1 character VALUES TRIM('by' FROM ' derby')
UCASE or UPPER ( CharacterExpression )
VARCHAR (CharacterStringExpression )
XMLEXISTS ( xquery-string-literal PASSING BY REF xml-value-expression [ BY REF ] )
SELECT id, XMLEXISTS('//student[@age=20]' PASSING BY REF xcol) FROM x_table
SELECT id FROM x_table WHERE XMLEXISTS('/roster/student' PASSING BY REF xcol)
CREATE TABLE x_table ( id INT, xcol XML CHECK (XMLEXISTS ('//student[@age < 25]' PASSING BY REF xcol)) )
XMLPARSE (DOCUMENT string-value-expression PRESERVE WHITESPACE)
INSERT INTO x_table VALUES (1, XMLPARSE(DOCUMENT ' <roster> <student age="18">AB</student> <student age="23">BC</student> <student>NOAGE</student> </roster>' PRESERVE WHITESPACE) )
You should bind into the statement using the setCharacterStream() method, or any other JDBC setXXX method that works for the CAST target type.INSERT INTO x_table VALUES (2, XMLPARSE (DOCUMENT CAST (? AS CLOB) PRESERVE WHITESPACE) )
XMLQUERY ( xquery-string-literal PASSING BY REF xml-value-expression [ RETURNING SEQUENCE [ BY REF ] ] EMPTY ON EMPTY )
The result set for this query contains a row for every row in x_table, regardless of whether or not the XMLQUERY operator actually returns results.SELECT ID, XMLSERIALIZE( XMLQUERY('//student[@age>20]' PASSING BY REF xcol EMPTY ON EMPTY) AS VARCHAR(50)) FROM x_table
The result set for this query contains a row for only the rows in x_table that have a student whose name is BC.SELECT ID, XMLSERIALIZE( XMLQUERY('string(//student[text() = "BC"]/@age)' PASSING BY REF xcol EMPTY ON EMPTY) AS VARCHAR(50)) FROM x_table WHERE XMLEXISTS('//student[text() = "BC"]' PASSING BY REF xcol)
INSERT INTO x_table (id, xcol) VALUES (3, XMLPARSE(DOCUMENT '[xString]' PRESERVE WHITESPACE)); SELECT id, XMLSERIALIZE(xcol AS VARCHAR(100)) FROM x_table WHERE id = 3;
XMLSERIALIZE ( xml-value-expression AS string-data-type )
To retrieve the results from JDBC, you can use the JDBC getCharacterStream() or getString() method.SELECT ID, XMLSERIALIZE( xcol AS CLOB) FROM x_table
SELECT ID, XMLSERIALIZE( XMLQUERY('//student[@age>20]' PASSING BY REF xcol EMPTY ON EMPTY) AS VARCHAR(50)) FROM x_table
SYSCS_UTIL.SYSCS_GET_USER_ACCESS (USERNAME VARCHAR(128)) RETURNS VARCHAR(128)
SYSCS_UTIL.SYSCS_BACKUP_DATABASE(IN BACKUPDIR VARCHAR())
SYSCS_UTIL.SYSCS_BACKUP_DATABASE_NOWAIT(IN BACKUPDIR VARCHAR())
SYSCS_UTIL.SYSCS_BACKUP_DATABASE_AND_ENABLE_LOG_ARCHIVE_MODE (IN BACKUPDIR VARCHAR(32672), IN SMALLINT DELETE_ARCHIVED_LOG_FILES)
CallableStatement cs = conn.prepareCall ("CALL SYSCS_UTIL.SYSCS_BACKUP_DATABASE_AND_ENABLE_LOG_ARCHIVE_MODE(?, ?)"); cs.setString(1, "c:/backupdir"); cs.setInt(2, 0); cs.execute();
SYSCS_UTIL.SYSCS_BACKUP_DATABASE_AND_ENABLE_LOG_ARCHIVE_MODE('c:/backupdir', 0)
SYSCS_UTIL.SYSCS_BACKUP_DATABASE_AND_ENABLE_LOG_ARCHIVE_MODE('c:/backupdir', 1)
SYSCS_UTIL.SYSCS_BACKUP_DATABASE_AND_ENABLE_LOG_ARCHIVE_MODE_NOWAIT (IN BACKUPDIR VARCHAR(32672), IN SMALLINT DELETE_ARCHIVED_LOG_FILES)
CallableStatement cs = conn.prepareCall ("CALL SYSCS_UTIL.SYSCS_BACKUP_DATABASE_AND_ENABLE_LOG_ARCHIVE_MODE_NOWAIT(?, ?)"); cs.setString(1, "c:/backupdir"); cs.setInt(2, 0); cs.execute();
SYSCS_UTIL.SYSCS_BACKUP_DATABASE_AND_ENABLE_LOG_ARCHIVE_MODE_NOWAIT('c:/backupdir', 0)
SYSCS_UTIL.SYSCS_BACKUP_DATABASE_AND_ENABLE_LOG_ARCHIVE_MODE_NOWAIT('c:/backupdir', 1)
SYSCS_UTIL.SYSCS_COMPRESS_TABLE (IN SCHEMANAME VARCHAR(128), IN TABLENAME VARCHAR(128), IN SEQUENTIAL SMALLINT)
call SYSCS_UTIL.SYSCS_COMPRESS_TABLE('US', 'CUSTOMER', 1)
CallableStatement cs = conn.prepareCall ("CALL SYSCS_UTIL.SYSCS_COMPRESS_TABLE(?, ?, ?)"); cs.setString(1, "US"); cs.setString(2, "CUSTOMER"); cs.setShort(3, (short) 1); cs.execute();
SYSCS_UTIL.SYSCS_INPLACE_COMPRESS_TABLE( IN SCHEMANAME VARCHAR(128), IN TABLENAME VARCHAR(128), IN PURGE_ROWS SMALLINT, IN DEFRAGMENT_ROWS SMALLINT, IN TRUNCATE_END SMALLINT )
call SYSCS_UTIL.SYSCS_INPLACE_COMPRESS_TABLE('US', 'CUSTOMER', 1, 1, 1);
call SYSCS_UTIL.SYSCS_INPLACE_COMPRESS_TABLE('US', 'CUSTOMER', 0, 0, 1);
CallableStatement cs = conn.prepareCall ("CALL SYSCS_UTIL.SYSCS_INPLACE_COMPRESS_TABLE(?, ?, ?, ?, ?)"); cs.setString(1, "US"); cs.setString(2, "CUSTOMER"); cs.setShort(3, (short) 1); cs.setShort(4, (short) 1); cs.setShort(5, (short) 1); cs.execute();
CallableStatement cs = conn.prepareCall ("CALL SYSCS_UTIL.SYSCS_INPLACE_COMPRESS_TABLE(?, ?, ?, ?, ?)"); cs.setString(1, "US"); cs.setString(2, "CUSTOMER"); cs.setShort(3, (short) 0); cs.setShort(4, (short) 0); cs.setShort(5, (short) 1); cs.execute();
SYSCS_UTIL.SYSCS_DISABLE_LOG_ARCHIVE_MODE(IN SMALLINT DELETE_ARCHIVED_LOG_FILES)
CallableStatement cs = conn.prepareCall ("CALL SYSCS_UTIL.SYSCS_DISABLE_LOG_ARCHIVE_MODE(?)"); cs.setInt(1, 1); cs.execute(); cs.close();
CALL SYSCS_UTIL.SYSCS_DISABLE_LOG_ARCHIVE_MODE DELETE_ARCHIVED_LOG_FILES(0);
CALL SYSCS_UTIL.SYSCS_DISABLE_LOG_ARCHIVE_MODE DELETE_ARCHIVED_LOG_FILES(1);
SYSCS_UTIL.SYSCS_EXPORT_TABLE (IN SCHEMANAME VARCHAR(128), IN TABLENAME VARCHAR(128), IN FILENAME VARCHAR(32672), IN COLUMNDELIMITER CHAR(1), IN CHARACTERDELIMITER CHAR(1), IN CODESET VARCHAR(128))
SYSCS_UTIL.SYSCS_EXPORT_TABLE_LOBS_TO_EXTFILE ( IN SCHEMANAME VARCHAR(128), IN TABLENAME VARCHAR(128), IN FILENAME VARCHAR(32672), IN COLUMNDELIMITER CHAR(1), IN CHARACTERDELIMITER CHAR(1), IN CODESET VARCHAR(128) IN LOBSFILENAME VARCHAR(32672) )
CALL SYSCS_UTIL.SYSCS_EXPORT_TABLE_LOBS_TO_EXTFILE( 'APP', 'STAFF', 'c:\data\staff.del', ',' ,'"', 'UTF-8', 'c:\data\pictures.dat');
SYSCS_UTIL.SYSCS_EXPORT_QUERY(IN SELECTSTATEMENT VARCHAR(32672), IN FILENAME VARCHAR(32672), IN COLUMNDELIMITER CHAR(1), IN CHARACTERDELIMITER CHAR(1), IN CODESET VARCHAR(128))
SYSCS_UTIL.SYSCS_EXPORT_QUERY_LOBS_TO_EXTFILE ( IN SELECTSTATEMENT VARCHAR(32672), IN FILENAME VARCHAR(32672), IN COLUMNDELIMITER CHAR(1), IN CHARACTERDELIMITER CHAR(1), IN CODESET VARCHAR(128) IN LOBSFILENAME VARCHAR(32672) )
CALL SYSCS_UTIL.SYSCS_EXPORT_QUERY_LOBS_TO_EXTFILE( 'SELECT * FROM STAFF WHERE dept=20', 'c:\data\staff.del', ',' ,'"', 'UTF-8','c:\data\pictures.dat');
SYSCS_UTIL.SYSCS_IMPORT_DATA (IN SCHEMANAME VARCHAR(128), IN TABLENAME VARCHAR(128), IN INSERTCOLUMNS VARCHAR(32672), IN COLUMNINDEXES VARCHAR(32672), IN FILENAME VARCHAR(32672), IN COLUMNDELIMITER CHAR(1), IN CHARACTERDELIMITER CHAR(1), IN CODESET VARCHAR(128), IN REPLACE SMALLINT)
SYSCS_UTIL.SYSCS_IMPORT_DATA_LOBS_FROM_EXTFILE ( IN SCHEMANAME VARCHAR(128), IN TABLENAME VARCHAR(128), IN INSERTCOLUMNS VARCHAR(32672), IN COLUMNINDEXES VARCHAR(32672), IN FILENAME VARCHAR(32672), IN COLUMNDELIMITER CHAR(1), IN CHARACTERDELIMITER CHAR(1), IN CODESET VARCHAR(128), IN REPLACE SMALLINT) )
• | Offset is position in the external file in bytes | |
• | length is the size of the LOB column data in bytes |
CALL SYSCS_UTIL.SYSCS_IMPORT_DATA_LOBS_FROM_EXTFILE (null, 'STAFF', 'NAME,DEPT,SALARY,PICTURE', '2,3,4,6', 'c:\data\staff.del', ',','"','UTF-8', 0);
SYSCS_UTIL.SYSCS_IMPORT_TABLE (IN SCHEMANAME VARCHAR(128), IN TABLENAME VARCHAR(128), IN FILENAME VARCHAR(32672), IN COLUMNDELIMITER CHAR(1), IN CHARACTERDELIMITER CHAR(1), IN CODESET VARCHAR(128), IN REPLACE SMALLINT)
CALL SYSCS_UTIL.SYSCS_IMPORT_TABLE (null, 'STAFF', 'c:/output/myfile.del', ';', '%', null,0);
SYSCS_UTIL.SYSCS_IMPORT_TABLE_LOBS_FROM_EXTFILE ( IN SCHEMANAME VARCHAR(128), IN TABLENAME VARCHAR(128), IN FILENAME VARCHAR(32672), IN COLUMNDELIMITER CHAR(1), IN CHARACTERDELIMITER CHAR(1), IN CODESET VARCHAR(128), IN REPLACE SMALLINT) )
• | Offset is position in the external file in bytes | |
• | length is the size of the LOB column data in bytes |
CALL SYSCS_UTIL.SYSCS_IMPORT_TABLE_LOBS_FROM_EXTFILE( 'APP','STAFF','c:\data\staff.del',',','"','UTF-8',0);
String backupdirectory = "c:/mybackups/" + JCalendar.getToday(); CallableStatement cs = conn.prepareCall ("CALL SYSCS_UTIL.SYSCS_FREEZE_DATABASE()"); cs.execute(); cs.close(); // user supplied code to take full backup of "backupdirectory" // now unfreeze the database once backup has completed: CallableStatement cs = conn.prepareCall ("CALL SYSCS_UTIL.SYSCS_UNFREEZE_DATABASE()"); cs.execute(); cs.close();
String backupdirectory = "c:/mybackups/" + JCalendar.getToday(); CallableStatement cs = conn.prepareCall ("CALL SYSCS_UTIL.SYSCS_FREEZE_DATABASE()"); cs.execute(); cs.close(); // user supplied code to take full backup of "backupdirectory" // now unfreeze the database once backup has completed: CallableStatement cs = conn.prepareCall ("CALL SYSCS_UTIL.SYSCS_UNFREEZE_DATABASE()"); cs.execute(); cs.close();
SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(IN KEY VARCHAR(128), IN VALUE VARCHAR(32672))
CallableStatement cs = conn.prepareCall ("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(?, ?)"); cs.setString(1, "derby.locks.deadlockTimeout"); cs.setString(2, "10"); cs.execute(); cs.close();
SYSCS_UTIL.SYSCS_SET_USER_ACCESS (USERNAME VARCHAR(128), CONNECTION_PERMISSION VARCHAR(128))
SYSCS_UTIL.SYSCS_UPDATE_STATISTICS(IN SCHEMANAME VARCHAR(128), IN TABLENAME VARCHAR(128), IN INDEXNAME VARCHAR(128)))
CALL SYSCS_UTIL.SYSCS_UPDATE_STATISTICS('SAMP','EMPLOYEE','PAY_DESC');
CALL SYSCS_UTIL.SYSCS_UPDATE_STATISTICS('SAMP', 'EMPLOYEE', null);
Diagnostic table expression | Type of expression |
SYSCS_DIAG.CONTAINED_ROLES | Table function |
SYSCS_DIAG.ERROR_LOG_READER | Table function |
SYSCS_DIAG.ERROR_MESSAGES | Table |
SYSCS_DIAG.LOCK_TABLE | Table |
SYSCS_DIAG.SPACE_TABLE | Table function |
SYSCS_DIAG.STATEMENT_CACHE | Table |
SYSCS_DIAG.STATEMENT_DURATION | Table function |
SYSCS_DIAG.TRANSACTION_TABLE | Table |
SELECT * FROM TABLE (SYSCS_DIAG.CONTAINED_ROLES(reader))
where T1 is a user-specified table name that is any valid identifier.SELECT * FROM TABLE (SYSCS_DIAG.ERROR_LOG_READER()) AS T1
SELECT * FROM TABLE (SYSCS_DIAG.ERROR_LOG_READER('myderbyerrors.log')) AS T1
SELECT * FROM SYSCS_DIAG.ERROR_MESSAGES
SELECT * FROM SYSCS_DIAG.LOCK_TABLE
where T2 is a user-specified table name that is any valid identifier.SELECT T2.* FROM SYS.SYSTABLES systabs, TABLE (SYSCS_DIAG.SPACE_TABLE(systabs.tablename)) AS T2 WHERE systabs.tabletype = 'T'
SELECT * FROM TABLE (SYSCS_DIAG.SPACE_TABLE('MYSCHEMA', 'MYTABLE')) AS T2