Blackfish SQL
ContentsIndex
PreviousUpNext
SQL Reference

The SQL Reference includes the following topics:

Data Types 
 
Literals 
Keywords 
Identifiers 
List Syntax 
Expressions 
Predicates 
Functions 
Table Expressions 
Statements 
Data Definition Statements 
Transaction Control Statements 
Data Manipulation Statements 
Security Statements 
Escape Sequences 
Escape Functions 
ISQL 

In SQL, you can specify data types by using Blackfish SQL names or by using synonyms, which are more portable to other SQL dialects. The following table lists the Blackfish SQL SQL data types and their Java equivalents. See Administering Blackfish SQL for a description of each data type.  

Strings are stored in UNICODE character format. However, if a string contains no high-bit characters. the high bytes are not saved and the number of bytes is equal to the number of characters. In double-byte languages such as Japanese, the number of bytes is double the number of characters.  

NOTE: The word “inline” refers to the portion of the field data that is stored in the table row. When the maximum inline value is surpassed, the remaining data is stored in a separate stream as a Blob.

SQL Data Types Supported by Blackfish SQL

The following table describes the SQL data types supported by Blackfish SQL:

Data Type  
SQL Equivalents 1 
8 bit byte 
TINYINT BYTE 
16 bit integer 
SMALLINT SHORT 
32 bit integer 
INT INTEGER 
64 bit integer 
BIGINT LONG 
Exact decimal number 
DECIMAL(p,d) BIGDECIMAL(p,d) 
64 bit floating point 
FLOAT(p), p=24 through 52 FLOAT DOUBLE DOUBLE PRECISION 
32 bit floating point 
REAL FLOAT(p), p=1 through 23 
Unicode string 
VARCHAR(p,m) STRING(p,m) 
Array of bytes 
VARBINARY(p,m) BINARY(p,m) INPUTSTREAM(p,m) 
Serializable object 
OBJECT(t,m) 
Boolean 
BOOLEAN BIT 
Date 
DATE 
Time 
TIME 
Timestamp 
TIMESTAMP 

1 In the SQL Equivalents column, bold indicates the more portable forms.  

Examples

VARCHAR(30,10) 
A string with a maximum size of 30 characters; the first 10 bytes are stored inline, the remainder in a Blob (a separate stream for large objects) 
VARCHAR(30) 
A string with a maximum size of 30 characters, all stored inline because the precision is less than default inline value of 64 
VARCHAR 
A string with no length limit; the first 64 bytes are stored inline, any additional bytes are stored in a Blob (a separate stream for large objects) 
DECIMAL(5,2) 
A BigDecimal with a precision of at least 5 and exactly 2 decimal places 
DECIMAL(4) 
A BigDecimal with a precision of at least 4 and exactly 0 decimal places 
DECIMAL 
A BigDecimal with space for at least 72 significant digits and exactly 0 decimal places 
OBJECT 
A serializable Java object 
OBJECT('java.math.BigInteger') 
A serializable Java object that must consist of java.math.BigInteger objects 

The following table lists the types of scalar literal values supported:

Blackfish SQL Data Type 
Examples 
Description  
SMALLINT INT BIGINT 
Integer data types 
DECIMAL(p,d) 

  1. 15.7 .9233

 

An exact numeric; can contain a decimal point 
REAL DOUBLE FLOAT(p) 
8E0 4E3 0.3E2 6.2E-72 
An approximate numeric: a number followed by the letter E, followed by an optionally signed integer 
VARCHAR(p,m) 
'Hello' 'don''t do that' 
A string: must be enclosed in single quotes. The single quote character is represented by two consecutive single quotes 
VARBINARY(p,m) 
B'1011001' X'F08A' X'f777' 
A binary or hexadecimal sequence enclosed in single quotes and preceded by the letter B for binary or X for hexadecimal 
BOOLEAN 
TRUE FALSE 
 
DATE 
DATE '2002-06-17' 
Displays local time of origin; format is DATE 'yyyy-mm-dd' 
TIME 
TIME '15:46:55' 
Displays local time of origin; format is TIME 'hh:mm:ss' in 24-hour format 
TIMESTAMP 
TIMESTAMP '2001-12-31 13:15:45' 
Displays local time of display; format is TIMESTAMP 'yyyy-mm-dd hh:mm:ss' 

NOTE: There are no object literals in Blackfish SQL.

The two lists below show all the current keywords for Blackfish SQL. The words in the first list are reserved and can be used as SQL identifiers only when enclosed in double quotation marks. The keywords in the second list are not reserved and can be used either with or without quotation marks.  

Note that not all SQL-92 keywords are treated as a keyword by the Blackfish SQL SQL engine. For maximum portability, don’t use identifiers that are treated as keywords in any SQL dialect.

Reserved Blackfish SQL Keywords

The words in this list are reserved keywords. They can be used as SQL identifiers only if they are enclosed in double quotation marks. When quoted in this fashion, they are case sensitive.

ABSOLUTE ACTION ADD ADMIN ADMINISTRATOR ALL ALTER AND ANY AS ASC AUTHORIZATION AUTOINCREMENT AVG BETWEEN BIT BIT_LENGTH BOTH BY CALL CASCADE CASE CAST CHAR CHAR_LENGTH CHARACTER CHARACTER_LENGTH CHECK COALESCE COLUMN CONSTRAINT COUNT CREATE CROSS CURRENT_DATE 
CURRENT_ROLE CURRENT_TIME CURRENT_TIMESTAMP CURRENT_USER DATE DECIMAL DEFAULT DELETE DESC DISTINCT DOUBLE DROP ELSE END ESCAPE EXCEPT EXECUTE EXISTS EXTRACT FALSE FLOAT FOR FOREIGN FROM FULL GRANT GROUP HAVING IN INDEX INNER INSERT INT INTEGER INTERSECT 
INTO IS ISOLATION JOIN KEY LEADING LEFT LEVEL LIKE LOWER MAX MIN NATURAL NO NONE NOT NULL NULLIF NUMERIC OCTET_LENGTH ON ONLY OPTION OR ORDER OUTER POSITION PRECISION PRIMARY PRIVILEGES PUBLIC REAL REFERENCES RENAME RESOLVABLE 
RESTRICT REVOKE RIGHT SCHEMA SELECT SET SMALLINT SOME SQRT STARTUP SUBSTRING SUM TABLE THEN TIME TIMESTAMP TO TRAILING TRANSACTION TRIM TRUE UNION UNIQUE UNKNOWN UPDATE UPPER USER USING VALUES VARCHAR VARYING VIEW WHEN WHERE WITH 

 

Unreserved Blackfish SQL Keywords

The keywords in the following list are not reserved. They can be used as SQL identifiers either with or without quotation marks. When used without quotation marks, they are case insensitive and are interpreted as all caps by the SQL parser. When enclosed in double quotation marks, they are case sensitive.

ABS AUTOCOMMIT BOOLEAN BIGDECIMAL BIGINT BINARY BYTE CASEINSENSITIVE CLASS COMMIT COMMITTED CONCAT CONVERT CURDATE CURTIME D DAY 
DAYOFMONTH DEC FN GRANTED HOUR IFNULL INPUTSTREAM METHOD LCASE LENGTH LOCATE LOCK LONG LONGINT LONGVARBINARY LONGVARCHAR LTRIM 
METHOD MINUTE MONTH NOW NOWAIT OBJECT OFF OJ PASSWORD READ REPEATABLE ROLE ROLLBACK RTRIM SECOND SERIALIZABLE 
SHORT STRING T TIMESTAMPADD TIMESTAMPDIFF TIMEZONEHOUR TIMEZONEMINUTE TINYINT TS TYPE UCASE UNCOMMITTED VARBINARY WORK WRITE YEAR 

Unquoted SQL identifiers are case insensitive and are treated as uppercase. An identifier can be enclosed in double quotes, and is then treated as case sensitive. An unquoted identifier must follow these rules:

  • The first character must be a letter recognized by the java.lang.Character class.
  • Each following character must be a letter, digit, underscore (_), or dollar sign ($).
  • Keywords can't be used as identifiers.

Quoted identifiers can contain any character string including spaces, symbols, and keywords. Examples  

Valid identifiers:

Identifier 
Description 
customer 
Treated as CUSTOMER 
Help_me 
Treated as HELP_ME 
"Hansen" 
Treated as Hansen 
" "  
Treated as a single space 

Invalid identifiers:

Identifier 
Problem 
_order 
Must start with a character 
date 
date is a reserved keyword 
embarcadero.com 
Dots are not allowed 

The forms in the following list are all the same identifier and are all treated as LAST_NAME:

  • last_name
  • Last_Name
  • lAsT_nAmE
  • "LAST_NAME"

The following section contains element names ending with the words “list” or “commalist” that are not further defined. For example:

<select item commalist>
<column constraint list>

These definitions are to be read as a lists with at least one element, comma separated in the case of a commalist:

<select item commalist> ::= 
   <select item> [ , <select item> ] *

<column constraint list> ::= 
   <column constraint> [ <column constraint> ] *

Expressions are used throughout the SQL language. They contain several infix operators and a few prefix operators. This is the operator precedence from strongest to weakest:

  • prefix + -
  • infix * /
  • infix + - ||
  • infix = <> < > <= >=
  • prefix NOT
  • infix AND
  • infix OR

Syntax

<expression> ::=
      <scalar expression>
    | <conditional expression>

 

<scalar expression> ::=
      <scalar expression> {+ | - | * | / | <concat> }
          <scalar expression>
    | {+ | -} <scalar expression>
    | ( <expression> )
    | ( <table expression> )
    | <column reference>
    | <user defined function reference>
    | <literal>
    | <aggregator function>
    | <function>
    | <parameter marker>

For a list of functions supported in Blackfish SQL, see Functions.

<conditional expression> ::=
      <conditional expression> OR <conditional expression>
    | <conditional expression> AND <conditional expression>
    | NOT <conditional expression>
    | <scalar expression> <compare operator> <scalar expression>
    | <scalar expression> <compare operator> { ANY | SOME | ALL }
         (<table expression>)
    | <scalar expression> [NOT] BETWEEN <scalar expression>
    | <scalar expression> [NOT] LIKE <scalar expression> 
         [ ESCAPE <scalar expression> ]
    | <scalar expression> [NOT] IS { NULL | TRUE | FALSE | UNKNOWN }
    | <scalar expression> IN ( <scalar expression commalist> )
    | <scalar expression> IN ( <table expression> )
    | EXISTS ( <table expression> )

 

<compare operator> ::=
      = | <> | < | > | <= | >=

 

<concat> ::=   ||

 

<table expression> ::=
      <table expression> UNION [ ALL ] <table expression>
    | <table expression> EXCEPT [ ALL ] <table expression>
    | <table expression> INTERSECT [ ALL ] <table expression>
    | <join expression>
    | <select expression>
    | ( <table expression> )

 

<aggregator function> ::=
      <aggregator name> ( <expression> )
    | COUNT ( * )
                                                        
<aggregator name> ::=
      AVG
    | SUM
    | MIN
    | MAX
    | COUNT

 

<column reference> ::=  [ <table qualifier> . ] <column name>

<user defined function reference> ::= 
    <method name> ([ <expression commalist> ])
                                                        
<table qualifier> ::=
      <table name> | <correlation name>
                                                        
<correlation name> ::=  <SQL identifier>

Examples  

The following statement selects the calculated value of Amount times Price from the Orders table for a to-be-provided customer for orders in January:

SELECT Amount * Price FROM Orders 
    WHERE CustId = ? AND EXTRACT(MONTH FROM Ordered) = 1;

The following statement gets data using a scalar subquery:

SELECT Name, (SELECT JobName FROM Job WHERE Id=Person.JobId) 
    FROM Person;

Note that it is an error if the subquery returns more than one row.

The following predicates, used in condition expressions, are supported.

BETWEEN

The BETWEEN predicate defines an inclusive range of values. The result of:

expr BETWEEN leftExpr AND rightExpr

is equivalent to the expression:

leftExpr <= expr AND expr <= rightExpr

Syntax

