http://www.apache.org/licenses/LICENSE-2.0
|
•
|
SQL language reference
Reference information
about Derby's SQL language,
including manual pages for statements, functions, and other syntax elements.
| |
|
•
|
SQL reserved words
SQL keywords beyond the standard SQL-92 keywords.
| |
|
•
|
Derby support for SQL-92 features
A list of
SQL-92 features that Derby does
and does not support.
| |
|
•
|
Derby System Tables
Reference
information about the Derby system
catalogs.
| |
|
•
|
Derby exception messages and SQL states
Information
about Derby exception messages.
| |
|
•
|
JDBC Reference
Information
about Derby's implementation
of the JDBC interface include support for JDBC 2.0 features.
| |
|
•
|
Setting attributes for the database connection URL
Information
about the supported attributes to Derby's
JDBC database connection URL.
| |
|
•
|
J2EE Compliance: Java Transaction API and javax.sql Extensions
Information
about the supported attributes to Derby's
support for the Java Transaction API.
| |
|
•
|
Derby API
Notes
about proprietary APIs for Derby.
|
|
•
|
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 expression
.
| |
|
•
|
Two dashes (--) and a newline character delimit a comment, as per the
SQL-92 standard. The two dashes start the comment and the newline character
ends the comment.
|
"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 'MYTABLE' does not exist.
|
•
|
add a column to a table
| |
|
•
|
add a constraint to a table
| |
|
•
|
drop an existing constraint from a table
| |
|
•
|
increase the width of a VARCHAR, CHAR VARYING, and CHARACTER VARYING column
| |
|
•
|
override row-level locking for the table (or drop the override)
|
ALTER TABLE table-Name { ADD COLUMN column-definition | ADD CONSTRAINT clause | DROP { PRIMARY KEY | FOREIGN KEY constraint-name | UNIQUE constraint-name | CHECK constraint-name | CONSTRAINT constraint-name } ALTER column-alteration | LOCKSIZE { ROW | TABLE } }
Simple-column-Name DataType [ Column-level-constraint ]* [ [ WITH ] DEFAULT {ConstantExpression | NULL } ]
column-Name SET DATA TYPE VARCHAR(integer) | column-name SET INCREMENT BY integer-constant
|
•
|
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 length of an existing VARCHAR column. CHARACTER VARYING
or CHAR VARYING can be used as synonyms for the VARCHAR keyword.
To increase
the width of a column of these types, specify the data type and new size after
the column name.
You are not allowed to decrease the width or to change
the data type. You are not allowed to increase the width of a column that
is part of a primary or unique key referenced by a foreign key constraint
or that is part of a foreign key constraint.
| |
|
•
|
Specifying the interval between consecutive values of the identity column.
To
set an interval between consecutive values of the identity column, specify
the integer-constant. You must previously define the column with the IDENTITY
attribute (SQLSTATE 42837). If there are existing rows in the table, the values
in the column for which the SET INCREMENT default was added do not change.
|
-- Add a new column with a column-level constraint -- to an existing table -- An exception will be thrown if the table -- contains any rows -- since the newcol will be initialized to NULL -- in all existing rows in the table ALTER TABLE CITIES ADD COLUMN REGION VARCHAR(26) CONSTRAINT NEW_CONSTRAINT CHECK (REGION IS NOT NULL); -- Add a new unique constraint to an existing table -- An exception will be thrown if duplicate keys are found ALTER TABLE SAMP.DEPARTMENT ADD CONSTRAINT NEW_UNIQUE UNIQUE (DEPTNO); -- add a new foreign key constraint to the -- Cities table. Each row in Cities is checked -- to make sure it satisfied the constraints. -- if any rows don't satisfy the constraint, the -- constraint is not added ALTER TABLE CITIES ADD CONSTRAINT COUNTRY_FK Foreign Key (COUNTRY) REFERENCES COUNTRIES (COUNTRY); -- Add a primary key constraint to a table -- First, create a new table CREATE TABLE ACTIVITIES (CITY_ID INT NOT NULL, SEASON CHAR(2), ACTIVITY VARCHAR(32) NOT NULL); -- You will not be able to add this constraint if the -- columns you are including in the primary key have -- null data or duplicate values. ALTER TABLE Activities ADD PRIMARY KEY (city_id, activity); -- Drop a primary key constraint from the CITIES table ALTER TABLE Cities DROP CONSTRAINT Cities_PK; -- Drop a foreign key constraint from the CITIES table ALTER TABLE Cities DROP CONSTRAINT COUNTRIES_FK; -- add a DEPTNO column with a default value of 1 ALTER TABLE SAMP.EMP_ACT ADD COLUMN DEPTNO INT DEFAULT 1; -- increase the width of a VARCHAR column ALTER TABLE SAMP.EMP_PHOTO ALTER PHOTO_FORMAT SET DATA TYPE VARCHAR(30); -- change the lock granularity of a table ALTER TABLE SAMP.SALES LOCKSIZE TABLE;
CREATE FUNCTION function-name ( [ FunctionParameter [, FunctionParameter ] ] * ) RETURNS DataType [ FunctionElement ] *
[ schemaName . ] SQL92Identifier
{ | LANGUAGE { JAVA } | EXTERNAL NAME string | PARAMETER STYLE JAVA | { 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
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 } | 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
CREATE SCHEMA schemaName
-- Create a schema for employee-related tables CREATE SCHEMA EMP; -- Create a schema for airline-related tables CREATE SCHEMA Flights -- Create a table called "Availability" in each schema CREATE TABLE FLIGHTS.AVAILABILITY (FLIGHT_ID CHAR(6) NOT NULL, SEGMENT_NUMBER INT NOT NULL, FLIGHT_DATE DATE NOT NULL, ECONOMY_SEATS_TAKEN INT, BUSINESS_SEATS_TAKEN INT, FIRSTCLASS_SEATS_TAKEN INT, CONSTRAINT FLT_AVAIL_PK PRIMARY KEY (FLIGHT_ID, SEGMENT_NUMBER, FLIGHT_DATE)); CREATE TABLE EMP.AVAILABILITY (HOTEL_ID INT NOT NULL, BOOKING_DATE DATE NOT NULL, ROOMS_TAKEN INT, CONSTRAINT HOTELAVAIL_PK PRIMARY KEY (HOTEL_ID, BOOKING_DATE));
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 }
CREATE TABLE table-Name ( { column-definition | Table-level constraint } [ , { column-definition | Table-level constraint } ] * )
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));
Simple-column-Name DataType [ Column-level-constraint ]* [ [ WITH ] DEFAULT { ConstantExpression | NULL } | generated-column-spec ] [ Column-level-constraint ]*
[ 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');
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.
| |
|
•
|
It must not execute a CALL statement.
| |
|
•
|
Before triggers cannot have INSERT, UPDATE or DELETE statements as their
action.
|
|
•
|
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 MODE DB2SQL 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 MODE DB2SQL DELETE FROM FLIGHTAVAILABILITY WHERE FLIGHT_ID = OLD.FLIGHT_ID;
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
DROP FUNCTION function-name
DROP PROCEDURE procedure-Name
DROP SCHEMA schemaName RESTRICT
RENAME TABLE table-Name TO new-Table-Name
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
|
•
|
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. NULL values
are not allowed.
| |
|
•
|
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. The identified
columns must be defined as NOT NULL.
| |
|
•
|
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}]
|
•
|
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 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 SYNONYM
| |
|
•
|
CREATE TRIGGER
| |
|
•
|
CREATE VIEW
| |
|
•
|
LOCK
| |
|
•
|
RENAME
|
|
•
|
BLOB
| |
|
•
|
CLOB
| |
|
•
|
LONG VARCHAR
|
|
•
|
index support
| |
|
•
|
synonyms, triggers and views on SESSION schema tables (including physical
tables and temporary tables)
| |
|
•
|
LOCK TABLE
| |
|
•
|
constraints and primary keys
| |
|
•
|
generated-column-spec
| |
|
•
|
importing into temporary tables
|
DELETE FROM SAMP.IN_TRAY; stmt.executeUpdate("DELETE FROM SAMP.IN_TRAY WHERE CURRENT OF " + resultSet.getCursorName())
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), 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
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;
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
.
| |
|
•
|
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);
JOIN Operation
|
•
|
INNER JOIN
Specifies a join between
two tables with an explicit join clause. See
INNER JOIN
.
| |
|
•
|
LEFT OUTER JOIN
Specifies a
join between two tables with an explicit join clause, preserving unmatched
rows from the first table. See
LEFT OUTER JOIN
.
| |
|
•
|
RIGHT OUTER JOIN
Specifies a join between
two tables with an explicit join clause, preserving unmatched rows from the
second table. See
RIGHT OUTER JOIN
.
|
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;
|
•
|
avoiding the overhead of multiple row locks on a table (in other words,
user-initiated lock escalation)
| |
|
•
|
avoiding deadlocks
|
LOCK TABLE table-Name IN { SHARE | EXCLUSIVE } MODE
-- lock the entire table in share mode to avoid -- a large number of row locks LOCK TABLE Flights IN SHARE MODE; SELECT * FROM Flights WHERE orig_airport > 'OOO'; -- lock the entire table in exclusive mode -- for a transaction that will update many rows, -- but where no single statement will update enough rows -- acquire an exclusive table lock on the table. -- In a row-level locking system, that transaction would -- require a large number of locks or might deadlock. LOCK TABLE HotelAvailability IN EXCLUSIVE MODE; UPDATE HotelAvailability SET rooms_taken = (rooms_taken + 2) WHERE hotel_id = 194 AND booking_date = DATE('1998-04-10'); UPDATE HotelAvailability SET rooms_taken = (rooms_taken + 2) WHERE hotel_id = 194 AND booking_date = DATE('1998-04-11'); UPDATE HotelAvailability SET rooms_taken = (rooms_taken + 2) WHERE hotel_id = 194 AND booking_date = DATE('1998-04-12'); UPDATE HotelAvailability SET rooms_taken = (rooms_taken + 2) WHERE hotel_id = 194 AND booking_date = DATE('1998-04-12'); -- if a transaction needs to look at a table before -- updating it, acquire an exclusive lock before -- selecting to avoid deadlocks LOCK TABLE People IN EXCLUSIVE MODE; SELECT MAX(person_id) + 1 FROM PEOPLE; -- INSERT INTO PEOPLE . . .
ORDER BY { column-Name | ColumnPosition } [ ASC | DESC ] [ , column-Name | ColumnPosition [ ASC | DESC ] ] *
{ ( 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');
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;
-- 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);
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 WORKDEPT, AVG(SALARY) FROM EMPLOYEE GROUP BY WORKDEPT ORDER BY 1;
|
•
|
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;
Query [ ORDER BY 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:
|
|
•
|
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 } [ [ AS ] correlation-Name [ ( Simple-column-Name [ , Simple-column-Name ]* ) ] ] ]
|
•
|
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);
{ UPDATE table-Name SET column-Name = Value [ , column-Name = Value } ]* [ WHERE clause ] | UPDATE table-Name SET column-Name = Value [ , column-Name = Value ]* WHERE CURRENT OF }
-- 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 certain employees to MANAGER UPDATE EMPLOYEE SET JOB = 'MANAGER' WHERE CURRENT OF CURS1; -- 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';
-- 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)
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");
|
'
|
All Types
|
Numeric Built-in Data Types
|
|
COUNT
|
X
|
X
|
|
MIN
|
'
|
X
|
|
MAX
|
'
|
X
|
|
AVG
|
'
|
X
|
|
SUM
|
'
|
X
|
|
•
|
A SelectItem in a
SelectExpression
.
| |
|
•
|
A
HAVING clause
.
| |
|
•
|
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))
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 )
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
|
-
|
Y
|
|
TIME
|
-
|
-
|
-
|
-
|
-
|
-
|
-
|
Y
|
Y
|
-
|
-
|
-
|
-
|
-
|
-
|
-
|
Y
|
Y
|
|
TIME STAMP
|
-
|
-
|
-
|
-
|
-
|
-
|
-
|
Y
|
Y
|
-
|
-
|
-
|
-
|
-
|
-
|
Y
|
Y
|
Y
|
|
•
|
numeric
| |||||||
|
•
|
string
| |||||||
|
•
|
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)
|
•
|
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 } }
The NULLIF expression is very similar to the CASE expression. For example:NULLIF(L, R)
is equivalent to the following CASE expression:NULLIF(V1,V2)
CASE WHEN V1=V2 THEN NULL ELSE V1 END
If the value of the instance specified in an instance method invocation is null, the result of the invocation is null (SQL NULL). However, you still might need to use the CASE expression for when a nullable column is a primitive method parameter.-- returns 3 VALUES CASE WHEN 1=1 THEN 3 ELSE 4 END;
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.
|
|
•
|
If the argument is a date, timestamp, or valid string representation of
a date or timestamp: The result is the day part of the value, which is an
integer between 1 and 31.
| |
|
•
|
If the argument is a time duration or timestamp duration: The result is
the day part of the value, which is an integer between -99 and 99. A nonzero
result has the same sign as the argument.
|
|
•
|
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 argument is a date, timestamp, or valid string representation of
a date or timestamp: The result is the hour part of the value,
which is an integer between 0 and 24.
| |
|
•
|
If the argument is a time duration or timestamp duration: The result is
the hour part of the value, which is an integer between -99 and 99. A nonzero
result has the same sign as the argument.
|
|
•
|
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 )
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