<between expression> ::=
     <scalar expression> [NOT] BETWEEN <scalar expression> 
       AND <scalar expression>

Example 

The following statement selects all the orders where a customer orders between 3 and 7 items of the same kind:

SELECT * from Orders WHERE Amount BETWEEN 3 AND 7;

 

EXISTS

An EXISTS expression evaluates to either TRUE or FALSE depending on whether there are any elements in a result table.  

Syntax

<exists predicate> ::= EXISTS ( <table expression> )

Example 

The following statement finds all diving equipment where the beginning of the name is the same as the beginning of a name of a different piece of equipment.

SELECT * FROM zodiac z
   WHERE EXISTS
      ( SELECT * FROM zodiac z2 WHERE POSITION(z.name IN z2.name) = 1 
          AND z.name < > z2.name );

 

IN

The IN clause indicates a list of values to be matched. Any one of the values in the list is considered a match for the SELECT statement containing the IN clause.  

Syntax

<in expression> ::=
    <scalar expression> IN ( <scalar expression commalist> )

Example 

The following statement returns all records where the name column matches either "leo" or "aquarius":

SELECT * FROM zodiac WHERE name IN ('leo', 'aquarius');

The IN clause also has a variant where a subquery is used instead of an expression list.  

Syntax

<in expression> ::= <scalar expression> 
   IN ( <table expression> )
SELECT * FROM zodiac WHERE name IN (SELECT name FROM people);

 

IS

The IS predicate tests expressions. Any expression can evaluate to the value NULL, but conditional expressions can evaluate to one of the three values: TRUE, FALSE, or UNKNOWN. UNKNOWN is equivalent to NULL for conditional expressions. Note that for a SELECT query with a WHERE clause, only rows that evaluate to TRUE are included. If the expression evaluates to FALSE or UNKNOWN, the row isn't included. The output of the IS predicate can have two results: TRUE or FALSE.  

Syntax

<is expression> ::=
      <scalar expression> IS [NOT] { NULL | TRUE | FALSE | UNKNOWN }

Examples 

TRUE IS TRUE evaluates to TRUE

FALSE IS NULL evaluates to FALSE

LIKE

The LIKE predicate provides SQL with simple string pattern matching. The search item, pattern, and escape character (if given) must all evaluate to strings. The pattern can include the special wildcard characters _ and % where:

  • An underscore (_) matches any single character
  • A percent character (%) matches any sequence of n characters where n >= 0

The escape character, if given, allows the two special wildcard characters to be included in the search pattern. The pattern match is case-sensitive. Use the LOWER or UPPER functions on the search item for a case-insensitive match. Syntax

<like expression> ::=
      <search item> [NOT] LIKE <pattern> [ ESCAPE <escape char> ]
                                                       
<search item>  ::= <scalar expression>
                                                        
<pattern>  ::= <scalar expression>
                                                        
<escape char>  ::= <scalar expression>

Examples

  1. The following expression evaluates to TRUE if Item contains the string "shoe" anywhere inside it:
Item LIKE '%shoe%'
  1. The following expression evaluates to TRUE if Item is exactly three characters long and starts with the letter "S":
Item LIKE 'S__'
  1. The following expression evaluates to TRUE if Item ends with the percent character. The * is defined to escape the two special characters. If it precedes a special character, it is treated as a normal character in the pattern:
Item Like '%*%' ESCAPE '*'

 

Quantified Comparisons

An expression can be compared to some or all elements of a result table.  

Syntax

<quantified comparison> ::=
     <scalar expression> <compare operator> 
        { ANY | SOME | ALL } ( <table expression> )
SELECT * FROM zodiac 
    WHERE quantify <= ALL ( SELECT quantify FROM zodiac );

Functions that act on strings work for strings of any length. Large strings are stored as Blobs, so you might want to define large text fields as VARCHAR to enable searches.

ABSOLUTE

The ABSOLUTE function works on numeric expressions only, and yields the absolute value of the number passed. 

Syntax

<absolute function> ::= ABSOLUTE( <expression> )
SELECT * FROM Scapes WHERE ABSOLUTE( Height - Width ) < 50;

 

BIT_LENGTH

The BIT_LENGTH function gives the length in bits of a STRING, INPUTSTREAM, or OBJECT value.  

Syntax

<bit length function> ::= 
     BIT_LENGTH( <expression> )
SELECT * FROM TABLE1 WHERE BIT_LENGTH( binary_column ) > 8192;

 

CASE

The CASE function returns a conditional value. 

Syntax

<case function> ::=
    CASE  [ <expression> ]
        <when clause commalist>
        ELSE  <expression>
    END

<when clause> ::=
    WHEN <expression>  THEN <expression>

Examples

CASE
   WHEN COL1 > 50 THEN 'Heavy Item'
   WHEN COL1 > 25 THEN 'Middle weight Item'
   WHEN COL1 >  0  THEN 'Light Item'
   ELSE  'No weight specified'
END
                                                        
CASE COL2
   WHEN 4 THEN 'A'
   WHEN 3 THEN 'B'
   WHEN 2 THEN 'C'
   WHEN 1 THEN 'D'
   ELSE 'Invalid Grade'
END

 

CAST

The CAST function casts one data type to another data type.  

Syntax

<cast function> ::=
    CAST ( <column name> AS <data type> )

Example 

The following example yields a row where a string column ID equals '001234'

SELECT * FROM employee WHERE CAST ( id AS long ) = 1234;  

 

CHAR_LENGTH and CHARACTER_LENGTH

The SQL CHAR_LENGTH and CHARACTER_LENGTH functions yield the length of the given string. 

Syntax

<char length function> ::=
      CHAR_LENGTH ( <scalar expression> )
      CHARACTER_LENGTH ( <scalar expression> )

 

COALESCE

The COALESCE function returns the first non-NULL value from the expression list.  

Syntax

<coalesce function> ::= 
    COALESCE( expression commalist )

Example  

The following statement yields a list of names. The name is the last_name if this column is not NULL, otherwise it is the first_name.

SELECT COALESCE(last_name, first_name) AS name FROM  table1;

 

CURRENT_DATE, CURRENT_TIME, and CURRENT_TIMESTAMP

These SQL functions yield the current date and/or time. If one of these functions occurs more than once in a statement, it yields the same result each time when the statement is executed. 

 

SELECT * from Returns where ReturnDate <= CURRENT_DATE;

 

CURRENT_ROLE

The CURRENT_ROLE function returns the current role, or NULL if no role has been set using the SET ROLE statement.  

Syntax

<current_role_function> ::= CURRENT_ROLE

Example 

The following statement returns all notes from the CUSTOMERS table that were placed there by anyone using the MANAGER role. The SOURCE column has a data type of VARCHAR.

SET ROLE MANAGER;
                                                        
SELECT * FROM CUSTOMERS
    WHERE SOURCE = CURRENT_ROLE;

 

CURRENT_USER

The CURRENT_USER function returns the name of the current user.  

Syntax

<current_user function> ::= CURRENT_USER

Example 

The following statement returns returns all notes from the INVOICES table that were placed there by the current user. The SOURCE column has a data type of VARCHAR.

SELECT * FROM INVOICES
    WHERE SOURCE = CURRENT_USER;

 

EXTRACT

The SQL EXTRACT function extracts parts of date and time values. The expression can be a DATE, TIME, or TIMESTAMP value.  

Syntax

<extract function> ::=
      EXTRACT ( <extract field> FROM <scalar expression> )
                                                        
<extract field> ::=
      YEAR
    | MONTH
    | DAY
    | HOUR
    | MINUTE
    | SECOND

Examples

EXTRACT(MONTH FROM DATE '1999-05-17') yields 5. 

 

EXTRACT(HOUR FROM TIME '18:00:00') yields 18. 

 

EXTRACT(HOUR FROM DATE '1999-05-17') yields an
exception. 

 

LOWER and UPPER

The SQL LOWER and UPPER functions convert the given string to the requested case, either all lowercase or all uppercase.  

Syntax

<lower function> ::=
      LOWER ( <scalar expression> )
                                                        
<upper function> ::=
      UPPER ( <scalar expression> )

 

NULLIF

The NULLIF function compares two expressions. It returns NULL if the expressions are equal. Otherwise, it returns the first expression. It is logically equivalent to the following CASE expression: CASE WHEN expr1 = expr2 THEN NULL ELSE expr1 END.  

Syntax

<NULLIF> ::= 
    ( <scalar expression>, <scalar expression> )

Example  

The following statement returns a row with the last_name value for each row in TABLE1 where the first name is not the same as the last name. If the first_name value is the same as the last_name value, it returns NULL.

SELECT NULLIF(last_name,first_name) FROM TABLE1; 

 

OCTET_LENGTH

The OCTET_LENGTH function gives the length in bytes of a STRING, INPUTSTREAM, or OBJECT value.  

Syntax

<octet_length> ::= OCTET_LENGTH(<expression>)
SELECT * FROM TABLE1 WHERE OCTET_LENGTH(binary_column)>1024;

 

POSITION

The SQL POSITION function returns the position of a string within another string. If any of the arguments evaluate to NULL, the result is NULL.  

Syntax

<position function> ::=
      POSITION ( <string> IN <another> )

Examples

POSITION('BCD' IN 'ABCDEFG') yields 2.
POSITION('' IN 'ABCDEFG') yields 1.
POSITION('TAG' IN 'ABCDEFG') yields 0.

 

SQRT

The SQRT function works on numeric expressions only, and yields the square root of the number passed.  

Syntax

<sqrt function>  ::=  SQRT( <expression> )
SELECT * FROM Scapes WHERE SQRT(HEIGHT*WIDTH - ?) > ?;

 

SUBSTRING

The SQL SUBSTRING function extracts a substring from a given string. If any of the operands are NULL, the result is NULL. The start position indicates the first character position of the substring, where 1 indicates the first character. If FOR is used, it indicates the length of the resulting string.  

Syntax

<substring function> ::= 
    SUBSTRING ( <string expression>
        FROM <start pos> [ FOR <length> ] )

Examples

SUBSTRING('ABCDEFG' FROM 2 FOR 3)

yields 'BCD'.

SUBSTRING('ABCDEFG' FROM 4)

yields 'DEFG'.

SUBSTRING('ABCDEFG' FROM 10)

yields ''.

SUBSTRING('ABCDEFG' FROM -6 FOR 3)

yields 'ABC'.

SUBSTRING('ABCEDFG' FROM 2 FOR -1) 

raises an exception.

TRIM

The SQL TRIM function removes leading and/or trailing padding characters from a given string. The <padding> must be a string of length 1, which is the character that is removed from the string.

  • If <padding> is omitted, space characters are removed.
  • If the <trim spec> is omitted, BOTH is assumed.
  • If both <padding> and <trim spec> are omitted, the FROM keyword must be omitted.

Syntax

<trim function> ::=
    TRIM ( [<trim spec>] [<padding>] [FROM] <scalar expression> )

<trim spec> ::=
    LEADING
    | TRAILING
    | BOTH
<padding> ::= 
    <scalar expression>

Examples

TRIM(' Hello world ')

yields 'Hello world'.

TRIM(LEADING '0' FROM '00000789.75')

yields '789.75'.

USER

The USER function returns the name of the current user; this function is the same as CURRENT_USER.  

Syntax

<user function> ::= USER

Example 

The following statement returns all notes from the INVOICES table that were placed there by the current user.

SELECT * FROM INVOICES
    WHERE SOURCE = USER;

This section describes a number of conventions that are used in the following statements reference. Specifically:

  • Select expressions
  • Unions, intersections, and differences
  • Join expressions
<table expression> ::= <table expression> UNION
[ALL] <table expression> |
<table expression> EXCEPT [ALL] <table expression> |

<table expression> INTERSECT [ALL] <table expression> |
<join expression> | <select expression> | ( <table
expression> )

 

Select Expressions

A select expression is the table expression most often used in a SELECT statement.

  • Specify DISTINCT to remove any duplicates in the result.
  • Specify GROUP BY and HAVING in connection with aggregate functions to calculate summary values from the data in a table. The WHERE clause (if present) limits the number of rows included in the summary. If an aggregate function is used without a GROUP BY clause, a summary for the whole table is calculated. If a GROUP BY clause is present, a summary is computed for each unique set of values for the columns listed in the GROUP BY. Then, if the HAVING clause is present, it filters out complete groups given the conditional expression in the HAVING clause.

Summary queries have additional rules about where columns can appear in expressions:

  • There can be no aggregate functions in the WHERE clause.
  • Column references appearing outside an aggregator must be in the GROUP BY clause.
  • You cannot nest aggregator functions.

Syntax

<select expression> ::=
    SELECT [ ALL | DISTINCT ] <select item commalist>
    FROM <table reference commalist>
        [ WHERE <conditional expression> ]
        [ GROUP BY <column reference commalist> ]
        [ HAVING <conditional expression> ]

 

<select item> ::=
      <scalar expression> [ [AS] <output column name> ]
     | [ <range variable> . ] *

 

<table reference> ::= 
      <join expression>
    | <table name> [ <output table rename> ]
    | ( <table expression> ) [ <output table rename> ]

<output table rename> ::= 
      [AS] <range variable> [ ( <column name commalist> ) ]

<conditional expression> ::=

      <conditional expression> OR <conditional expression>
    | <conditional expression> AND <conditional expression>
    | NOT <conditional expression>
    | <scalar expression> <compare operator> <scalar expression>
    | <scalar expression> <compare operator> { ANY | SOME | ALL }
        (<table expression>)
    | <scalar expression> [NOT] BETWEEN <scalar expression>
    | <scalar expression> [NOT] LIKE <scalar expression>
        [ ESCAPE <scalar expression> ]
    | <scalar expression> [NOT] IS { NULL | TRUE | FALSE | UNKNOWN }
    | <scalar expression> IN ( <scalar expression commalist> )
    | <scalar expression> IN ( <table expression> )
    | EXISTS ( <table expression> )

<column reference> ::=
      [ <table qualifier> . ] <column name>

<scalar expression> ::=
      <scalar expression> {+ | - | * | / | <concat> } <scalar expression>
    | {+ | -} <scalar expression>
    | ( <expression> )
    | ( <table expression> )
    | <column reference>
    | <user defined function reference>
    | <literal>
    | <aggregator function>
    | <function>
    | <parameter marker>

<table name> ::=
      [ <schema name> . ] <SQL identifier>

<schema name> ::= 
      <SQL identifier>

<user defined function reference> ::= 
    <method name> ([ <expression commalist> ])

Example 1 

The following statement yields a single row with the total value of all orders.

SELECT SUM(Amount * Price) FROM Orders;

Example 2 

The following statement returns a single row with the number of orders where Amount is non-null for the customer 123.

SELECT COUNT(Amount) FROM Orders WHERE CustId = 123;

Example 3 

The following statement returns a set of rows where the total value of all orders grouped by customers for the customers with an ID number less than 200.

SELECT CustId, SUM(Amount * Price), COUNT(Amount)
        WHERE CustId < 200 GROUP BY CustId;

Example 4 

The following example yields a set of big customers with the value of all their orders.

SELECT CustId, SUM(Amount * Price), COUNT(Amount) 
  GROUP BY CustId HAVING SUM(Amount * Price) > 500000;

Example 5 

The following statement is illegal because it has nested aggregators.

SELECT CustId, COUNT(23 + SUM(Amount)) GROUP BY CustId;

Example 6 

The following statement is illegal because the CustId column is referenced in the select item list, but it is not present in the GROUP BY reference list.

SELECT CustId, SUM(Amount* Price) GROUP BY Amount;

For the syntax of table expressions see "Table expressions".

Unions, Intersections, and Differences

A table expression is an expression that evaluates to an unnamed table. Of the following operators, INTERSECT binds the strongest and UNION and EXCEPT are equal.

UNION ALL 
Creates the union of two tables including all duplicates. 
UNION 
Creates the union of two tables. If a row occurs multiple times in both tables, the result has this row exactly twice. Other rows in the result have no duplicates. 
INTERSECTION ALL 
Creates the intersection of two tables including all duplicates. 
INTERSECTION 
Creates the intersection of two tables. If a row has duplicates in both tables, the result has this row exactly twice. Other rows in the result has no duplicates. 
EXCEPT ALL 
Creates a table that has all rows that occur only in the first table. If a row occurs m times in the first table and n times in the second, the result holds that row the larger of zero and m-n times. 
EXCEPT 
Creates a table that has all rows that occur only in the first table. If a row occurs m times in the first table and n times in the second, the result holds the row exactly twice if m > 1 and n = 0. Other rows in the result has no duplicates. 

Example 1

SELECT * FROM T1 UNION SELECT * FROM T2 UNION SELECT * FROM T3;

is executed as:

(SELECT * FROM T1 UNION SELECT * FROM T2) UNION SELECT * FROM T3;

Example 2

SELECT * FROM T1 UNION SELECT * FROM T2 INTERSECT SELECT * FROM T3;

is executed as:

SELECT * FROM T1 UNION (SELECT * FROM T2 INTERSECT SELECT * FROM T3);

 

Join Expressions

In Blackfish SQL, join expressions give access to a wide variety of join mechanisms. The two most commonly used, inner joins and cross joins, can be expressed with a SELECT expression alone, but any kind of outer join must be expressed with a JOIN expression.

CROSS JOIN 
A CROSS JOIN B produces the same result set as SELECT A.*, B.* FROM A,B 
INNER JOIN 
A INNER JOIN B ON A.X=B.X produces the same result as SELECT A.*, B.* FROM A,B WHERE A.X=B.X 
LEFT OUTER 
A LEFT OUTER JOIN B ON A.X=B.X produces the rows from the corresponding inner join plus the rows from A that didn't contribute, filling in the spaces corresponding to columns in B with NULLs. 
RIGHT OUTER 
A RIGHT OUTER JOIN B ON A.X=B.X produces the rows from the corresponding inner join plus the rows from B that didn't contribute, filling in the spaces corresponding to columns in A with NULLs. 
FULL OUTER 
A FULL OUTER JOIN B ON A.X=B.X produces the rows from the corresponding inner join plus the rows from A and B that didn't contribute, filling in the spaces corresponding to columns in B and A with NULLs. 
UNION 
A UNION JOIN B produces a result similar to the following: A LEFT OUTER JOIN B ON FALSE UNION ALL A RIGHT OUTER JOIN B ON FALSE a table with columns for all columns in A and B, with all the rows from A having NULL values for columns from B appended with all the rows from B having NULL values for columns from A.  
The following are mutually exclusive: 
 
ON 
ON is an expression that needs to be fulfilled for a JOIN expression. 
USING 
USING( C1, C2, C3) is equivalent to the ON expression above A.C1=B.C1 AND A.C2=B.C2 AND A.C3=B.C3, except that the resulting table has columns C1, C2, and C3 occurring once each as the first three columns. 
NATURAL 
NATURAL is the same as a USING clause with all the column names that appear in both tables A and B. 

Syntax

<join expression> ::=
      <table reference> CROSS JOIN <table reference>
    | <table reference> [NATURAL] [INNER] JOIN <table reference> 
         [ <join kind> ]
    | <table reference> [NATURAL] LEFT [OUTER] JOIN <table reference> 
         [ <join kind> ]
    | <table reference> [NATURAL] RIGHT [OUTER] JOIN <table reference> 
         [ <join kind> ]
   | <table reference> [NATURAL] FULL [OUTER] JOIN <table reference> 
         [ <join kind> ]
   | <table reference> UNION JOIN <table reference>

<table reference> ::= 
      <join expression>
    | <table name> [ <output table rename> ]
          <table reference> CROSS JOIN <table reference>
    | <table reference> [NATURAL] [INNER] JOIN <table reference> 
         [ <join kind> ]
    | <table reference> [NATURAL] LEFT [OUTER] JOIN <table reference> 
         [ <join kind> ]
    | <table reference> [NATURAL] RIGHT [OUTER] JOIN <table reference> 
         [ <join kind> ]
   | <table reference> [NATURAL] FULL [OUTER] JOIN <table reference> 
         [ <join kind> ]
   | <table reference> UNION JOIN <table reference>

<table reference> ::= 
      <join expression>
    | <table name> [ <output table rename> ]| ( <table expression> ) [ <output table rename> ]

 

<output table rename> ::= 
      [AS] <range variable> [ ( <column name commalist> ) ]

<range variable> ::= 
      <SQL identifier>

<join kind> ::= 
      ON <conditional expression>
    | USING ( <column name commalist> )

Examples

SELECT * FROM Tinvoice FULL OUTER JOIN Titem USING ("InvoiceNumber");

SELECT * FROM Tinvoice LEFT JOIN Titem ON Tinvoice."InvoiceNumber" 
    = Titem."InvoiceNumber";

SELECT * FROM Tinvoice NATURAL RIGHT OUTER JOIN Titem;

SELECT * FROM Tinvoice INNER JOIN Titem USING ("InvoiceNumber");

SELECT * FROM Tinvoice JOIN Titem ON Tinvoice."InvoiceNumber" 
    = Titem."InvoiceNumber";

The Blackfish SQL JDBC driver supports a subset of the ANSI/ISO SQL-92 standard. In general, it provides:

  • Data definition language for managing tables and indexes, schemas, views, and security elements.
  • Data manipulation and selection with INSERT, UPDATE, DELETE, and SELECT; but no cursors.
  • Support for general table expressions including JOIN, UNION, and INTERSECT.

For Blackfish SQL for Java, cursor operations are supported through the JDBC version 3.0 ResultSet API. 

Syntax

<SQL statement> ::=
     <data definition statement>
   | <transaction control statement>
   | <data manipulation statement>

 

<data definition statement> ::=
     <create schema statement>
   | <drop schema statement>
   | <create table statement>
   | <alter table statement>
   | <drop table statement>
   | <create view statement>
   | <alter view statement>
   | <drop view statement>
   | <create index statement>
   | <drop index statement>
   | <create method statement>
   | <drop method statement>
   | <create class statement>
   | <drop class statement>
   | <create user statement>
   | <alter user statement>
   | <drop user statement>
   | <create role statement>
   | <drop role statement>
   | <grant statement>
   | <revoke statement>
   | <set role statement>

 

<transaction control statement> ::=
     <commit statement>
   | <rollback statement>
   | <set autocommit statement>
   | <set transaction statement>

<data manipulation statement> ::=
     <select statement>
   | <single row select statement>
   | <delete statement>
   | <insert statement>
   | <update statement>
   | <call statement>
   | <lock statement>

 

CREATE SCHEMA

The CREATE SCHEMA statement creates a name space for tables, views, and methods. You can use it to create multiple objects in one SQL statement.

  • You can create a table, view, or method in an existing schema in two ways:
    • You can create it as part of a CREATE SCHEMA statement.
    • You can specify a schema name as part of the object name when you issue a standalone CREATE TABLE, CREATE VIEW, or CREATE METHOD statement. If you use the latter method (using CREATE TABLE, for example), you must specify a schema name that already exists.
  • To create an object in a new schema, specify a new schema name in the CREATE SCHEMA statement and then create the table, view, or method as part of the CREATE SCHEMA statement.
  • The AUTHORIZATION clause names the owner of the schema. If you do not specify an owner, the owner is the user of the SQL session. Only an administrator can specify a user name other than their own user name in the AUTHORIZATION clause.
  • If you issue a standalone CREATE TABLE, CREATE VIEW, or CREATE METHOD statement (meaning that it s not embedded in a CREATE SCHEMA statement) and you do not specify a schema name as part of the CREATE statement, Blackfish SQL uses the following algorithm to assign the new object to a schema:
    • If you have explicitly created a schema that has the same name as your current user name, then you have created a personal default schema. The table, view, or method belongs to your default schema.
    • If you have not created a personal default schema, the table, view, or method belongs to the DEFAULT_SCHEMA schema.
  • You can create schemas with names other than your user name, but you cannot create schemas that have other users' names unless you have administrative privileges.
  • All objects created in early versions of Blackfish SQL that did not support schemas belong to the DEFAULT_SCHEMA schema when migrated to version 7 or later.
  • A semicolon marks the end of the CREATE SCHEMA statement. There cannot be any semicolons between the schema elements.
  • All the statements in the schema element list are executed as one statement in the same transaction.

 

Default Schemas

Initially your default schema is DEFAULT_SCHEMA. When you create a schema with the same name as your current user name, that schema becomes your default schema. You can create objects without specifying a schema name and those objects automatically belongs to your default schema. Assume, for example, that user PETER created a schema PETER. At a later time, PETER creates a table without specifying a schema. The table belongs to the PETER schema.  

In the following example, the created table would actually be named PETER.FOO.

[USER: PETER]
CREATE TABLE FOO (COL1 INT, COL2 VARCHAR);

You are permitted to create schemas with names other than your user name, but they can never be your default schema. You cannot create a schema that has another user's name unless you are an administrator.  

Syntax

<create schema statement> ::=
    CREATE SCHEMA [ <schema name> ]
        [ AUTHORIZATION <user name> ]
         <schema element list>

<schema name> ::=
        <SQL identifier>

<schema element commalist> ::=
    <create table statement>
  | <create view statement>
  | <create method statement>
  | <grant statement>

See GRANT for more information about GRANT statements. 

Example 

The following statement creates the schema BORIS with a table T1 and a view V1. In this schema, the user BJORN is granted SELECT privileges on view V1. After this statement executes, BORIS is the default schema for user BORIS.

 [USER: BORIS]
 CREATE SCHEMA BORIS
     CREATE TABLE T1 (C1 INT, C2 VARCHAR)
     CREATE VIEW V1 AS SELECT C2 FROM T1
     GRANT SELECT ON V1 TO BJORN;

 

DROP SCHEMA

The DROP SCHEMA statement deletes the specified schema. If the command is used without options, it is the same as specifying the RESTRICT option: the schema to be dropped must be empty. The command fails if the schema contains any objects.

  • The RESTRICT option causes the statement to fail if there are any objects in the schema. RESTRICT is the default option.
  • Used with the CASCADE option, DROP SCHEMA deletes the named schema including all of its tables, views, foreign key dependencies, and methods.

WARNING: The DROP SCHEMA command used with the CASCADE option is extremely powerful and should be used with caution. When this command is issued, it drops the schema and all of its objects and dependencies without any chance to change your mind. There is no undo. 

TIP: If you want to drop a schema but wish to preserve some of its tables, use the ALTER TABLE command to assign the tables to another schema. For example:

ALTER TABLE OLDSCHEMA.JOBS
RENAME TO NEWSCHEMA.JOBS;

Syntax

<drop schema statement> ::=
  DROP SCHEMA <schema name> [ CASCADE | RESTRICT ]

Examples

  1. The following two statements are the same: they drop the schema BORIS; they both fail if the schema contains any objects.
DROP SCHEMA BORIS;

DROP SCHEMA BORIS RESTRICT;
  1. The following statement drops the schema BORIS and all of its tables, views, and methods. It also drops any dependent views and foreign keys.
DROP SCHEMA BORIS CASCADE;

 

CREATE TABLE

The CREATE TABLE statement creates a Blackfish SQL table. Each column definition must include at least a column name and data type. Optionally, you can specify a default value for each column, along with uniqueness constraints.  

You can also optionally specify a foreign key and primary key. Blackfish SQL supports the use of one or more columns as a primary key or foreign key.

Specifying Schemas

To create a table in a particular schema, specify the schema name as part of the table name:

CREATE TABLE SOMESCHEMA.MYTABLE(. . .);

If you do not specify a schema name, the table is created in your default schema. See CREATE SCHEMA for more information about schemas.

Tracking Data Changes for DataExpress

Note: This feature is supported for Blackfish SQL for Java, only.
If you specify RESOLVABLE as part of the table definition, Blackfish SQL keeps track of changes made to the data. The recorded changes are available to the DataExpress application, but not to SQL. The default is NOT RESOLVABLE.

Overriding Consistency Checks

The NO CHECK option creates the foreign key without checking the consistency at creation time. Use this option with caution.

Using AutoIncrement Columns with SQL

To create or alter a column to have the Autoincrement property using SQL, add the AUTOINCREMENT keyword to your <table element> definition.  

The following statement creates table T1 with an integer autoincrement column called C1:

CREATE TABLE T1 ( C1 INT AUTOINCREMENT, C2 DATE, C3 CHAR(32) );

To obtain the Autoincrement value of a newly inserted row using the JDS JDBC driver (JVM version 1.3 or earlier), call the JdsStatement.getGeneratedKeys method. This method is also available in the statement interface of JDBC 3 in JVM 1.4.)

Specifying Column Position

In the columns definition, use the POSITION option to force a column to be in a particular position in the table (second column, for example). The following code snippet forces column COLD to be the second column:

CREATE TABLE(COLA INT, COLB STRING, COLC INT, COLD STRING POSITION 2);

Syntax

<create table statement> ::=  
      CREATE TABLE <table name> ( <table element commalist> )

 

<table name> ::=
      [ <schema name> . ] <SQL identifier>

<schema name> ::=
      <SQL identifier>

 

<table element> ::=
        <column definition> 
       | <primary key> 
       | <unique key> 
       | <foreign key>
       | [NOT] RESOLVABLE 

 

<column definition> ::=   
    <column name> <data type> 
    [ DEFAULT <default value> ]
    [ [NOT] NULL ]
    [ AUTOINCREMENT ]
    [ POSITION <integer literal> ]
    [ [ CONSTRAINT <constraint name> ] PRIMARY KEY ]
    [ [ CONSTRAINT <constraint name> ] UNIQUE ]
    [ [ CONSTRAINT <constraint name> ] <references definition> ]

 

<column name> ::=  
      <SQL identifier>
                                                        
<default value> ::=   
      <literal> 
      | <current date function>

 

<current date function> ::=
      CURRENT_DATE
     | CURRENT_TIME
     | CURRENT_TIMESTAMP

 

<primary key> ::=
         [ CONSTRAINT <constraint name> ] PRIMARY KEY <column name commalist>)

<unique key> ::=  
    [ CONSTRAINT <constraint name> ] UNIQUE ( <column name commalist> )                                                        

<foreign key> ::=
      [ CONSTRAINT <constraint name> ] FOREIGN KEY ( <column name commalist> )
         <references definition>

<references definition> ::=
     REFERENCES <table name> [ ( <column name commalist> ) ]  
     [ ON DELETE <action> ] 
     [ ON UPDATE <action> ]  
     [ NO CHECK ]
  
<action> ::= 
     NO ACTION  
    | CASCADE  
    | SET DEFAULT 
    | SET NULL
                                                        
<constraint name> ::=  
    <SQL identifier>

Example 1 

The following statement creates a table with four columns. The CustId column is the primary key and the OrderDate column has the current time as the default value.

CREATE TABLE Orders ( CustId INTEGER PRIMARY KEY, Item VARCHAR(30), 
     Amount INT, OrderDate DATE DEFAULT CURRENT_DATE);

Example 2 

The following statement creates a table that uses two columns for the primary key constraint:

CREATE TABLE T1 (C1 INT, C2 STRING, C3 STRING, PRIMARY KEY (C1, C2));

Example 3 

The following statement creates a table T1 in the BORIS schema:

CREATE TABLE BORIS.T1 (C1 INT, C2 STRING, C3 STRING);

 

ALTER TABLE

The ALTER TABLE statement performs the following operations:

  • Adds or removes columns in a Blackfish SQL table
  • Sets or drops column defaults and NULLability
  • Changes column data types
  • Adds or drops primary key, unique key, and foreign key column constraints and table constraints; changes the referenced table and type of action for these constraints
  • Renames columns
  • Renames tables; this also allows you to move tables from one schema to another
  • Adds or drops the RESOLVABLE table property
  • Repositions columns within the table

Syntax

<alter table statement> ::= 
    ALTER TABLE <table name> <change definition commalist>
                                                       
<table name> ::=  [ <schema name> . ]<SQL identifier>

 

<change definition> ::=
      <add column element>
    | <drop column element>
    | <alter column element>
    | <add constraint>
    | <drop constraint>
    | [RENAME] TO <table name>
    | [NOT] RESOLVABLE

<add column element> ::= ADD [COLUMN] <column definition>

<column definition> ::=
       <column name> <data type>     [ DEFAULT <default value> ]
    [ [NOT] NULL ]
    [ AUTOINCREMENT ]
    [ POSITION <integer literal> ]
    [ [ CONSTRAINT <constraint name> ] PRIMARY KEY ]
    [ [ CONSTRAINT <constraint name> ] UNIQUE ]
    [ [ CONSTRAINT <constraint name> ] <references definition> ]

<drop column element> ::= DROP [COLUMN] <column name>

 

<alter column element> ::= 
       ALTER [COLUMN] <column name> [TYPE] <data type>
     | ALTER [COLUMN] <column name> SET DEFAULT <default-value>
     | ALTER [COLUMN] <column name> DROP DEFAULT
     | ALTER [COLUMN] <column name> [NOT] NULL
     | ALTER [COLUMN] <column name> [RENAME] TO <column name>
     | ALTER [COLUMN] <column name> [POSITION] <integer literal>
     | ALTER [COLUMN] <column name> AUTOINCREMENT
     | ALTER [COLUMN] <column name> DROP AUTOINCREMENT

<add constraint> ::= ADD <base table constraint>

<base table constraint> ::=
    <primary key> |  <unique key> |  <foreign key>

<drop constraint> ::= DROP CONSTRAINT <constraint name>

<primary key> ::= 
    [ CONSTRAINT <constraint name> ]
    PRIMARY KEY <column name commalist>)

<unique key> ::=  
    [ CONSTRAINT <constraint name> ] 
      UNIQUE ( <column name commalist> )

<foreign key> ::=  
    [ CONSTRAINT <constraint name> ]
       FOREIGN KEY ( <column name commalist> )
   <references definition>
                          
<references definition> ::= 
      REFERENCES <table name> [ ( <column name commalist> ) ]  
    [ ON DELETE <action> ] 
    [ ON UPDATE <action> ]  
    [ NO CHECK ]

<action> ::= 
        NO ACTION  
    | CASCADE  
    | SET DEFAULT 
    | SET NULL
                                                       
<constraint name> ::=  <SQL identifier>

In ALTER [COLUMN], the optional COLUMN keyword is included for SQL compatibility. It has no effect.  

Example  

The following example adds a column named ShipDate to the Orders table and drops the Amount column from the table.

ALTER TABLE Orders
    ADD ShipDate DATE, 
     DROP Amount;

The following example moves the Jobs table from the OldSchema schema to the NewSchema schema.

ALTER TABLE OldSchema.Jobs
 RENAME TO NewSchema.Jobs;

 

DROP TABLE

The DROP TABLE statement deletes a table and its indexes from a Blackfish SQL database.

  • The RESTRICT option guarantees that the statement will fail if there are foreign key or view dependencies on the table.
  • The CASCADE option causes all dependent views and foreign keys to be dropped when the table is dropped.
  • Specifying neither RESTRICT nor CASCADE drops the table and any foreign keys that reference it. The statement fails if there are dependent views.

Syntax

<drop table statement> ::=
      DROP TABLE [ <schema name> . ]<table name> [ CASCADE|RESTRICT ]

<schema name> ::= <SQL identifier>

Examples

  1. The following statement drops the Orders table only if there are no dependent views. If there are dependent foreign keys, the statement succeeds and the foreign keys are dropped.
DROP TABLE Orders; 
  1. The following statement drops the Orders table only if there are no dependent views or foreign keys.
DROP TABLE Orders RESTRICT;
  1. The following statement drops the Orders table. All dependent views and dependent foreign keys are also dropped.
DROP TABLE Orders CASCADE;

 

CREATE VIEW

The CREATE VIEW statement creates a derived table by selecting specified columns from existing tables. Views provide a way of accessing a consistent subcollection of the data stored in one or more tables. When the data in the underlying tables changes, the view reflects this change.  

Views look just like ordinary database tables, but they are not physically stored in the database. The database stores only the view definition, and uses this definition to filter the data when a query referencing the view occurs.  

When you create a view, you can specify names for the columns in the view using the optional <column name commalist> portion of the syntax. If you do not specify column names, the names of the table columns from which the view columns are derived are used. If you do specify column names, you must specify exactly the number of columns that will be returned from the SELECT query.  

The WITH CHECK OPTION clause causes a runtime check to be performed to ensure that an inserted or updated row will not be filtered out by the WHERE clause of the view definition.  

Views are updatable only under limited conditions. If you want to execute INSERT, UPDATE, or DELETE on a view, it must meet all of the following conditions:

  • It is derived from a single table.
  • None of the columns are calculated.
  • The SELECT clause that defines the view does not contain the DISTINCT keyword.
  • The SELECT expression that defines the view does not contain any of the following:
    • Subqueries
    • A HAVING clause
    • A GROUP BY clause
    • An ORDER BY clause
    • Aggregate functions
    • methods

Syntax

<create view statement> ::=
     CREATE VIEW <view name> [ ( <column name commalist> ) ]
    AS <select expression> [ WITH CHECK OPTION ]

<view name> ::=
    [ <schema name> . ] <SQL identifier>

Example 

The following statement creates a view V1 from table T1. The columns in the view are named C1 and C2.

CREATE VIEW V1(C1,C2)
     AS SELECT  C8+C9, C6 FROM T1 WHERE C8 < C9;

 

ALTER VIEW

The ALTER VIEW statement modifies a view without losing dependent views and existing GRANTs. This statement can be used to change the name of a view, the columns that comprise the view, and whether the view has the WITH CHECK OPTION constraint.  

Note that after ALTER VIEW executes, it is possible that there are dependent views that are no longer valid.  

Syntax

<alter view statement> ::=
     ALTER VIEW <view name> [ ( <column name commalist> ) ]

    AS <select expression> [ WITH CHECK OPTION ]

Example 

The following statements show how the ALTER VIEW statement can be used to validate an invalid view. The first two statements create a table and then create a view based on that table. The third statement, SELECT, succeeds.

CREATE TABLE T1 (C1 INT, C2 VARCHAR);
CREATE VIEW V1 AS SELECT C1, C2 FROM T1;
SELECT * FROM V1;

The following statement changes a column name in the table.

ALTER TABLE T1 ALTER COLUMN C1 RENAME TO ID;

The next SELECT statement therefore fails because there is no longer a C1 column in the table T1, which is accessed by view V1.

SELECT * FROM V1;

The following ALTER VIEW statement changes the definition of the view, so that the next SELECT statement succeeds.

ALTER VIEW V1 (C1, C2) AS SELECT ID, C2 FROM T1;
SELECT * FROM V1;

 

DROP VIEW

The DROP VIEW statement drops the named view. It fails if there are dependencies on the view.

  • The RESTRICT option is the same as specifying no options: the statement fails if there are dependencies on the view.
  • The CASCADE option drops the view and any dependent views.

Syntax

<drop view statement> ::=
     DROP VIEW <view name> [ CASCADE | RESTRICT ]

Example 

The following code creates a table and two views:

CREATE TABLE T1 (C1 INT, C2 VARCHAR);
CREATE VIEW V1 AS SELECT C1, C2 FROM T1;
CREATE VIEW V2 AS SELECT C1, C2 FROM V1;

The following statement fails because view V1 has a dependent view (V2).

DROP VIEW V1 RESTRICT;

The following statement succeeds and both V1 and V2 are dropped.

DROP VIEW V1 CASCADE;

 

CREATE INDEX

The CREATE INDEX statement creates an index for a Blackfish SQL table. Each column can be ordered in ascending or descending order. The default value is ascending order.  

Syntax

<create index statement> ::=

      CREATE [UNIQUE] [CASEINSENSITIVE] INDEX <index name>
           ON <table name> ( <index element commalist> )
<table name> ::=  
    [ <schema name> . ]<SQL identifier>
                                                        
<index name> ::= 
      <SQL Identifier>
                                                        
<index element> ::= 
      <column name> [ DESC|ASC ]

Example 

The following statement generates a non-unique, case-sensitive, ascending index on the Item column of the Orders table:

CREATE INDEX OrderIndex ON Orders (Item ASC);

 

DROP INDEX

The DROP INDEX statement deletes an index from a Blackfish SQL table.  

Syntax

<drop index statement> ::=
      DROP INDEX <index name> ON <table name>

Example 

The following statement deletes the OrderIndex index from the Orders table:

DROP INDEX OrderIndex ON Orders;

 

CREATE METHOD

The CREATE METHOD statement makes a stored procedure or a UDF implemented in Java or a .NET language (e.g., Delphi, C#, or VB.NET) available for use in Blackfish SQL. The class files for the code must be added to the classpath of the Blackfish SQL server process before use. See Stored Procedures and UDFs for details about how to implement stored procedures and UDFs for Blackfish SQL.  

To create a method in a particular schema, specify the schema name as part of the table name:

CREATE METHOD SOMESCHEMA.MYMETHOD AS . . .

If you do not specify a schema name, the method is assigned to a schema as follows:

  • If you have created a personal default schema (a schema that has the same name as your user name), the method is created in that schema.
  • If you have have not created a personal default schema, the method is created in the DEFAULT_SCHEMA schema.

See CREATE SCHEMA for more information about schemas. The AUTHORIZATION clause causes the called stored procedure to be run as if the username in the AUTHORIZATION clause were the actual user. If this clause is omitted, the current_user is used as the actual user during method calls. This feature allows the current user controlled access to tables and views that would not otherwise be accessible. Syntax

<create method statement> ::= 
    CREATE METHOD <method name> [AUTHORIZATION <username>]
         AS <method definition>
                                                          
<method name> ::= 
    [ <schema name> . ] <SQL identifier>
                                                        
<schema name> ::= <SQL identifier>
                                                        
<method definition> ::= <string literal>
CREATE METHOD ABS AS 'MathClass.abs';

 

DROP METHOD

The DROP METHOD statement drops a stored procedure or a UDF, making it unavailable for use in Blackfish SQL SQL.  

Syntax

<drop method statement> ::= 
     DROP METHOD <method_name>
DROP METHOD ABS;

 

CREATE CLASS

The CREATE CLASS statement makes all public static methods of a class available to Blackfish SQL SQL as stored procedures or UDFs. You must ensure that the class files for the code are on the classpath of the Blackfish SQL server process before use. See the Stored Procedures and UDFs chapter for details.  

The AUTHORIZATION clause causes the called stored procedure to be run as if the username in the AUTHORIZATION clause were the actual user. If this clause is omitted, the current_user is used as the actual user during method calls. This feature allows the current user controlled access to tables and views that would not otherwise be accessible.  

Syntax

<create class statement> ::=
    CREATE CLASS <class name> [AUTHORIZATION <username>] 
        AS <class definition>
                                                           
<class name> ::=
    [ <schema name> . ] <SQL identifier>
                                                         
<schema name> ::= <SQL identifier>
                                                         
<class definition> ::= <string literal>

Examples

CREATE CLASS MATH AS 'mscorlib::System.Math';

After the above statement executes, all public static methods in System.Math can be called from SQL. Note that the method names are case sensitive. 

Usage 

The following statement calls the Abs() method in System.Math:

SELECT * FROM CUSTOMER WHERE MATH."Abs"(AGE - 50) < 5;

 

DROP CLASS

The DROP CLASS statement drops a stored class, making it unavailable for use in Blackfish SQL.  

Syntax

<drop class statement> ::=
   DROP CLASS <method_name>
DROP CLASS MATH;

 

CREATE TRIGGER

The CREATE TRIGGER statement creates a row level trigger for a table. You must ensure that the classes can be loaded by the Blackfish SQL server process. See Triggers for Blackfish SQL for details on implementing trigger methods and ensuring that the method classes can be loaded.  

Syntax

create trigger statement> ::= CREATE TRIGGER  <trigger name>  
      

           <trigger action time> <trigger action name> 
      

          ON <table name> AS <trigger spec>

       <trigger name> ::=   <SQL identifier> 

        <tablename> ::= <SQL identifier> 

        <triggeraction time> ::= <BEFORE | AFTER> 

         <trigger action name> ::= <INSERT | UPDATE | DELETE > 

       
      Blackfish SQL for Java: 
         <trigger spec> ::= "[<package>.]<class-name>.<method-name>" 
      Blackfish SQL for windows: 
      <trigger spec> ::="<assembly-name>::[<name-space>.]<class-name>.<method-name>" 
      

Examples  

Blackfish SQL for Windows:

 CREATE
TRIGGER VALIDATE_CUSTOMER BEFORE INSERT ON CUSTOMER AS

 OrderEntryAssembly::OrderEntry.Customers.ValidateCustomer

Blackfish SQL for Java:

CREATE TRIGGER VALIDATE_CUSTOMER BEFORE INSERT ON CUSTOMER AS 

OrderEntry.Customers.validateCustomer 

 

DROP TRIGGER

The DROP TRIGGER statement drops a trigger, making it unavailable for use in Blackfish SQL.  

Syntax

<drop trigger statement> ::= DROP TRIGGER 
<trigger
name> 

            ON <table name> 

      

        <trigger name> ::=  <SQL identifier>
      

        <table name> ::= <SQL identifie
DROP TRIGGER VALIDATE_CUSTOMER on CUSTOMER 

 

COMMIT

The COMMIT statement commits the current transaction. It has an effect only if AUTOCOMMIT is turned off.  

Syntax

<commit statement> ::= 
      COMMIT [WORK]

 

ROLLBACK

The ROLLBACK statement rolls back the current transaction. This statement does not have any effect when AUTOCOMMIT is turned on. 

Syntax

<rollback statement> ::= 
      ROLLBACK [WORK]

 

SET AUTOCOMMIT

The SET AUTOCOMMIT statement changes the autocommit mode. Autocommit is initially ON when a JDBC connection is created.  

The autocommit mode is also controllable using the JDBC Connection instance.  

Syntax

<set autocommit statement> ::= 
    SET AUTOCOMMIT { ON | OFF };

 

SET TRANSACTION

The SET TRANSACTION statement sets the properties for the following transaction. You can use it to specify the isolation level and whether the transaction is read-write or read-only. See System Architecture for a discussion of Blackfish SQL transaction management.  

This command must be issued when there is no open transaction. It affects only the next transaction and does not itself start a transaction.  

To understand isolation levels, you should understand the following terms:

  • A dirty read occurs when a row changed by one transaction is read by another transaction before any changes in that row have been committed.
  • A non-repeatable read occurs when one transaction reads a row, a second transaction alters the row, and the first transaction rereads the row, getting different values the second time.
  • A phantom read occurs when one transaction reads all rows that satisfy a WHERE condition, a second transaction inserts a row that satisfies that WHERE condition, and the first transaction rereads for the same condition, retrieving the additional "phantom" row in the second read.

Blackfish SQL offers the following transaction isolation levels: TRANSACTION_READ_UNCOMMITTED permits dirty reads, non-repeatable reads, and phantom reads. If any of the changes are rolled back, the row retrieved by the second transaction is invalid. This isolation level does not acquire row locks for read operations. It also ignores exclusive row locks held by other connections that have inserted or updated a row.  

TRANSACTION_READ_COMMITTED prevents dirty reads; non-repeatable reads and phantom reads are permitted. This level only prohibits a transaction from reading a row with uncommitted changes in it. This level does not acquire row locks for read operations, but blocks when reading a row that has an exclusive lock held by another transaction.  

TRANSACTION_REPEATABLE_READ prevents dirty reads and non-repeatable reads but prevents phantom reads. It acquires shared row locks for read operations. This level provides protection for transactionally consistent data access without the reduced concurrency of TRANSACTION_SERIALIZABLE, but results in increased locking overhead.  

TRANSACTION_SERIALIZABLE provides complete serializability of transactions at the risk of reduced concurrency and increased potential for deadlocks.  

Syntax

<set transaction statement> ::= 
    SET TRANSACTION <transaction option commalist>
                                                        
<transaction option> ::=
    READ ONLY
  | READ WRITE
  | ISOLATION LEVEL <isolation level>
                                                        
<isolation level> ::=
    READ UNCOMMITTED
  | READ COMMITTED
  | REPEATABLE READ
  | SERIALIZABLE

Example 

In the following example the select from T1 will be a dirty read, meaning that the data cannot yet be committed by another user. After the second COMMIT, the isolation level returns to whatever was specified for the session.

COMMIT;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
SELECT * FROM T1;
COMMIT;

 

SELECT

A SELECT statement retrieves data from one or more tables. The optional keyword DISTINCT eliminates duplicate rows from the result set. The keyword ALL, which is the default, returns all rows including duplicates. The data can optionally be sorted using ORDER BY. The retrieved rows can optionally be locked for an upcoming UPDATE by specifying FOR UPDATE.  

Syntax

<select statement> ::= 
    <table expression> [ ORDER BY <order item list> ]
        [ FOR UPDATE|FOR READ ONLY ]

<table expression> ::=
      <table expression> UNION [ALL] <table expression>
    | <table expression> EXCEPT [ALL] <table expression>
    | <table expression> INTERSECT [ALL] <table expression>
    | <join expression>
    | <select expression>
    | ( <table expression> )

<order item> ::= <order part> [ ASC|DESC ]

<order part> ::=
     <integer literal> | <column name> | <expression>

<select expression> ::=
    SELECT [ ALL|DISTINCT ] <select item commalist>
    FROM <table reference commalist>
        [ WHERE <conditional expression> ]
        [ GROUP BY <column reference commalist> ]
        [ HAVING <conditional expression> ]

Examples 

The following statement orders the output by the first column in descending order.

SELECT Item FROM Orders ORDER BY 1 DESC;

The next statement orders by the calculated column CALC:

SELECT CustId, Amount*Price+500.00 
    AS CALC FROM Orders 
    ORDER BY CALC;

The next statement orders the output by the given expression, Amount*Price:

SELECT CustId, Amount 
    FROM Orders 
    ORDER BY Amount*Price;

 

SELECT INTO

A SELECT INTO statement is a SELECT statement that evaluates into exactly one row, whose values are retrieved in output parameters. It is an error if the SELECT evaluates into more than one row or to the empty set.  

Syntax

<single row select statement> ::=
     SELECT [ ALL|DISTINCT ] <select item commalist>
        INTO <parameter commalist>
        FROM <table reference commalist>
            [ WHERE <conditional expression> ]
            [ GROUP BY <column reference commalist> ]
            [ HAVING <conditional expression> ]

Example 

In the following statement, the first two parameter markers indicate output parameters from which the result of the query can be retrieved:

SELECT CustId, Amount
     INTO ?, ? 
     FROM Orders 
     WHERE CustId=? ;

 

INSERT

The INSERT statement inserts rows into a table in a Blackfish SQL database. The INSERT statement lists columns and their associated values. Columns that aren't listed in the statement are set to their default values.  

Syntax

<insert statement> ::=
    [ SELECT AUTOINCREMENT FROM ]
    INSERT INTO <table name> [ ( <column name commalist> ) ]
        [ <insert table expression>|DEFAULT VALUES ]

<table name> ::=
      [ <schema name> . ]<SQL identifier>

<insert table expression> ::=
      <select expression>     |  VALUES ( <expression commalist> )

Example 1 

The following statement inserts one row each time it is executed. It inserts one row each time it is executed. The columns not mentioned are set to their default values. If a column doesn't have a default value, it is set to NULL.

INSERT INTO Orders (CustId, Item) VALUES (?,?);

Example 2  

The following statement finds all the orders from the customer with CustId of 123 and inserts the Item of these orders into the ResTable table.

INSERT INTO ResTable 
    SELECT Item FROM Orders 
    WHERE CustId = 123;

Example 3 

The following statement inserts one row each time it is executed. In this case, the CustId column of the Orders table is not specified. It is assumed that the CustId is an AUTOINCREMENT column, for which the SQL engine automatically generates an incremented value. In this example, SELECT AUTOINCREMENT FROM is specified, causing the generated value to be returned as a result set. If the Orders table does not have an AUTOINCREMENT column, and the result set will be the INTERNALROW values for the inserted rows.

SELECT AUTOINCREMENT FROM INSERT INTO Orders (Item) VALUES (?)

 

UPDATE

The UPDATE statement is used to modify existing data. The columns to be changed are listed explicitly. All the rows for which the WHERE clause evaluates to TRUE are changed. If no WHERE clause is specified, all rows in the table are changed.  

Syntax

<update statement> ::=
      UPDATE <table name> 
      SET <update assignment commalist>
    [ WHERE <conditional expression> ]
                                                        
<table name> ::=  
    [ <schema name> . ] <SQL identifier>

<update assignment> ::=
      <column reference> = <update expression>

<update expression> ::=
      <scalar expression>
    | DEFAULT
    | NULL

Example 1 

The following statement changes all orders from customer 123 to orders from customer 500:

UPDATE Orders SET CustId = 500 WHERE CustId = 123;

Example 2  

The following statement increases the amount of all orders in the table by 1:

UPDATE Orders SET Amount = Amount + 1;

Example 3  

The following statement reprices all disposable underwater cameras to $7.25:

UPDATE Orders SET Price = 7.25 
    WHERE Price > 7.25 AND Item = 'UWCamaras';

 

DELETE

A DELETE statement deletes rows from a table in a Blackfish SQL database. If no WHERE clause is specified, all the rows are deleted. Otherwise only the rows that match the WHERE expression are deleted.  

Syntax

<delete statement> ::=
      DELETE FROM <table name>
    [ WHERE <conditional expression> ]

 

<table name> ::=  
                                                            [ <schema name> . ] <SQL identifier>

Example  

The following statement deletes all orders for shorts from the Orders table.

DELETE FROM Orders WHERE Item = 'Shorts';

 

CALL

A CALL statement calls a stored procedure.  

Syntax

<call statement>  ::=
     [ ? = ] CALL <method name> ( <expression commalist> )

Example 1 

The parameter marker indicates an output parameter position from which the result of the stored procedure can be retrieved.

?=CALL ABS(-765);

Example 2 

The method implementing IncreaseSalaries updates the salaries table with an increase of some percentage for all employees. A connection object will be passed implicitly to the method. An updateCount of all the rows affected by IncreaseSalaries will be returned from Statement.executeUpdate.

CALL IncreaseSalaries(10);

 

LOCK TABLE

The LOCK TABLE statement explicitly locks a table. The lock ceases to exist when the transaction is committed or rolled back.  

Syntax

<lock statement>  ::=
    `LOCK <table name commalist>

 

<table name> ::=  
    [ <schema name> . ] <SQL identifier>

Example  

The following statement locks the Orders and LineItems tables.

LOCK Orders, LineItems;

 

CREATE USER

The CREATE USER statement adds the named user and associated password to the database. Only an administrator can create users.

Note: The password that you enter is always case sensitive. The user name is not case-sensitive.
A newly created user has all database privileges except ADMINISTRATOR by default. That is, they have STARTUP, WRITE, CREATE, DROP, CREATE ROLE, and CREATE SCHEMA privileges. If you wish to remove certain privileges from a user, use REVOKE to remove them.  

Syntax

<create user statement> ::= 
    CREATE USER <user name> PASSWORD <SQL identifier>
CREATE USER jmatthews PASSWORD "@nyG00dPas2d";

 

ALTER USER

The ALTER USER statement sets a new password for an existing user. Only an administrator or the named user can change a password.

Note: The password that you enter is stored in all caps unless you enclose the password string in double quotation marks. It is recommended that you always use the double quotes when specifying the password.
Syntax

<alter user statement> ::= 
    ALTER USER <user name> SET PASSWORD <SQL identifier>
ALTER USER GSMITH SET PASSWORD "usethisOnen0w";

 

DROP USER

The DROP USER statement drops a user and all objects that the user owns.

  • Used with RESTRICT or with no option, the statement fails if the user owns any objects, such as tables, views, or methods.
  • Used with CASCADE, it deletes the user and all objects that the user owns.

Syntax

<drop user statement> ::= 
    DROP USER <user name> [ CASCADE|RESTRICT ]

Example  

The following statement drops the user gsmith and all tables, views, and methods that he owns.

DROP USER gsmith CASCADE;

 

CREATE ROLE

The CREATE ROLE statement creates a named role.  

Using roles is a four-step process:

  • Create a role using the CREATE ROLE statement.
  • Grant privileges to the role using the GRANT statement.
  • Grant the role to one or more users using the GRANT statement, thus authorizing that user to use that role.
  • An authorized user accesses the privileges granted to a role by using the SET ROLE statement.

To create a role, the user must have the CREATE ROLE system privilege. All users have this by default, but this privilege can be explicitly revoked. Syntax

<create role statement> ::= 
    CREATE ROLE <role name>
CREATE ROLE salesperson;

 

SET ROLE

The SET ROLE statement makes the named role active. The current user acquires all privileges assigned to that role. Use SET ROLE NONE to deactivate the current role without setting another role.

Note: This command must be issued when there is no active transaction. The role remains active until the end of the session or until another SET ROLE command is issued.
Syntax

<set role statement> ::= 
    SET ROLE <role specification>
                                                        
<role specification> ::=
    NONE
  | <role name>

Example 

The following statement makes the Manager role active:

SET ROLE Manager;

The following statement removes the active role and makes no roles active:

SET ROLE NONE;

 

DROP ROLE

The DROP ROLE statement drops the specified role.

  • When DROP ROLE is used with CASCADE, all privileges that were granted through this role are revoked.
  • When DROP ROLE is used with RESTRICT, the statement fails if the role is currently granted to any users or roles.
  • Issuing DROP ROLE with neither option is the same as DROP ROLE with RESTRICT.

Syntax

<drop role statement> ::= 
     DROP ROLE <role name> [ CASCADE|RESTRICT ]

Example 

The following statement drops the Sales role. All privileges that were granted to users or other roles through the Sales role are revoked.

DROP ROLE Sales CASCADE;

 

GRANT

The GRANT statement performs the following three actions:

  • It grants object privileges, such as INSERT or SELECT, on tables or methods to PUBLIC, users, or roles.
  • It grants database privileges (for example, STARTUP or RENAME) to users or roles.
  • It grants roles to users or roles.

GRANT options:

  • When object privileges are granted with the GRANT option, the grantee has the power to pass on the granted object privileges to other users.
  • When database privileges or roles are granted with the ADMINISTRATOR option, the grantee has the power to pass on the granted database privileges or roles to other users.
  • The ADMINISTRATOR database privilege grants STARTUP, WRITE, CREATE, DROP, RENAME, CREATE ROLE, and CREATE SCHEMA privileges. When these privileges are acquired through the ADMINISTRATOR privilege, they can be revoked only by revoking the ADMINISTRATOR privilege. In other words, if you grant ADMINISTRATOR to a user and then revoke CREATE, that user still has CREATE privileges.

Note that when specifying the privilege object, you can use the optional TABLE keyword to grant privileges on either tables or views. You do not use the VIEW keyword in this context. You can also revoke privileges on a method, using the required METHOD keyword. It is possible to grant the following database privileges:

Privilege 
Description 
ADMINISTRATOR 
Grants startup, write, create, drop, rename, create role, and create schema privileges 
STARTUP 
User can start the database 
WRITE 
User can write to the database 
CREATE 
User can create tables 
DROP 
User can drop tables 
RENAME 
User can rename tables 
CREATE ROLE 
User can create roles 
CREATE SCHEMA 
User can create schemas 

CREATE ROLE and CREATE SCHEMA are granted by default when a user is created. 

Syntax

<grant statement> ::=
      <grant database privileges statement>
    | <grant object privileges statement>
    | <grant role statement>

<grant database privileges statement> ::=
      GRANT <database privilege commalist>
      TO <grantee commalist>
      [ WITH ADMIN OPTION ]

<grant object privileges statement> ::=
      GRANT < object privileges>
      ON <privilege object>
      TO <grantee commalist>
      [ WITH GRANT OPTION ]
      [ GRANTED BY <grantor> ]

<grant role statement> ::=
      GRANT <role name commalist>
      TO <grantee commalist>
      [ WITH ADMIN OPTION ]
      [ GRANTED BY <grantor> ]

<database privilege> ::=
      STARTUP
    | ADMINISTRATOR
    | WRITE
    | CREATE
    | DROP
    | RENAME
    | CREATE ROLE
    | CREATE SCHEMA

<grantee> ::=
      PUBLIC
    | <user name>
    | <role name>

<object privileges> ::=
      ALL PRIVILEGES
    | <privilege commalist>

<privilege>::=
      SELECT
    | INSERT [ ( <column name commalist> ) ]
    | UPDATE [ ( <column name commalist> ) ]
    | REFERENCES [ ( <column name commalist> ) ]
    | DELETE
    | EXECUTE

<privilege object> ::=
      [TABLE] <table name or view name>
    | METHOD <method name> <grantor> ::=
      CURRENT_USER
    | CURRENT_ROLE

Examples 

In the following example, USER_1 receives SELECT and INSERT privileges on table T1. USER_2 receives SELECT privileges on table T1 because the SELECT privilege was granted to ROLE_B and ROLE_B was granted to USER_2. However, USER_2 can use this SELECT privilege only after enabling ROLE_B with a SET ROLE statement.

GRANT SELECT ON TABLE T1 TO USER_1, ROLE_B;
GRANT INSERT ON T1 TO USER_1;

GRANT ROLE_B TO USER_2;

 

REVOKE

The REVOKE statement can perform the following operations:

  • It revokes object privileges, such as INSERT or SELECT, on tables or methods from PUBLIC, users, or roles.
    • If the user or role has granted the now-revoked privilege to others, CASCADE revokes the privileges from those others as well. If any views depend on the revoked privileges, they are dropped.
    • When the REVOKE statement includes RESTRICT, the statement fails if the grantee has granted the acquired privileges to others.
  • It revokes database privileges&mdash;such as STARTUP or RENAME&mdash;from users or roles.
  • It revokes roles from users or roles.
  • It revokes the ADMIN option from a role without revoking the role itself.
  • REVOKE GRANT OPTION FOR privilege revokes the power to grant the privilege to others without revoking the privilege itself. REVOKE ADMIN OPTION FOR role similarly revokes the power to grant the named role without revoking the role itself.

Note that when specifying the privilege object, you can use the optional TABLE keyword to revoke privileges on either tables or views. You do not use the VIEW keyword in this context. You can also revoke privileges on a method, using the required METHOD keyword. Syntax

<revoke statement> ::=
      <revoke database privileges statement>
    | <revoke object privileges statement>
    | <revoke role statement>

<revoke database privileges statement> ::=
      REVOKE <database privilege commalist>
      FROM <grantee commalist>

<revoke object privileges statement> ::=
      REVOKE [ GRANT OPTION FOR ] < object privileges>
          ON <privilege object>
           FROM <grantee commalist>
      [ GRANTED BY <grantor> ]
      [ CASCADE|RESTRICT ]

<revoke role statement> ::=
      REVOKE [ ADMIN OPTION FOR ] <role name commalist>
      FROM <grantee commalist>
      [ GRANTED BY <grantor> ]
      [ CASCADE|RESTRICT ]

<database privilege> ::=
      STARTUP
    | ADMINISTRATOR
    | WRITE
    | CREATE
    | DROP
    | RENAME
    | CREATE ROLE
    | CREATE SCHEMA

<grantee> ::=
      PUBLIC
    | <user name>
    | <role name>

<object privileges> ::=
      ALL PRIVILEGES
    | <privilege commalist>

<privilege>::=
      SELECT
    | INSERT [ ( <column name commalist> ) ]
    | UPDATE [ ( <column name commalist> ) ]
    | REFERENCES [ ( <column name commalist> ) ]
    | DELETE
    | EXECUTE

<privilege object> ::=
      [TABLE] <table name or view name>
    | METHOD <method name> <grantor> ::=
      CURRENT_USER
    | CURRENT_ROLE

Example 1 

In all of the following examples, the name before the colon is the nameof the user executing the statement. 

The following GRANT statements are issued by users U1, U2, and U3 and are the context for the examples that follow: 

Statement 1:  

U1: GRANT SELECT ON TABLE T1 TO U2 WITH GRANT OPTION;

Statement 2:

U2: GRANT SELECT ON TABLE T1 TO U3 WITH GRANT OPTION;

Statement 3:

U3: GRANT SELECT ON TABLE T1 TO U4 WITH GRANT OPTION;

Example 1a: 

The RESTRICT option causes the following REVOKE statement to fail because in Statement 2, user U2 exercised the privilege he acquired in Statement 1.

U1: REVOKE SELECT ON TABLE T1 FROM U2 RESTRICT;

Example 1b: 

The following example succeeds and Statements 1, 2, and 3 are negated.

U1: REVOKE SELECT ON TABLE T1 FROM U2 CASCADE;

Example 1c: 

The RESTRICT option causes the following statement to fail because in Statement 2, user U2 exercised the GRANT OPTION privilege he acquired in Statement 1.

U1: REVOKE GRANT OPTION FOR SELECT ON TABLE T1 FROM U2 RESTRICT;

Example 1d: 

The following statement succeeds and negates Statements 2 and 3. U2 retains SELECT privilege on T1, but cannot grant this privilege to others.

U1: REVOKE GRANT OPTION FOR SELECT ON TABLE T1 FROM U2 CASCADE;

Example 2 

The following GRANT and CREATE statements are issued by users U1, U2, and U3 and are the context for the examples that follow. The name before the colon is the name of the user who issued the statement. 

Statement 1:  

U1: GRANT SELECT ON TABLE T1 TO U2 WITH GRANT OPTION;

Statement 2:

U2: GRANT SELECT ON TABLE T1 TO U3 WITH GRANT OPTION;

Statement 3:

U3: GRANT SELECT ON TABLE T1 TO U4 WITH GRANT OPTION;

Statement 4:

U2: CREATE VIEW V2 AS SELECT A, B FROM T1;

Statement 5:

U3: CREATE VIEW V3 AS SELECT A, B FROM T1;

Example 2a: 

The following statement succeeds and negates Statements 1, 2, and 3. In addition, views V2 and V3 are dropped because U2 and U3 no longer have the SELECT privileges on T1 that are required by the views.

U1: REVOKE SELECT ON TABLE T1 FROM U2 CASCADE

Example 2b: 

The following statement succeeds and negates Statements 2 and 3. User U2 retains the SELECT privilege on T1, but cannot grant this privilege to others. In addition, the view V3 is dropped because U3 no longer has the SELECT privilege on T1. View V2 is not dropped because U2 still holds SELECT privileges on T1.

U1: REVOKE GRANT OPTION FOR SELECT ON TABLE T1 FROM U2 CASCADE

Example 3 

The following GRANT and CREATE statements are issued by users U1, U2, and U3 and are the context for the examples that follow. The name before the colon is the name of the user who issued the statement. 

Statement 1:  

U1: CREATE ROLE R1; 

Statement 2:

U1: GRANT SELECT ON TABLE T1 TO R1;

Statement 3:

U1: GRANT R1 TO U2 WITH ADMIN OPTION;

Statement 4:

U2: GRANT R1 TO U3 WITH ADMIN OPTION;

Statement 5:

 U3: GRANT R1 TO U4 WITH ADMIN OPTION; 

Example 3a: 

The following statement fails because user U2 has exercised the privileges acquired as a result of being granted role R1.

 U1: REVOKE R1 FROM U2 RESTRICT;

Example 3b: 

The following statement succeeds. Statements 3, 4, and 5 above are negated.

 U1: REVOKE R1 FROM U2 CASCADE; 

Example 3c: 

The following statement fails because in Statement 3, user U2 exercised the ADMIN OPTION.

 U1: REVOKE ADMIN OPTION FOR R1 FROM U2 RESTRICT; 

Example 3d:  

The following statement succeeds. Statements 4 and 5 are negated. U2 retains the privileges granted by role R1, but cannot grant this role to others.

 U1: REVOKE ADMIN OPTION FOR R1 FROM U2 CASCADE; 

Blackfish SQL supports escape sequences for the following:

  • Date and time literals
  • OUTER JOIN
  • The escape character for a LIKE clause
  • Calling stored procedures

Escapes must always be enclosed in braces {}. They are used to extend the functionality of SQL.

Date and Time Literals

 

{T 'hh:mm:ss'} 
Specifies a time, which must be entered in the sequence: hours, followed by minutes, followed by seconds. 
{D 'yyyy-mm-dd} 
Specifies a date, which must be entered in the sequence; year, followed by month, followed by day.  
{TS 'yyyy-mm-dd hh:mm:ss'} 
Specifies a timestamp, which must be entered in the format indicated; year, month, day, hour, minute, second. 

Examples

INSERT INTO tablename VALUES({D '2004-2-3'}, {T '2:55:11'});
SELECT {T '10:24'} FROM tablename;
SELECT {D '2000-02-01'} FROM tablename;
SELECT {TS '2000-02-01 10:24:32'} FROM tablename;

 

Outer Joins

 

{OJ <join_table_expression>} 
An outer join is performed on the specified table expression. 
SELECT * FROM {OJ a LEFT JOIN b USING(id)};

 

Escape Character for LIKE

 

{ESCAPE <char>} 
The specified character becomes the escape character in the preceding LIKE clause. 
SELECT * FROM a WHERE name LIKE '%*%' {ESCAPE '*'}

 

Calling Stored Procedures

 

{call <procedure_name> (<argument_list>)}

Or, if the procedure returns a result parameter:

{? = call <procedure_name> (<argument_list>)}

Example 1 

The method implementing IncreaseSalaries updates the salaries table with an increase of some percentage for all employees. A connection object is passed implicitly to the method. An updateCount of all the rows affected by IncreaseSalaries is returned from Statement.executeUpdate.

{CALL IncreaseSalaries(10)};

Example 2  

The parameter marker indicates an output parameter position from which the result of the stored procedure can be retrieved.

{?=CALL ABS(-765)};

Functions are written in the following format, where FN indicates that the function following it should be performed:

{fn <function_name>(<argument_list>) }

 

Numeric functions

 

Function name 
Function returns 
ABS(number) 
Absolute value of number 
ACOS(float) 
Arccosine, in radians, of float 
ASIN(float) 
Arcsine, in radians, of float 
ATAN(float) 
Arctangent, in radians, of float 
ATAN2(float1, float2) 
Arctangent, in radians, of float2 divided by float1 
CEILING(number) 
Smallest integer >= number 
COS(float) 
Cosine of float radians 
COT(float) 
Cotangent of float radians 
DEGREES(number) 
Degrees in number radians 
EXP(float) 
Exponential function of float 
FLOOR(number) 
Largest integer <= number 
LOG(float) 
Base e logarithm of float 
LOG10(float) 
Base 10 logarithm of float 
MOD(integer1, integer2) 
Remainder for integer1 divided by integer2 
PI() 
The constant pi 
POWER(number, power) 
number raised to (integer) power 
RADIANS(number) 
Radians in number degrees 
RAND(integer) 
Random floating point for seed integer 
ROUND(number, places) 
number rounded to places places 
SIGN(number) 
&ndash;1 to indicate number is < 0; 0 to indicate number is = 0; 1 to indicate number is > 0 
SIN(float) 
Sine of float radians 
SQRT(float) 
Square root of float 
TAN(float) 
Tangent of float radians 
TRUNCATE(number, places) 
number truncated to places places 

 

String Functions

 

Function name 
Function returns 
ASCII(string) 
Integer representing the ASCII code value of the leftmost character in string 
CHAR(code) 
Character with ASCII code value code, where code is between 0 and 255 
CONCAT(string1, string2) 
Character string formed by appending string2 to string1; if a string is null, the result is DBMS-dependent 
DIFFERENCE(string1, string2) 
Integer indicating the difference between the values returned by the function SOUNDEX for string1 and string2 
INSERT(string1, start, length, string2) 
A character string formed by deleting length characters from string1 beginning at start, and inserting string2 into string1 at start 
LCASE(string) 
Converts all uppercase characters in string to lowercase 
LEFT(string, count) 
The count leftmost characters from string 
LENGTH(string) 
Number of characters in string, excluding trailing blanks 
LOCATE(string1, string2[, start]) 
Position in string2 of the first occurrence of string1, searching from the beginning of string2; if start is specified, the search begins from position start. Returns zero if string2 does not contain string1. Position 1 is the first character in string2. 
LTRIM(string) 
Characters of string with leading blank spaces removed 
REPEAT(string, count) 
A character string formed by repeating stringcount times 
REPLACE(string1, string2, string3) 
Replaces all occurrences of string2 in string1 with string3 
RIGHT(string, count) 
The count rightmost characters in string 
RTRIM(string) 
The characters of string with no trailing blanks 
SOUNDEX(string) 
A data source-dependent character string representing the sound of the words in string; this can be, for example, a four-digit SOUNDEX code or a phonetic representation of each word. 
SPACE(count) 
A character string consisting of count spaces 
SUBSTRING(string, start, length) 
A character string formed by extracting length characters from string beginning at start 
UCASE(string) 
Converts all lowercase characters in string to uppercase 

Examples

SELECT {FN LCASE('Hello')} FROM tablename;

SELECT {FN UCASE('Hello')} FROM tablename;

SELECT {FN LOCATE('xx', '1xx2')} FROM tablename;

SELECT {FN LTRIM('Hello')} FROM tablename;

SELECT {FN RTRIM('Hello')} FROM tablename;

SELECT {FN SUBSTRING('Hello', 3, 2)} FROM tablename;

SELECT {FN CONCAT('Hello ', 'there.')} FROM tablename;

 

Date and Time Functions

 

Function name 
Function returns 
CURDATE() 
The current date as a date value 
CURTIME() 
The current local time as a time value 
DAYNAME(date) 
A character string representing the day component of date; the name for the day is specific to the data source 
DAYOFMONTH(date) 
An integer from 1 to 31 representing the day of the month in date 
DAYOFWEEK(date) 
An integer from 1 to 7 representing the day of the week in date; Sunday = 1 
DAYOFYEAR(date) 
An integer from 1 to 366 representing the day of the year in date 
HOUR(time) 
An integer from 0 to 23 representing the hour component of time 
MINUTE(time) 
An integer from 0 to 59 representing the minute component of time 
MONTH(date) 
An integer from 1 to 12 representing the month component of date 
MONTHNAME(date) 
A character string representing the month component of date; the name for the month is specific to the data source 
NOW() 
A timestamp value representing the current date and time 
QUARTER(date) 
An integer from 1 to 4 representing the quarter in date; January 1 through March 31 = 1 
SECOND(time) 
An integer from 0 to 59 representing the second component of time 
TIMESTAMPADD(interval, count, timestamp) 
A timestamp calculated by adding count number of intervals to timestamp; interval can be any one of the following: SQL_TSI_FRAC_SECOND, SQL_TSI_SECOND, SQL_TSI_MINUTE, SQL_TSI_HOUR, SQL_TSI_DAY, SQL_TSI_WEEK, SQL_TSI_MONTH, SQL_TSI_QUARTER, or SQL_TSI_YEAR 
TIMESTAMPDIFF(interval, timestamp1, timestamp2) 
An integer representing the number of intervals by which timestamp2 is greater than timestamp1; interval can be any one of the following: SQL_TSI_FRAC_SECOND, SQL_TSI_SECOND, SQL_TSI_MINUTE, SQL_TSI_HOUR, SQL_TSI_DAY, SQL_TSI_WEEK, SQL_TSI_MONTH, SQL_TSI_QUARTER, or SQL_TSI_YEAR 
WEEK(date) 
An integer from 1 to 53 representing the week of the year in date 
YEAR(date) 
An integer representing the year component of date 

Examples

SELECT {FN NOW()} FROM tablename;

SELECT {FN CURDATE() } FROM tablename;

SELECT {FN CURTIME() } FROM tablename;

SELECT {FN DAYOFMONTH(datecol) } FROM tablename;

SELECT {FN YEAR(datecol)} FROM tablename;

SELECT {FN MONTH(datecol)} FROM tablename;

SELECT {FN HOUR(timecol) } FROM tablename;

SELECT {FN MINUTE(timecol) } FROM tablename;

SELECT {FN SECOND(timecol) } FROM tablename;

 

System Functions

 

Function name 
Function returns 
DATABASE() 
Name of the database 
IFNULL(expression, value) 
value if expression is null; expression if expression is not null 
USER() 
User name in the DBMS 

 

Conversion Functions

 

Function name 
Function returns 
CONVERT(value, SQLtype) 
value converted to SQLtype where SQLtype can be one of the following SQL types: BIGINT, BINARY, BIT, CHAR, DATE, DECIMAL, DOUBLE, FLOAT, INTEGER, LONGVARBINARY, LONGVARCHAR, REAL, SMALLINT, TIME, TIMESTAMP, TINYINT, VARBINARY, or VARCHAR 
SELECT {FN CONVERT('34.5',DECIMAL(4,2))} FROM tablename;

ISQL is a SQL command interpreter that can be used to execute SQL statements interactively. This feature is currently available for Blackfish SQL for Java only.

Getting Help

To see a help display for Blackfish SQL ISQL, issue one of the following help commands: From the system prompt:

  • isql -? displays ISQL startup options.
  • isql -help displays ISQL options.

From the SQL prompt:

  • HELP CREATE displays help on creating datasources.HELP SHOW displays a list of SHOW commands with briefdescriptions.
  • HELP SET displays a list of SET commands with brief descriptions of each.

 

Starting ISQL

To start Blackfish SQL ISQL, either ensure that <BlackfishSQL_install_dir>\bin is in your system path, or go to that directory to issue the ISQL command. These options are available: 

Startup Options for ISQL

Option and arguments 
Description 
-user userName 
Specifies the userName for this connection 
-password password 
Specifies the password associated with userName 
-role roleName 
Activates the named role for the user 
-input filename 
Executes all commands in the specified file and then quits 
-output filename 
Redirects all output to the named file 
-datasource filename 
Specifies an alternative datasource file 
-echo 
Prints all commands before executing them 
-stacktrace 
Prints a stacktrace for each error encountered 
-pagelength length 
Prints column headers every length number of rows 
-x 
Prints all the data definition statements from the current connection and exits 
-z 
Shows version information and exits 

 

Datasource and File Management

Once you have started ISQL, the following commands are available for managing datasource connections, file management and session management. You can see a list of these commands during an ISQL session by issuing the following:

SHOW CREATE;

There are two additional groups of commands that are discussed later in this section: SHOW commands and SET commands. The SQL commands that are available for data definition, data manipulation, security, and transaction management are discussed throughout this chapter.  

ISQL Datasource and File Management Commands

Command 
Description 
CREATE DATASOURCE dataSourceName [dataSourceClassName] properties 
Associates a datasource with the dataSourceName. You pass this dataSourceName to CONNECT in order to connect to a database. See "Creating datasources with ISQL" below, for information on creating datasources in ISQL.  
CONNECT dataSourceName [userpassword] 
Connects to the datasource specified by dataSourceName. Before you can use CONNECT, you must use CREATE DATASOURCE to associate a database with the dataSourceName that you pass to CONNECT. You do not need to specify user name or password if it was specified as part of the CREATE DATASOURCE statement.  
INPUT filename 
Takes the contents of the named SQL file as input. 
OUTPUT filename 
Writes the output to the specified file. 
OUTPUT 
Writes the output to stdout. 
EXPORT 
Exports the data definition statements and data of the current database to SQL. 
EXPORT [userpassword] 
Exports the data definition statements and data of the current database to the specified datasource. To export to a file, use EXPORT in conjunction with OUTPUT: OUTPUT sqlfile.txt; EXPORT;  
IMPORT [userpassword] 
Imports the data definition statements and data from the specified datasource. 
VERSION 
Shows the version of ISQL and the version of any connected database. 
EXIT 
Commits changes and exits. 
QUIT 
Rolls back changes and exits. 

 

Creating Datasources with ISQL

This section provides more detail about creating datasources in ISQL using the CREATE DATASOURCE command listed above. The CREATE DATASOURCE syntax is as follows:

CREATE DATASOURCE dataSourceName [dataSourceClassName] properties

The arguments for the CREATE DATASOURCE command are:  

dataSourceName identifies the new datasource; it can be any SQL identifier assigned by you. 

dataSourceClassName is the class that specifies the properties needed to connect to a JDBC database. It must be an implementation of the standard JDBC javax.sql.DataSource interface. If this argument is not provided, com.borland.javax.sql.JdbcDataSource is used. To access InterBase databases, you can use interbase.interclient.DataSource.  

properties can include any properties in the class supplied as the dataSourceClassName. Properties are separated by commas and commonly include the following: 

  • user='username' If you do not supply a user name here, you can supply it as part of the CONNECT statement.
  • password='password' If you do not supply a password here, you can supply it as part of the CONNECT statement.
  • databaseName='database_name_to_connect_to'

Example 

You can supply values for any properties in the datasource class. For example, to create a new database, add the following:

 CREATE=true: CREATE DATASOURCE

JDS user=SYSDBA, password=masterkey,

databaseName='c:/databases/test.jds',CREATE=true'; 

Examples 

These examples both use the Blackfish SQL default class com.borland.javax.sql.JdbcDataSource, since no className is specified. 

The example below creates a local datasource, JDS_LOCAL:

CREATE DATASOURCE JDS_LOCAL
  user=SYSDBA,
  password=masterkey,
  create=true,
  databaseName='c:/test.jds';

The next example creates a remote datasource, JDS_REMOTE. It also creates the test.jds database.

CREATE DATASOURCE JDS_REMOTE
  user=SYSDBA,
  password=masterkey,
  networkProtocol=tcp,
  serverName=localhost,
  portNumber=2508,
  create=true,
  databaseName='c:/test.jds';

 

ISQL SHOW Commands

 

Command 
Description 
SHOW DATASOURCE [name] 
Displays all datasources or the specified datasource. 
SHOW DATABASE 
Displays settings for the current database. 
SHOW VERSION 
Displays the ISQL version and the version of any connected database. 
SHOW DDL 
Displays the data definition statements for the current database. 
SHOW SYSTEM 
Displays the system tables. 
SHOW TABLE [[schema.]table] 
Displays all tables or the specified table. 
SHOW VIEW [[schema.]view] 
Displays all views or the specified view. 
SHOW PROCEDURE [[schema.]name] 
Displays all procedures or the specified pprocedures 
SHOW FUNCTION [[schema.]name] 
Displays all functions or the specified function. 
SHOW INDEX [index [ON [schema.]table]] 
Displays all indexes or the specified index. 
SHOW ROLES 
Lists all roles defined in the database. 
SHOW USERS 
Lists all users defined in the database. 
SHOW GRANT TABLE [[schema.]table] 
Lists all privileges on tables that have been granted WITH GRANT OPTION. 
SHOW GRANT VIEW [[schema.]view] 
Lists all privileges on views that have been granted WITH GRANT OPTION. 
SHOW GRANT PROCEDURE [[schema.]name] 
Lists all privileges on procedures that have been granted WITH GRANT OPTION. 
SHOW GRANT FUNCTION [[schema.]name] 
Lists all privileges on functions that have been granted WITH GRANT OPTION. 
SHOW GRANT ROLE [role] 
Lists all users who have been granted the specified role. 
SHOW GRANT DATABASE [user|role] 
Lists all database privileges that have been granted to the specified user or role. 

 

ISQL SET Commands

 

Command 
Description 
SET 
Displays the current value of ECHO, STACKTRACE, and PAGELENGTH. 
SET ECHO {ON|OFF} 
Toggles echoing of all commands to standard out. 
SET STACKTRACE {ON|OFF} 
Toggles display of error traces. 
SET PAGELENGTH number 
Sets the page length in lines; default is 0, meaning that the column headings print out only once. 
Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!