sql reference - spartan controls/media/resources/... · iii preface this document describes the sql...
TRANSCRIPT
SQL Reference
Polyhedra Ltd
i
Copyright notice
This document is copyright © 1994 - 2006 by Polyhedra Ltd. All Rights Reserved. This documentcontains information proprietary to Polyhedra Ltd. It is supplied in confidence and must not be used forany purpose other than that for which it was supplied. This document may not, in whole or in part, becopied, photocopied, reproduced, translated or reduced to any electronic medium or machine readableform without prior written consent from Polyhedra Ltd.
Trademarks
Polyhedra is a registered trademark of Polyhedra Ltd.
Certain terms used in this document are trademarks; while these are not acknowledged as such in thetext, this should in no way be construed as a challenge to that trademark status, or as an infringement ofthat status.
Manual DetailsManual title SQL Reference
Document number manuals/sql
Revision number 6.3.3
Revision Date 12th June 2006
Software Version
This documentation corresponds to the following version of the software:
Version 6.3
iii
PREFACE
This document describes the SQL language supported by Polyhedra.
This document is a reference manual and it is recommended that the reader should also see PolyhedraOverview, Polyhedra User's Guide and the appropriate data server document (Real-time RelationalDatabase or Database Interface) prior to reading the SQL Reference.
The document is aimed at the application writer and it is assumed that the reader is familiar withdatabase query languages, relational databases and object-oriented concepts. The organisation of thedocument is as follows:
Section 1 Overview
Section 2 Terminology
Section 3 Lexical conventions
Section 4 Features of SQL
Section 5 SQL command reference
Document conventions
The following notation is used in this guide:
[ x ] Optional item
{ x y } Enter one of the items separated by
{ x... } Enter one or more of...
boldlowercase Keywordslowercase VariablesMixedCase Tables( ) , . Syntax punctuation. Enter exactly as shown.
v
CONTENTS
1. OVERVIEW OF SQL .................................................................................................................1
2. DATABASE TERMS ..................................................................................................................3
3. LEXICAL CONVENTIONS.......................................................................................................53.1 SQL lexical conventions.....................................................................................................53.2 Naming rules ......................................................................................................................53.3 Reserved words ..................................................................................................................6
4. SQL FEATURES .........................................................................................................................74.1 Conformity with ANSI SQL...............................................................................................74.2 Enhancements.....................................................................................................................7
4.2.1 Object-oriented model ............................................................................................74.2.2 Inheritance..............................................................................................................74.2.3 Saving the database................................................................................................84.2.4 Index usage.............................................................................................................84.2.5 Shared columns ......................................................................................................84.2.6 Virtual columns ......................................................................................................9
4.3 User-defined types: Domains............................................................................................10
5. COMMAND REFERENCE......................................................................................................11alter domain .................................................................................................................................13alter schema .................................................................................................................................15alter table .....................................................................................................................................16add-clause ....................................................................................................................................18alter-clause...................................................................................................................................19drop-clause...................................................................................................................................20modify-clause...............................................................................................................................21rename-clause ..............................................................................................................................22column-redefn..............................................................................................................................23call ...............................................................................................................................................24create domain...............................................................................................................................26create index..................................................................................................................................28create schema...............................................................................................................................30create table...................................................................................................................................32column-definition.........................................................................................................................35column-constraint ........................................................................................................................36table-constraint-definition............................................................................................................38create view...................................................................................................................................40delete............................................................................................................................................43drop domain.................................................................................................................................44drop index....................................................................................................................................45drop table .....................................................................................................................................46drop view.....................................................................................................................................47grant .............................................................................................................................................48privilege .......................................................................................................................................50insert ............................................................................................................................................51revoke ..........................................................................................................................................53save ..............................................................................................................................................54select ............................................................................................................................................56send..............................................................................................................................................60shutdown......................................................................................................................................61update ..........................................................................................................................................62
vi
Data types ....................................................................................................................................64Expressions..................................................................................................................................66
APPENDIX A: BUILT-IN FUNCTIONS ...........................................................................................71
APPENDIX B: CONFORMITY WITH ANSI SQL ..........................................................................89
SQL Reference Overview of SQL
1
1. Overview of SQL
This document describes the SQL syntax supported by the RTRDB component of Polyhedra and allPolyhedra data servers.
SQL provides an industry-standard means of accessing a database. SQL supports the definition of datastructures, data modification and access to data in a database.
This implementation of SQL is based on the ANSI standard as specified in ISO 9075. In addition,important extensions to SQL have been developed. These include:
• object-oriented extensions
• data integrity enforcement
• real-time support
• data persistency
This document assumes that the reader has knowledge of relational databases and object-orienteddesign. Familiarity with Polyhedra servers is also assumed.
SQL Reference Database terms
3
2. Database terms
This section provides an introduction to the terms describing the structure of relational data. Theseterms will be used throughout the remainder of this document.
Schema A schema is a set of database object definitions, typically consisting of tables,domains and indexes.
Table A table is a data structure that holds rows of data (objects) in the database.Each data row in the same table has the same data structure. This structure isdefined by the sequence of columns in the table.
Column A table column enforces type and other constraints on each field in the column.
Row A row is a set of data in a table. It consists of a sequence of fields whosestructure conforms to the data structure of the table.
Field A field is where a column and a row intersect. It holds the row's value for aparticular column.
Null value A null value is a value used where no data value would be applicable or data ismissing.
Literal A constant value.
Index Indexes are used mainly to provide quick access to rows in a table. They mayalso be used to enforce the uniqueness of rows within a table.
Primary keys The primary key of a table is the minimum set of columns whose valuesidentify individual rows in the table uniquely. Once set, the primary key valuemay not be changed, nor may it contain null values.
Foreign keys A foreign key links a row in one table with a row in another table byreferencing its primary key. A foreign key consists of a set of columns thatmatch the target primary key. The only values a foreign key can take areexisting values of the target primary key or null.
Domain Domains are user-defined types. A domain is defined by a set of columns inmuch the same way as a table. Domain instances represent composite valuesthat are only accessible through columns of that type and exist only whilereferences remain.
Domains may not be treated as a whole; the individual components must beexplicitly referenced.
View A view is a 'virtual' table whose data is obtained directly or indirectly from oneor more tables by the evaluation of a query expression. It appears to the user asif it were a table but its contents depend on the data in the underlying tableswhen the query expression is evaluated.
Database terms SQL Reference
4
The diagram below illustrates the relationship between tables, rows, columns and fields.
i j k l m n oTable
Column
RowField
Figure 1. Relationship between tables, rows, columns and fields
SQL Reference Lexical conventions
5
3. Lexical conventions
3.1 SQL lexical conventions
SQL statements may include one or more tabs, carriage returns, spaces or comments at any point wherea space occurs within the statement. For example the following statements are identical:
select name, salary from Employees order by salary asc;
select name, salary
from Employees
order by salary asc;
Case is only significant in character string literals; it is ignored in reserved words and identifiers.
Inside a character string literal the escape sequence \uxxxx is interpreted as a single Unicode characterwhere the 4-digit hexadecimal value (xxxx) is interpreted as the Unicode code point value.
Two types of comment are recognised:
• from a sequence of two consecutive hyphens (-) up to the next newline
• from a /* sequence up to the next */ sequence
For example:-- This is a comment
/* This is
a comment */
3.2 Naming rules
The names of identifiers must comply with the following rules.
An identifier:
• must begin with a letter (a-z, A-Z).
• may only contain characters a-z, A-Z, 0-9 or _ (underscore).
• must not end with _ (underscore).
• is not case sensitive.
• may be of any length.
Examples:EMPLOYEE_NAME employee_0 BookTitle
Lexical conventions SQL Reference
6
3.3 Reserved words
The reserved words consist of all the reserved words in the ISO standard plus the extensionsimplemented by Polyhedra:
ADD ALL ALTER AND ANY
ARRAY AS ASC AUTHORIZATION AVG
BEGIN BETWEEN BINARY BOOL BUT
BY CALL CASCADE CHANGE CHAR
CHARACTER CHECK CL CLOSE COBOL
COMMIT COMPUTED COMPUTING CONTINUE COUNT
CREATE CURRENT CURSOR DATETIME DEC
DECIMAL DECLARE DEFAULT DELETE DERIVED
DESC DISTINCT DOMAIN DOUBLE DROP
END ESCAPE EVERY EXEC EXECUTE
EXISTS FALSE FETCH FLOAT FOR
FOREIGN FORTRAN FOUND FROM GO
GOTO GRANT GROUP HAVING HIDDEN
IN INDEX INDICATOR INSERT INT
INTEGER INTO IS KEY LANGUAGE
LIKE LOAD LOCAL LOGGED LOGGING
MAX MIN MODIFY MODULE NOT
NULL NUMERIC OF OLD ON
OPEN OPTION OR ORDER ORDERED
PASCAL PERSISTENT PLI PRECISION PRIMARY
PRIVILEGES PROCEDURE PUBLIC PURGING REAL
REFERENCES RENAME RESTRICT REVOKE ROLLBACK
SAVE SCHEMA SECTION SELECT SEND
SET SHARED SHUTDOWN SMALLINT SOME
SQL SQLCODE SQLERROR SUM TABLE
TO TRANSIENT TRUE UNION UNIQUE
UNKNOWN UPDATE USER VALUES VARCHAR
VARYING VIEW VIRTUAL WHENEVER WHERE
WITH WORK
SQL Reference SQL features
7
4. SQL features
4.1 Conformity with ANSI SQL
The SQL supported by the RTRDB is a dialect based on the ANSI SQL. It provides standardcommands for data definition and data manipulation and enforces data integrity. Extensions have beenmade to the language to include object-oriented and real-time data handling facilities. The client-serverdesign of Polyhedra components has rendered part of the ANSI SQL syntax inappropriate and therehave been some omissions (see Appendix B for further details).
4.2 Enhancements
A brief summary of the enhancements is given below.
4.2.1 Object-oriented model
Extensions have been made to encourage the use of object-oriented design features such as inheritance.Object-oriented features are made available to the RTRDB by making the following mapping betweenrelational and object-oriented models:
• A table defines a class.
• A column defines an attribute of that class.
• A row is an instance (or object) of that class.
4.2.2 Inheritance
One way to save space and improve access to data is to utilise existing tables when designing new onesand to build on them. Related tables may have columns in common which can be abstracted anddefined in a base table from which others can be derived. A derived table inherits the characteristicsand columns of its base table and may add to them. The primary key is inherited and may not beredefined. All records in derived tables also appear in the parent table.
An example of inheritance is shown below.
A table called Books is created to hold information on the title, author, publisher and location of eachbook in a library. Each book is assigned a unique book number that serves as the primary key for thetable:Books
bookno title author publisher
(primary key)
There may be some books in the library that require additional information to be stored about themwhile still being required to appear in the above table of all books. For example, with fiction books,one might want to store the fiction category that each book belongs to so that they might be sortedaccording to this category.
Without inheritance there are two options. The first is to create another table of fiction bookscontaining the extra column and references back to Books. The problem with this is that adding abook to Fiction does not add it to Books. The second is simply to add the extra column to the tableBooks. This involves wasting space by adding a column that is not used by every row of the table andmeans that all of table Books have to be searched for fiction books.
Inheritance provides the best solution by enabling the 'sharing' of common structure. We create the
SQL features SQL Reference
8
table Fiction to inherit from Books.
Fiction
Books storytype
(inherited) (additional)
Books is the generic base table. Fiction is derived from Books. The information held in Bookswhich is common to Fiction is shared by Fiction. There is only one copy of this information.As new books are added to Fiction they will also be seen to appear in Books.
The diagram below illustrates, in an abstract way, how these tables are represented in memory wheninheritance is used.
Table
BOOKS
Table
FICTION
The diagrams below illustrate how the tables would be stored without inheritance:
TableBOOKS
TableFICTION
wastedspace
TableBOOKS
TableFICTION
foreign keyaccess required
Inheritance removes the need for duplicate definitions and once generic tables have been defined, newtables can be rapidly created without disturbing the generic tables.
4.2.3 Saving the database
The database may be saved to disk. The structure of the database is always saved. Table data is also besaved by marking columns as persistent. Only data marked persistent is saved. Howeverdata for transient columns in persistent tables may be present in the saved file – but is ignored whenreloading. To prevent sensitive data being present on disk, place the data in completely transient tables.
4.2.4 Index usage
Indexes may be created and deleted. Index usage improves the access speed. They can also be used toenforce unique values for a set of columns over the rows in a table.
4.2.5 Shared columns
A shared column contains a single value that is shared between all the rows of the table it appears in.This value is retained by the column even if there are no rows in the table. Shared columns have global
SQL Reference SQL features
9
scope; their values may be used in any expression.
4.2.6 Virtual columns
Virtual columns are like shared columns except that each deriving class has its own shared value for thecolumn. They provide a way of differentiating between rows from derived classes when accessing therows from the base class.
For example, consider the inheritance hierarchy below. If class X has a virtual column, the column cantake a different value in each of the classes X, Y, YY and Z. Thus, querying the column value fromeach of the classes could give the results below:
X
Y YY
Z
Class hierarchy
(Parent/base class)
PK Virtual column1 'I am a X'2 'I am a Y'3 'I am a YY'4 'I am a Z'
Table X:
Virtual columns provide a wayof differentiating between derivedclasses from the base classes.
PK Virtual column2 'I am a Y'4 'I am a Z'
Table Y:
PK Virtual column3 'I am a YY'
Table YY:
PK Virtual column4 'I am a Z'
Table Z:
SQL features SQL Reference
10
4.3 User-defined types: Domains
Users can define their own data types called domains which are treated in the same manner as built-intypes. User-defined types are classes just like tables. A domain shares the same name space as tablesand hence table and domain names must not be the same. The diagram below illustrates this where thecolumn age group is a user-defined type:
bookno
lowerage upperage
title author publisher story agegrouptype
Fiction table
Domain
SQL Reference Command reference
11
5. Command reference
This section contains detailed descriptions of all the SQL statements. The statements appear inalphabetical order and each description contains:
• a brief summary
• the syntax
• an explanation of the syntax
• rules that apply to the statement
• examples
SQL statements may be classified into three types:
DDL Data Definition Language: these statements affect the structure of the database.
DML Data Manipulation Language: these statements manipulate the data in the database.
Query These statements view data in the database without altering it.
Summary of SQL statements
Statement Type Descriptionalter domain DDL Changes the domain definition
alter schema DDL Groups together alterations
alter table DDL Changes the table definition
call DML orquery
Executes a stored procedure
create domain DDL Creates a domain
create index DDL Creates an new index for a table
create schema DDL Groups together definitions
create table DDL Creates a new table
create view DDL Creates a new view
delete from DML Deletes rows from a table
drop domain DDL Removes a domain from the database
drop index DDL Removes an index from a table
drop table DDL Removes a table from the database
drop view DDL Removes a view from the database
grant DDL Grants privileges to a user
insert into DML Inserts rows into a table
revoke DDL Revokes privileges from a user
save DDL Saves the database to a file
select Query Selects data from the database
Command reference SQL Reference
12
send DML Sends an arbitrary event to a table
shutdown DDL Shuts down the database
update DML Updates data in a table
Examples
Throughout the reference, the examples will be based on a library of books:Books
bookno title author publisher
AgeSet a domain
lowerage upperage
Fiction derived from Books
storytype agegroup
Reference derived from Books
version
Onloan
bookno custno returndate
Customers
custno name address allowance
A book has a title, author and publisher. It is classified as being either a fiction or a reference. Thestory type is kept with each fiction book. The version number is kept with each reference. Associatedwith each fiction book there is an age group that indicates the age of the reader.
A member of the library has a name, address and an allowance. The library gives each book a uniquenumber and each member a unique membership number.
The library keeps track of which member has which book and on which date the book should bereturned.
SQL Reference Command reference
13
alter domain
This command is used to alter the definition of a domain.
alter domain domain-name{ { persistent | transient | local }| add { add-clause | ( add-clause [{, add-clause...}] ) }| alter { alter-clause
| ( alter-clause [{, alter-clause...}] ) }| drop { drop-clause | ( drop-clause [{, drop-clause...}] ) }| modify { modify-clause
| ( modify-clause [{, modify-clause...}] ) }| rename to new-domain-name| rename { rename-clause
| ( rename-clause [{, rename-clause...}] ) }
Explanation
alter domain Required keywords.domain-name The name of the domain.add-clause Columns and table constraints to add. See page 18alter-clause Columns to alter default values of. See page 19drop-clause Columns and table constraints to drop. See page 20modify-clause Modifications of existing columns. See page 21new-domain-name A new name for the domain.rename-clause Columns to rename. See page 22
Rules
• domain-name must be an existing domain.
• Specifying persistent or transient affects the default persistency of the domain columns.If a new column is added to the domain, and no persistency is specified, the column takes thedefault persistency of the domain. Where the persistency is specified, this only affects the newcolumn and does not affect any already existing columns in the domain.
• Column types may not be changed.
• It is an error to make a column not null when it contains null values.
• A column may be made hidden or not hidden.
• Specifying local affects the default local constraint of the domains columns.
• new-domain-name must not be the same as an existing domain, table or view.
Command reference SQL Reference
14
Examples
To make an existing column not null and persistent:
alter domain AgeSet
modify (lowerage persistent not null);
SQL Reference Command reference
15
alter schema
This command allows one to create or alter a set of tables and/or domains. Definitions declared withina schema are treated as a single transaction and foreign key references may refer to tables defined laterin the schema (note, however, that table derivation cannot be forward references).
alter schema{ table-defn domain-defn alter-table-defn
| alter-domain-defn drop-table-defn| drop-domain-defn }
[ { ,{ table-defn domain-defn alter-table-defn| alter-domain-defn drop-table-defn| drop-domain-defn } }…]
Explanation
alter schema Required keywords.table-defn A create table command. See page 32
domain-defn A create domain command. Page 26
alter-table-defn An alter table command. See page 16
alter-domain-defn An alter domain command. See page 18
drop-table-defn A drop table command. See page 46
drop-domain-defn A drop domain command. See page 44
Rules
• Definitions are treated as a single transaction and they are treated as a whole rather than as anordered sequence of commands.
• Definitions may be mutually dependent, for example, two tables may reference each other.
• Definitions may contain forward references to tables or domains defined later in the schema. Forexample, a table may contain a foreign key reference to a later table.
Examples
To drop two tables Table1 and Table2 that reference each other and so cannot be droppedseparately.
alter schema
drop table Table1
drop table Table2
;
Command reference SQL Reference
16
alter table
This command is used to alter the definition of a table.
alter table table-name{ { persistent | transient | local }| add { add-clause | ( add-clause [{, add-clause...}] ) }| alter { alter-clause
| ( alter-clause [{, alter-clause...}] ) }| drop { drop-clause | ( drop-clause [{, drop-clause...}] ) }| modify { modify-clause
| ( modify-clause [{, modify-clause...}] ) }| rename to new-table-name| rename { rename-clause
| ( rename-clause [{, rename-clause...}] ) }
Explanation
alter table Required keywords.table-name The name of the table.add-clause Columns and table constraints to add. See page 18alter-clause Columns to alter default value of. See page 19drop-clause Columns and table constraints to drop. See page 20modify-clause Modifications to existing columns. See page 21new-table-name A new name for the table.rename-clause Columns to rename. See page 22
Rules
• table-name must be an existing table.
• Specifying persistent or transient affects the default persistency of the table columns.
• Column types may not be changed.
• It is an error to make a column not null when it contains null values.
• A column may be made hidden or not hidden.
• Specifying local affects the default local constraint of the table columns.
• new-domain-name must not be the same as an existing domain, table or view.
• The statement is rejected if it invalidates any view referencing the table.
SQL Reference Command reference
17
Examples
To alter the Books table definition by adding not null column constraint to author:
alter table Books
modify ( author not null );
To add two new columns to the Books table to hold the purchase price of the book and whether thebook is a paperback:
alter table Books
add ( price integer, ispaperback bool );
To alter the price column to have a default value of 0:
alter table Books
alter price set default 0;
To alter the price column to remove the default value:
alter table Books
alter price drop default;
To drop the price and ispaperback columns:
alter table Books
drop ( price, ispaperback );
To rename the author column to writer:
alter table Books
rename author to writer;
To rename the Books table to LibraryBooks:
alter table Books
rename to LibraryBooks;
Command reference SQL Reference
18
add-clause
This defines an add clause for alter table or alter domain.
{ column-defn table-constr-defn }
Explanation
column-defn Column definition. See page 35.table-constr-defn Table constraint. See page 38.
Rules
• The column name appearing in the column definition of an add clause must not exist in the table orin any table derived from the table.
• It is an error to use a primary key constraint in an add clause.
• It is an error to use a derived from constraint in an add clause
• A foreign key constraint must only constrain columns added in the same alter table statement.
• A not null constraint can only appear in an add clause if the table contains no records or thecolumn definition also contains a not null default value for the column.
• A unique constraint can only appear in an add clause if the table contains no records or the tableconstains 1 record and also contains a not null default value for the column.
Examples
See also alter table
To add a borrowed date to the the Onloan table definition
alter table Onloan
add ( borroweddate datetime );
SQL Reference Command reference
19
alter-clause
This defines an alter clause for alter table or alter domain.
{ column-name set default-value| column-name drop default}
Explanation
column-name The name of the column.
set default-value Sets the default value for the column.
drop default Removes the default value for the column.
Rules
• The column name must already exist in the table or domain.
• The type of default-value must match the type of the column.
Examples
See also alter table
To add a default allowance to the Customers table definition
alter table Customers
alter ( allowance default 5 );
Command reference SQL Reference
20
drop-clause
This defines a drop clause for alter table or alter domain.
{ column-name table-constr-defn }
Explanation
column-name The name of the column.table-constr-defn Table constraint. See page 38.
Rules
• The column name must already exist in the table or domain.
• It is an error to try to drop the derived from table constraint.
• It is an error to try to drop a primary key table constraint.
• It is an error to try to drop a foreign key table constraint.
• It is an error to try to drop a primary key column.
• It is an error to try to drop an indexed column.
• All columns of a foreign key must be dropped in the same alter table or alter domain.
• All columns of a unique constraint must be dropped in the same alter table or alter domain.
Examples
See alter table
SQL Reference Command reference
21
modify-clause
This defines a modify clause for alter table or alter domain.
column-redefn
Explanation
column-redefn Column redefinition. See page 23.
Rules
• The column name in the column redefinition must already exist.
• It is an error for primary key, references, shared, or virtual to appear in the column redefinition.
• Columns not altered in the modify clause remain the same.
Examples
See alter table
Command reference SQL Reference
22
rename-clause
This defines a rename item for alter table or alter domain.
column-name to new-column-name
Explanation
column-name The current name of the column.new-column-name The new name for the column.
Rules
• column-name must exist in the table or domain.
• new-column-name must not be the same as an existing column in the table or domain.
Examples
See alter table
SQL Reference Command reference
23
column-redefn
This redefines a column for a table.
column-name [default default-value][ column-constr ] [ { , column-constr}...]
Explanation
column-name The name of the column.
default default-value Default value used when records are inserted into the tablewithout specifying a value for this column. default-value isa literal value.
column-constr Column constraint. See page 36.
Rules
• The values that a column may contain are dependent on the type of the column and on anyconstraint placed on the column itself.
• The type of default-value must match the type of the column.
• A column may have any number of constraints. See page 36.
• An array is a variable length list of references to domain or table records. It is not accessible fromSQL, but it is used by Control Language methods.
• It is an error to have the following column constraints in a column redefinition: virtual, shared,primary or references.
Examples
See alter table
Command reference SQL Reference
24
call
This command executes a stored procedure.
call procedure-name[ (((( [ parameter-name = ] parameter-value[{ , [ parameter-name = ] parameter-value...}] )))) ]
Explanation
call Required keyword.procedure-name The name of the procedure.parameter-name Optional name of parameter.parameter-value Value of parameter.
Rules
• procedure-name must be stored procedure defined by a record in the sqlprocedure table.
• parameter-value must be either a parameter marker (?), a named parameter or a constantexpression.
• The number of parameters must match the number of parameters used by the stored procedure.
• When executed the number of runtime parameter values must match the number of parameters(parameter markers and named parameters) in the call statement.
• When executed the mapping of runtime parameter values to parameters (parameter markers andnamed parameters) in the call statement (not in the procedure) is performed identically to anyother statement.
• If parameter-name is supplied with a call statement parameter, this will be used whenexecuting the procedure. If parameter-name is not supplied, then any name supplied with theruntime parameter value will be used.
• It is possible to include a call statement in a statement sequence.
• It is possible to include a call statement in the text of a stored procedure.
• It is not be possible to create a stored procedure that contains a reference, either directly orindirectly via a call statement, to itself.
• It is possible to delete a procedure that is being referenced by a prepared call statement.However, the prepared statement is invalidated.
SQL Reference Command reference
25
Examples
Define and invoke a procedure to return a book. First using a named parameter:
insert into sqlprocedure ( name, text )values ( 'return_book',
'delete from onloan where bookno=:<integer>bookno' );
commit;
call return_book ( bookno = 29282 );
Next using an unnamed parameter:
insert into sqlprocedure ( name, text )values ( 'return_book',
'delete from onloan where bookno=?' );
commit;
call return_book ( 29282 );
Command reference SQL Reference
26
create domain
This command creates a new domain. A domain is a user-defined data type which is treated much like abuilt-in type. Domains are not 'first class' types and may not be used directly (for comparison andinitialisation). A domain is defined in much the same way as a table and may inherit from otherdomains and have constraints on its columns.
A domain is defined by one or more columns that represent the attributes of components of a new type.A domain is much like a table except that its rows are not accessed directly from the domain itself, butfrom columns that have the domain as their type. A domain does not have a primary key. Domainsmay contain columns of other domain types and domains may inherit from other domains.
create domain domain-name{ column-defn table-constr-defn }[ { ,{ column-defn table-constr-defn } } ...]
Explanation
create domain Required keywords.domain-name The name of new domain type.column-defn Column definitions. See page 35.table-constr-defn Table constraints. See page 38.
Rules
• A domain may not have the same name as any other domain, table, view or built-in type.
• A domain must have at least one column. This rule does not apply to domains that have beenderived from other domains, as they already have columns (the derived columns).
• No column of a domain can have the same name as another column in the domain. This includesinherited columns.
• A domain may not have a primary key defined on any of its columns.
• A domain may inherit from any other domain already defined.
• A domain (or its columns) may be marked as persistent or transient, but persistence rules only takeeffect if a domain object is contained in an object that is persistent.
• Domains may not be inserted into or deleted from directly, but may be selected from or updated asa table.
SQL Reference Command reference
27
Examples
To create a domain containing two integer types:
create domain AgeSet
(
lowerage integer,
upperage integer
);
To create a data type containing a list of information about the popularity of books, a domain is createdto contain readership information about a single book BookDetails. The second domainCategoryDetails strings together all the books of a particular type:
create domain BookDetails
(
booknumber integer not null,
noOfReaders integer,
ageOfBook integer,
);
create domain CategoryDetails
(
bookType integer not null,
allBooks array of BookDetails
);
Command reference SQL Reference
28
create index
This command creates a new index on a table. The index is defined on one or more of the columns andit provides direct access to rows in a table, thereby increasing the access speed. An index onlymaintains non-null values and detects clashes
create [unique] [ordered] index index-nameon table-name ( column-name [ { , column-name ...} ] )
Explanation
create index Required keywords. unique optional keyword which specifies thateach value in the indexed column should be unique. orderedoptional keyword specifies that the index will be optimised for theretrieval of ordered data
index-name The name of the new index. The name may be optionally of the form:local.<identifier>
If it is of this form then the index is local (see additional rules below)and the name of the index includes the local. prefix.
table-name The name of the table on which the index is created.column-name The name of the column within table-name on which the index is
created.
Rules
• An index may not have the same name as any other index.
• An index may not be created on a non-existing table.
• An index may be defined on more than one column.
• An index may not be defined over part of a foreign key unless it contains the entire key.
• An index may not be defined on columns of domain or array type.
• An index may not be defined on a shared or virtual column.
Additionally, the following rules apply to an ordered index:
• An ordered index may not be defined on columns that are part of a foreign key.
• The table specified by <table-name> must be either a table created using the CREATE TABLEstatement or a system catalogue table.
Additionally, the following rules apply to a local index:
• A local index will only appear in the catalogue tables on the local database in which it was created.
• A local index does not persist over restart.
• A local index is not journalled to a standby or replica database.
SQL Reference Command reference
29
• A unique local index can only be created on columns that are local.
UsageThe following rules describe when an ordered index will be used in the processing of a query.
1. An ordered index will be used to process an ORDER BY clause of a SELECT statementwhen the columns specified in the clause, and the order in which they are specified, exactlymatch the columns and order in which they are defined in the CREATE ORDERED INDEXstatement for the index. In addition, all the columns in the ORDER BY clause must beordered in the same direction, either all ASCENDING or all DESCENDING.Currently for the index to be used there is a further requirement that the columns in theORDER BY clause have restrictions in the WHERE clause.
2. If a unique hash index cannot be used, then an ordered index will be used to process aSELECT statement if the WHERE clause contains restrictions of the form,
<column> <comparison operator> <constant>
for the first M columns specified in the CREATE ORDERED INDEX statement (where Mless than or equal to the number of columns in the index) and the comparison operator is theequality operator (=) for all but the restriction on the least significant column. The comparisonoperator for the restriction on the least significant column (column M) can be any comparisonoperator (<, <=, =, =>, >).The restrictions must be separated by the AND operator in the WHERE clause.The restrictions may appear in any order in the WHERE clause.Additional restrictions may exist in the WHERE clause.
Examples
To create a unique index ind_booktitle on column title of table Books (fields in columntitle may not have the same values):
create unique index ind_booktitle on Books (title);
To create a non-unique index ind_bookauthor on column author of table Books.
create index ind_bookauthor on Books (author);
To create a unique ordered index ind_bookpublisher on column publisher of table Books.
create unique ordered index ind_bookpublisher
on Books (publisher);
Command reference SQL Reference
30
create schema
This command defines a set of tables, domains, views and indexes to be created. Definitions declaredwithin a schema are treated as a single transaction and foreign key references may refer to tablesdefined later in the schema (note, however, that table derivation cannot be forward references). Singletables, domains and indexes may be created using the appropriate command directly.
create schema{ table-defn domain-defn view-defn index-defn }[ { ,{ table-defn domain-defn view-defn index-defn } }…]
Explanation
create schema Required keywords.table-defn The definition of a new table. See page 32domain-defn The definition of a new domain. See page 26view-defn The definition of a new view. See page 40index-defn The definition of a new index. See page 28
Rules
• Definitions are treated as a single transaction and they are treated as a whole rather than as anordered sequence of commands.
• Definitions may be mutually dependent, for example, two tables may reference each other.
• Definitions may contain forward references to tables or domains defined later in the schema. Forexample, a table may contain a foreign key reference to a later table.
SQL Reference Command reference
31
Examples
To create a schema of tables and indexes:
create schema
create table Books
(
bookno integer not null primary key,
title char not null,
author char,
publisher char
)
create table Fiction
(
derived from Books, --inheritance
storytype char,
agegroup AgeSet
)
create table Reference
(
derived from Books, --inheritance
version integer
)
;
Command reference SQL Reference
32
create table
This command creates a new table. A table is defined by a set of columns, one or more of which mustmake up the primary key. All rows inserted into this table must conform to the table definition.
create table table-name( { column-defn table-constr-defn }[ { ,{ column-defn table-constr-defn } } ...] )
Explanation
create table Required keywords.table-name The name of the new table. The table must not have the same name
as any other table, domain or built-in type.column-defn The column definition. See page 35table-constr-defn The table constraint. See page 38
Rules
• A table must not have the same name as any other table, domain, view or built-in type.
• A table must have a primary key defined on one or more of its columns.
• A table may inherit directly from one other existing table.
• A table may not inherit from a system table.
• The primary key may not include columns of array or domain type or columns that form only partof a foreign key or columns that are hidden. The same applies to any unique constraints specified.
• A table may reference another existing table providing it is not a system table.
• Columns making up a foreign key must have the same null and persistence constraints.
• A primary key column cannot have a local constraint. A table constraint must be used instead.
When a table is created, associated indexes are created for any primary and foreign keys specified.These indexes prefixed by PK- and FK- may not be deleted.
SQL Reference Command reference
33
Examples
To create a table Books for holding records containing the book number, title, author and publisher ofeach book, each book is uniquely identified by its bookno which serves as the primary key:
create table Books
(
bookno integer not null primary key,
title char(30) not null,
author char(30),
publisher char(30)
);
To create a table Fiction which inherits the columns (and primary key) from Books and has anadditional column storytype:
create table Fiction
(
derived from Books, --inheritance
storytype char,
agegroup AgeSet --domain type column
);
To create a table Customers:
create table Customers
(
custno integer not null primary key,
name char,
address char,
allowance integer
);
To create a table Onloan with the columns bookno, custno and returndate. bookno andcustno are foreign keys that form a composite primary key for this table:
create table Onloan
(
bookno integer not null references
Books(bookno), -- foreign key to Books
custno integer not null references
customers(custno), -- foreign key to Customers
returndate datetime,
primary key (bookno, custno) -- composite
-- primary key
);
Command reference SQL Reference
34
To create a list of tables containing information about the shelves in an aisle of the library, a table iscreated to contain information about a single shelf Shelf. The second table ShelvesInAislestrings together all the shelves in a given aisle:
create table Shelf
(
location char not null,
level integer not null,
capacity integer,
firstBookNo integer,
primary key (location, level)
);
create table ShelvesInAisle
(
aisle integer not null primary key,
allShelves array of shelf
);
SQL Reference Command reference
35
column-definition
This defines a column for a table.
column-name data-type [default default-value][ column-constr ] [ { , column-constr}...]
Explanation
column-name The name of the column. A column may not have the same nameas any other column either in the table in which it is defined or ina derived table.
datatype The type of the column; must be a built-in type, a domain or anarray of references. See page 64.
default default-value Default value used when records are inserted into the tablewithout specifying a value for this column. default-value isa literal value.
column-constr Column constraint. See page 36.
Rules
• The values that a column may contain are dependent on the type of the column and on anyconstraints placed on the column itself.
• The type of default-value must match the type of the column.
• A column may have any number of constraints. See page 36.
• An array is a variable length list of references to domain or table records. It is not accessible fromSQL, but it is used by Control Language methods.
Examples
See create table
Command reference SQL Reference
36
column-constraint
This imposes valid constraints for a column of a table.
{ not null | null [ not null ] primary key references table-name [ ( column-name ) ] unique shared virtual persistent transient local [[[[not]]]] hidden }
Explanation
not null null values are not allowed in this column.
null null values are allowed in the column (default).
[ not null ]primary key
All values in this column must be unique and not contain a nullvalue. This column is used as the primary key of the table. Thisconstraint applies to tables only. Note: regardless of whether notnull is specified or not, this column will implicitly be not null.
referencestable-name[(column-name)]
This column is a foreign key. This means the contents of this columnis that contained in column-name of a row in the table table-name. If column-name is omitted, the primary key column isassumed. column-name must be the only primary key column oftable-name.
shared This column contains a single value shared by all the rows in the tableand by all the rows in the derived tables.
unique Specifies that values in this column are unique
virtual This column contains a single value shared by all the rows in this tableonly. All derived tables have their own values.
persistent Specifies that the values in this column are to be stored.
transient Specifies that the values in this column are not be stored.
hidden Specifies that this column must be explicitly referenced; it will not beincluded by default in statements such as select. Array columns arealways hidden; primary key columns may never be hidden. Columnsare not hidden by default.
local The local constraint only has significance in either a fault tolerantconfiguration or configurations with deployed replicas. The localconstraint will be used to indicate that the records in a table or thevalue of a column are not replicated from the active database to thestandby and replica databases.
SQL Reference Command reference
37
Rules
• Domains columns may not be primary keys.
• A column cannot have both a local constraint and a persistent constraint.
• The columns forming a reference to a table, which is constrained to be local, must beconstrained to be local.
• An array column referencing a table, which is constrained to be local, must be constrained to belocal.
• The local constraint is inherited.
• If any column of a composite foreign key is local, then all columns of the foreign key must belocal.
• It is not possible to have persistent local data.
Examples
See create table
Command reference SQL Reference
38
table-constraint-definition
This command adds a constraint to a table.
{ derived from table-name primary key (column-list) foreign key (column-list) references table-name (column-list) persistent unique (column-list) local transient }
Explanation
derived fromtable-name
A table may inherit from another table. The table-name specified inthis clause is the parent table.
primary key Defines a composite primary key made up of column-list
foreign keyreferencestable-name
Defines a composite foreign key made up of column-list
unique Defines a composite unique constraint made up of column-listcolumn-list A list of column names separated by commas.
persistent By default the column values are saved.
transient By default the column values are not saved.
local By default the columns values are not journalled to the standby or to areplica.
Rules
• When a table is inherited, all its attributes and methods are inherited.
• All the records inserted into the new table will also appear in the parent's table, but the parent doesnot know about any new columns that may have been created. Hence names of the columns in thenew table must be distinct from the columns in the parent table.
• If a table is marked persistent, all of its columns are by default persistent and those notmarked transient will be saved.
• A table by default is transient, which means that all its columns are by default transient. Atable may be marked as transient and contain columns marked persistent.
• When a table contains both transient and persistent columns, the data in transient columns will bepresent in the save file but will be removed when the file is loaded. If it is required that the transientdata may never appear in the save file (e.g. for security reasons), then use a completely transienttable. Data for tables containing only transient tables will never appear in the save file.
• All columns of a composite foreign key must have the same not null and persistenceconstraints.
SQL Reference Command reference
39
• If the primary key contains a foreign key column, the primary key must contain all columns of theforeign key.
• A table cannot have both a local constraint and a persistent constraint.
• A table constrained to be local, cannot contain any columns constrained to be persistent.
• A table constrained to be persistent cannot contain columns constrained to be local unlessthose columns are also constrained to be transient.
• The local constraint is inherited.
• If a local table constraint is used, then it must be specified in a table defining the primary key. Itcannot be specified in a derived table.
• A table that is not local cannot have any local attributes also constrained to be not null.
Examples
See create table
Command reference SQL Reference
40
create view
This command creates a view. A view is a 'virtual' table whose data is obtained directly or indirectlyfrom one or more tables by the evaluation of a query expression. It appears to the user as if it were atable but its contents depend on the data in the underlying tables when the query expression is evaluatedThese underlying tables can themselves be views.
Like tables, views can be queried, updated, inserted into, and deleted from, with restrictions. Alloperations performed on a view actually affect the underlying tables of the view.
Views are often used to do the following:
• Provide an additional level of security by restricting access to a predetermined set of rows andcolumns of a table. For example, a view of a table can be created so that columns with sensitivedata (for example, salary information) are not include in the definition of the view.
• Hide data complexity. For example, a single view can be used to create a join, which is a display ofrelated columns or rows to multiple tables. However, the view hides the fact that this data actuallyoriginates from several tables.
• Present the data in a different perspective from that of the underlying table. For example, viewsprovide a means to rename columns without affecting the tables on which the view is based.
create view view-name[ ( column-name [ { , column-name... } ] ) ] as select-expression
Explanation
create view Required keywords.view-name The name of the view.column-name The name of the column. A column may not have the same name as
any other column in the view.select-expression The select expression defining the view. A select statement. See
page 38.
SQL Reference Command reference
41
Rules
• A view must not have the same name as any other view, table, domain or built-in type.
• select-expression cannot include any reference, either direct or indirect to the name of the viewcurrently being defined.
• If a list of column names is supplied, the number of column names must match the number ofcolumns returned by the select expression.
• Every column of the view must have a column name that is unique.
• If no list of column names is supplied, the view will inherit its column names from the columns inthe select expression.
• It is possible to perform the SQL DML insert, update and delete statements on a view only if thatview is updatable.
• A view is updatable if and only if all of the following conditions apply:
1. The FROM clause of the select expression contains exactly one table reference.
2. Every select-item in the SELECT clause of the select expression (after any necessaryexpansion of "asterisk-style" select-items) consists of a column name (optionally accompaniedby an alias), representing a simple reference to a column of the underlying table. That is, noselect-item in the SELECT clause is an expression.
3. The single table reference in the FROM clause of the select expression identifies either a tableor an updatable view.
4. The select expression does not include a WHERE clause that includes a nested query thatincludes a FROM clause that includes a reference to the same table as is referenced in theFROM clause mentioned in 1.
• An insert statement performed on an updatable view will fail if no value is supplied for any columnin the underlying table defined as being NOT NULL. This could be because the view does notinclude the column as a select-item in the SELECT clause of its select expression.
• The ALTER TABLE statement applied to a table that is referenced by a view is rejected if itinvalidates the view.
If the ALTER TABLE statement is accepted, the result is same as if the view had been dropped,the table altered and the view recreated. This can result in columns being added (in any position)to, altered in or dropped from the view. The catalogue definition of the columns of the view, asrecorded in the attributes table may therefore be altered as the result of an ALTER TABLEstatement.
The ALTER TABLE statement will invalidate the view and be rejected for the following reasons:
• It adds a column that is implicitly referenced by the select expression of the view (by means ofa ‘*’ column reference in the projection), which is defined to have a specific number ofcolumns. For example if a view is defined as follows:
create view v ( a, b ) as select * from t;
It is not possible to add a column to the table t as it is implicitly referenced by the view v,which is defined to have only two columns (a and b).
• It drops a column that is explicitly referenced (by column name rather than a ‘*’ columnreference) by the select expression of the view.
• It renames a column that is explicitly referenced (by column name rather than a ‘*’ columnreference) by the select expression of the view.
Command reference SQL Reference
42
Examples
Define a view on all crime fiction:
create view CrimeFiction as
select * from Fiction where storytype = 'crime';
Define a view on all books on loan:
create view BooksOnLoan as
select b.bookno bookno, b.title title, b.author author,
b.publisher publisher, c.name customername,
c.address address, c.allowance allowance,
o.returndate returndate
from Books b, Customers c, Onloan o
where o.bookno = b.bookno and o.custno = c.custno;
SQL Reference Command reference
43
delete
This command deletes all or selected rows from a table or updatable view.
delete from table-name [ table-alias ][ where condition ]
Explanation
delete from Required keywords.table-name The name of a table or updatable view where rows are to be deleted.table-alias An alternative name for the table that can be used to reference the
table in the where condition.
where condition The condition on which rows will be deleted. See page 64.
Rules
• If no condition is specified, all rows are deleted.
• If a condition is specified, every row in the table for which the condition holds is deleted from thetable.
• If a record to be deleted is referenced by a foreign key, the delete statement will fail. This is touphold referential integrity.
• If a record to be deleted is referenced by an array, that reference will be removed from the array.
Examples
Delete all books from the Fiction table:
delete from Fiction
Delete from Customers any customer record that has no allowance.
delete from Customers
where allowance = 0
Command reference SQL Reference
44
drop domain
This command removes an existing table and all its data from the database.
drop domain domain-name
Explanation
drop domain Required keywords.domain-name The name of the existing domain to be removed.
Rules
• domain-name must refer to an existing domain.
• There must be no domains deriving from the domain to be removed.
• There must be no use of the domain in any other domain or table.
Examples
Removes the domain AgeSet from the database.
drop domain AgeSet;
SQL Reference Command reference
45
drop index
This command deletes an index from a table.
drop index index-name
Explanation
drop index Required keywords.index-name The name of the new index. The name may be optionally of the form:
local.<identifier>
If it is of this form then the index is local and the name of the indexincludes the local. prefix.
Rules
• index-name must be the name of the existing index added by create index.
• Primary and foreign keys indexes may not be dropped. They are automatically deleted when theirowning table is dropped.
Examples
Removes the index ind_bookno from the table Books.
drop index ind_booktitle;
Command reference SQL Reference
46
drop table
This command removes an existing table and all its data from the database.
drop table table-name
Explanation
drop table Required keywords.table-name The name of the existing table to be removed.
Rules
• table-name must refer to an existing table.
• There must be no tables deriving from the table to be removed.
• There must be no references from other tables (either by foreign key or by array) to the table to beremoved.
• There must be no views defined on the table to be removed.
• If the table contains rows, the rows are deleted first. If no errors are caused by deleting the rowsthen the table is deleted. Otherwise, the whole transaction is rolled back and the table is left as itwas.
• The table must not be in use by an RTRDB sub-system such as CL.
• Two tables that reference each other may be dropped by using the alter schema command.
Examples
Removes the table Fiction from the database. All records in Fiction have already been deleted.
drop table Fiction;
SQL Reference Command reference
47
drop view
This command removes an existing view from the database.
drop view view-name
Explanation
drop view Required keywords.view-name The name of the existing view to be removed.
Rules
• view-name must refer to an existing view.
• There must be no views defined on the view to be removed.
Examples
Removes the view CrimeFiction from the database.
drop view CrimeFiction;
Command reference SQL Reference
48
grant
This command is used to grant privileges for a particular table or view to users.
grant { all [ privileges ] | privilege [ { , privilege }... ] }on table-nameto { user-name | public } [ { ,{ user-name | public }} ...][with grant option]
Explanation
grant Required keyword.privilege An access privilege. See page 50
on table-name The name of the table or view for which the privileges are granted.
to user-name The name of a user to whom the privileges are granted.
Rules
• Each privilege specifies a privilege on the table specified by the table-name.
• table-name must be an existing table or view.
• Each user-name specifies a grantee and must be a user currently registered on the system.
• The user executing the statement is considered to be the grantor.
• For each privilege being granted the grantor must hold that privilege with grant option.
• Granting the privileges INSERT or UPDATE without a column name automatically grants thatprivilege in all columns of the table or view.
• If the WITH GRANT OPTION is specified, each privilege is granted with grant option.
• The same privileges may be granted by the same grantor to the same grantee any number of times.
• If the same privilege is granted to the same user twice, once with grant option and once without, theuser will hold the privilege with grant option. This holds no matter the order in which the grantsare made.
• Specifying ALL PRIVILEGES grants all privileges on table-name that are held by the grantorwith grant option.
• The owner of a table or view has all privileges on that table or view with grant option.
• All privileges granted to the PUBLIC user are implicitly granted to all other users.
Examples
Grant all security privileges on the Books table to the user named Librarian
SQL Reference Command reference
49
grant all on Books to Librarian;
Grant only select privilege on the Customers table to the users named Librarian
grant select on Customers to Librarian;
Grant update privilege on the allowance column of the Customers table to the user named Librarian
grant update(allowance) on Customers to Librarian;
Command reference SQL Reference
50
privilege
This specifies a security privilege
{ alter| delete| execute| index| insert [ ( column-name [{ , column-name }... ] ) ]| references| select| update [ ( column-name [{ , column-name }... ] ) ]}
Explanation
alter Privilege to alter a table.
delete Privilege to delete records from a table or updatable view.
execute Privilege to execute a CL handler on a table.
index Privilege to create an index on a table.
insert Privilege to insert records into a table or updatable view.
references Privilege to refer to a table within a table or column constraint.
select Privilege to query a table or view.
update Privilege to update records in a table or updatable view.
Rules
• Column names cannot be specified within a REVOKE command.
Examples
See grant and revoke.
SQL Reference Command reference
51
insert
This command adds a new row or a number of rows to a table or updatable view.
Insert a single row into a table:
insert into table-name[( column-ref {, column-ref } ...) ]values ( value {, value } ...)
Insert multiple rows into a table:
insert into table-name[ ( column-ref {, column-ref } ...) ]query
Explanation
insert into Required keywords.table-name The name of a table or updatable view into which a row is being
inserted.column-ref A reference to a column into which values are placed. The column-
name may also be a domain attribute reference. Referencing domainsdirectly is illegal; attributes must be explicitly specified in order toassign insert values, for example domain.x and domain.y
values Required keyword.value The values to be inserted into the columns.query A select statement. See page 56.
Rules
• The total number of values specified must match the total number of columns specified.
• If no columns are specified, all the values are assumed to be specified in the default column orderwhich is the same as that of select. If the table is derived from another table, the columns in thederived table appear first because they were defined first. If the table contains a domain column,the columns of the domain appear at that position. The example below illustrates the defaultordering:
create table x(i integer primary key, y integer);
create table y(derived from x, k integer, l integer);
insert into y values (1,2,3,4);
commit;
Command reference SQL Reference
52
This insert statement would insert the following values into the following columns:
i = 1, y = 2, k = 3 , l = 4
• The order of values must match the order of the columns.
• The type of the value must match the type of the column.
• Columns where no values are specified are initialised to null.
• Columns assigned to null must not have the constraint not null.
• If the query results in no rows found, no rows are inserted.
• When a table or domain definition contains a domain attribute and a new record is created, adomain record is created for that attribute even if no specific attributes in the domain record are set.Any attribute domain records are created before the parent record is created.
Examples
To insert a single record into table Fiction:
insert into Fiction
(bookno, title, author, publisher, storytype,agegroup.lowerage, agegroup.upperage)
values (29282, 'BIG SEVEN', 'JAMES, C.J', 'READS', 'WESTERN', 7,16);
SQL Reference Command reference
53
revoke
This command is used to revoke privileges for a particular table or view from users.
revoke { all [ privileges ] | privilege [{ ,privilege }...] }on table-namefrom { user-name | public } [ { ,{user-name | public}} ... ]
Explanation
revoke Required keyword.privilege An access privilege. See page 50
on table-name The name of the table or view for which the privileges are revoked.
from user-name The name of a user from whom the privileges are revoked.
Rules
• Each privilege specifies a privilege on the table or view specified by the table-name.
• table-name must be an existing table or view.
• Each user-name specifies a grantee and must be a user currently registered on the system.
• The user executing the statement is considered to be the grantor.
• For each privilege being revoked the grantee must have been previously granted privilege by thegrantor.
• Revoking a table privilege also revokes all column privileges granted for table-name.
• Specifying ALL PRIVILEGES revokes all privileges on table-name previously granted to thegrantee by the grantor.
Examples
Revoke all security privileges on the Books table from the user named Librarian
revoke all on Books from Librarian
Revoke only the select privilege on the Customers table from the users named Librarian
revoke select on Customers from Librarian
Command reference SQL Reference
54
save
This command creates a load file by saving the database to the configured file-system. The load filecontains the structure of the database (tables and other definitions) together with the state of thepersistent data and optionally the compiled form of any CL code.
save [[[[ [[[[ logging ]]]] into filename [[[[ with cl ] ]] ]] ]] ]
Explanation
save Required keyword.
logging Optional keyword specifying that journaling should switch to thenewly saved file.
into filename Optional clause specifying the name of the file to which the databaseis saved.
with cl Optional keywords, specifying that CL should be included in file.
Rules
• If no optional keywords are given (i.e. the command is just save), then the file created will have thesame name as the load_file resource specified when the database was started. A compiled form ofany CL code will be included in the load file, unless CL is disabled (the cl_enable resource was setto false) or there is no CL present in the database.
When the system is running with journalling enabled (enable_journalling resource set to true), thenthe save command will generally be used to create a new snapshot to which journal records areappended.
• If the logging keyword is given, then the file specified in the into filename clause replaces thefile given by the load_file resource. A snapshot of the current state of the database is written tofilename and journaling is enabled so that subsequent changes to the database are appended to thisfile. A compiled form of any CL code is also included in the file unless CL is disabled. Note thatsubsequent calls to save will use this filename instead of the original load_file resource.
• If the into filename clause is specified, a snapshot of the current state of the database (structureand persistent data) is created, but the journalling will continue to append journal records to the fileoriginally specified in the load_file resource. Thus, the save into command can be used to take asnapshot of the current state of the database without interrupting the journalling.
• The with cl clause only has affect if the into filename clause is present.
If the with cl clause is specified, the load file created will include the compiled form of any CLcode in addition to the database structure and persistent data.
SQL Reference Command reference
55
• An intermediate file with the extension “.tmp” will be created during the creation of the load file,this file will be removed once the load file creation has completed. The sequence is:
Create snapshot of database to filename.tmp
Rename filename to filename.old, if there already is a file called filename.
Rename filename .tmp to filename
Thus, where the file that is to be created already exists, the file will be renamed with a “.old”extension.
• Although this command involves writing to disk, the database will not block during the creation ofthe load file. The default behaviour is for the client to be informed of completion of the commandwhen the save has been initiated. The creation of the load file then continues as a backgroundprocess within the database, the database able to service other requests. To determine when thesave has completed the command can be issued in safe-commit mode, in which case the client willbe informed on the completion of the command only when the creation of the load file is completeor an error occurs.
• By convention filename is usually supplied with “.dat” extension. However due to thelimitation of some file systems this is not enforced.
Examples
To create a snapshot of the current state of the database, using the filename specified by the load_fileresource:
save;
To create a snapshot of the current state of the database to the file backup.dat:
save into 'backup.dat';
To create a snapshot that includes compiled CL code:
save into 'test.dat' with cl;
To create a snapshot and switch journaling to the file newtest.dat:
save logging into 'newtest.dat';
Command reference SQL Reference
56
select
This command selects columns of data from the database. The data may be selected from a single tableor a number of tables and the selection may depend upon a condition. Data may be combined in acompound query from multiple select statements using the union, except and intersect operators.
select [ all distinct ]{ * { { table-name.*
domain-column-ref.* expr [ output-alias-name ] }
[ [, { table-name.* domain-column-ref.* expr [ output-alias-name ] } } ...] } }
fromtable-name [ table-alias-name ][ { ,table-name [ table-alias-name ] } ...]
[ where condition ][ { union intersect except } [ all distinct ]
[ corresponding [ by ( column-name [, column-name] ... ) ] ]select-from-where ] ...
[ order by { column-name value [ asc desc ] }[ { ,{ column-name value [ asc desc ] } } ...]
Explanation
select Required keyword.
all Optional keyword, specifying that all rows to be returned; the default.
distinct Optional keyword, specifying that only distinct rows to be returned. * All the columns from the table specified in the from clause will be
selected except those that are hidden. domain-column-ref.* All columns from the named domain will be selected. table-name.* All the columns from the named table will be selected. expr expression. See page 48. output-alias-name To rename the columns or expressions specified for output.
from required keyword. table-name Name of table or view to select from. table-alias-name Alias for a table-name; the alias may be used in the where clause.
where condition Specifies a condition that all selected rows must conform to. See page66
union Indicates a compound query. Specifies that rows will be merged.
SQL Reference Command reference
57
intersect Indicates a compound query. Specifies that only common rows will bekept.
except Indicates a compound query. Specifies that only rows present in firstquery but not in second will be kept.
corresponding Specifies how columns in queries will be matched. select-from-where Another select statement containing just the select, from and where
clauses.
order by Specifies the order in which rows are to be returned. By default theorder is ascending.
column-name The name of the column. value A positive integer referring to an output column listed previously in
the select statement.
Rules
• Where * is used, all columns that are not hidden are returned from the table or domain referenced.The default column ordering is the order of definition. If the table or domain referenced is derivedfrom another table or domain, the derived columns appear first. The example below illustrates thedefault ordering:
create table x(i integer primary key, j integer);
create table y(derived from x, k integer, l integer);
select * from y;
This select statement would return the column values in the following order:
i, j, k, l
• A table specified in the from clause may be given an alias that may be used instead of the actualtable name in the where clause. All alias names must be unique within the select statement.However, once a table name has been aliased, the real name is free to be used as an alias foranother table.
• Output columns may be given alias names. These names may not be used elsewhere in thestatement.
• Output columns that involve expressions must be given an alias name.
• Ambiguous column names (columns from different tables with the same name) must bedistinguished by prefixing them with the name of the table.
• Inclusion of the distinct clause will generate an error if the select statement could potentially returnduplicate rows. Only select statements whose output columns include all the primary key columnsof the tables specified in the from clause can be successfully executed with a distinct clause.
• The component queries appearing in a compound query must be union compatible. Two queriesare union compatible if they return the same number of columns and columns at the same positionin the result set are data type compatible. For Polyhedra two columns will be data type compatibleif their type appears in the same row of the following table:
char varchar
Command reference SQL Reference
58
integer integer8 integer16
float float32
bool
datetime
binary
• Note that the names of the columns are not relevant in determining whether the queries are unioncompatible
• A compound query combines the results of its component queries into a single result set. The formof the combination is dependent on the particular set operator and whether the all, or distinctkeywords are present
• union
The union operator returns those rows that are returned by either component query.
• except
The except operator returns only those rows that are returned by the first component query butnot also returned by the second component query.
• intersect
The intersect operator returns only those rows that are returned by both the componentqueries.
• The distinct keyword specifies that all duplicate rows should be eliminated from the result set.This is the default behaviour if neither the all or distinct keywords are supplied. The all keywordspecifies that any duplicate rows should be retained in the result set.
• The columns returned by a compound query can be reduced by using the optional correspondingclause. A corresponding clause containing just the corresponding keyword specifies that onlycolumns with the same name in both the component queries should appear in the component queryresult set. Specifying a column list further restricts the columns to the columns in the list thatappear in both the component queries.
• A compound query is not updateable. i.e. a view defined as a compound query cannot be updated.
• A compound query cannot be an active query.
• A compound query may be used in a create view statement.
• A compound query may be used in an insert-select statement.
• A compound query may be used as a sub-query.
Examples
To select all the titles of references:
select title from Reference;
To select all the details of all the books in the library:
select * from Books;
To select all the details of the loan information where the return date is before 12th April 1997:
select * from Onloan
SQL Reference Command reference
59
where returndate < date('12-APR-1997');
To select all the details of the loan information where the return date is before 12th April 1997 orcustomer was one of the first 100 :
select * from Onloan
where returndate < date('12-APR-1997')
union
select * from Onloan
where custno <= 100;
To select the all customers who have a name containing Smith or a loan where the return date is before12th April 1997 :
select * from Onloan
where returndate < date('12-APR-1997')
union corresponding (custno)
select * from customers
where name like “%Smith%”
Command reference SQL Reference
60
send
This command sends an arbitrary event to selected rows of a table. This event triggers the calling of aCL handler of the same name attached to the table.
Syntax
send event to table-name [ where condition ]]]]
Explanation
send Required keyword. event Character string literal.
to Required keyword. table-name The name of the table to send the event to.
where condition Specifies a condition on the table. Only those rows that satisfy thiscondition are sent the event.
Rules
• If no where clause is specified then all rows in the table will receive the event.
• If the event specified does not match any handler attached to the table (or any derived table) thesend will have no effect.
• If the where clause is such that no records are selected from the table, the send will have no effect.
Examples
Send the event overdue to all overdue loans:
send 'overdue' to onloan where returndate > today();
SQL Reference Command reference
61
shutdown
This command initiates a database shutdown.
Syntax
shutdown
Explanation
shutdown Required keyword.
Rules
• The database shutdown is performed immediately after a transaction containing a shutdowncommand is committed.
• If security is enabled, only the SYSTEM user may execute a shutdown command.
Examples
Shutdown the database:
shutdown;
Command reference SQL Reference
62
update
This command updates selected data in a table or updatable view. The set clause determines whichcolumns are updated and what new values are stored in them.
Syntax
update table-name [ table-alias ]set column-ref = expr[ { , column-ref = expr } ...][ where condition ]
update table-name [ table-alias ]set ( column-ref [, column-ref ...] ) = ( query )[ where condition ]
Explanation
update Required keyword. table-name The name of table or updatable view to be updated. table-alias Another name by which the table may be referenced.
set Required keyword. column-ref The name of column being updated. expr May include column references to columns in table-name. For
example:
update bob
set i = i + 1
query A select statement. See page 56.
where condition Specifies a condition where those rows that satisfy this condition areupdated. See page 64.
SQL Reference Command reference
63
Rules
• Primary key columns may not be updated.
• If no where clause is specified, all the records in the named table are updated.
• Columns may be updated using expressions referencing columns in the table or shared columnselsewhere.
• Columns making up a primary key may only be updated with their current values.
• If a partial foreign key is updated, the rest of the key is made up from present values from each rowas the update is being executed. The entire foreign key at that time must be valid and reference anexisting target primary key.
• The query clause (if used) must return no more than one row. If no rows are returned, all thecolumns specified will be updated to null, providing the individual column constraints aresatisfied.
• The query may select from the table being updated1.
• Each value in the row brought back by a query must have a corresponding column specified. Thevalues are then assigned to their respective columns.
• Domain columns may not be updated directly, but their component columns of built-in type mustbe referenced explicitly.
Examples
To change every reference to a publisher called 'Rabbits' to one called 'Reads':
update Books
set publisher = 'Rabbits'
where publisher = 'Reads';
To give all customers an extra book allowance:
update Customers
set allowance = allowance + 1;
To give all customers the same allowance as C. P. Jones:
update Customers
set (allowance) = (select allowance from Customers
where name = 'Jones, C.P.');
Correlated queries and nested selects are not supported.
Command reference SQL Reference
64
Data types
This section describes the supported data types supported.
Built-in data types integer An integer value is a 32-bit signed number.
integer8 An integer8 value is a compact form of integer. It is treated exactly the sameas an integer type, but only 8 bits are stored.
integer16 An integer16 value is a compact form of integer. It is treated exactly the sameas an integer type, but only the least significant 16 bits are stored.
char A char value is an array of ASCII characters. It may not include a null character. Asingle quote may be included within the character string by specifying two consecutivesingle quotes. All character arrays have variable lengths and there is no limit on the sizeof the array; it may be of zero length.
varchar As char, but you may specify a length field. Strings stored in a varchar field will bepadded to the given length with nulls, or truncated if they have more than lengthcharacters.
real A real value is a double precision floating point number. real values may beexpressed in decimal point or exponential format.
float32 A float32 value is a single precision floating point number. It is handled in exactlythe same way as a real value but only the least significant 32 bits are stored.float32 values may be expressed in decimal point or exponential format.
datetime This type contains the date and time. The information is encoded into a 64-bit value.For details about this data type see page 64.
bool This type contains a truth value, true or false.
array This type contains a set of references to table records of a particular type. Array valuesmay not be manipulated by SQL.
binary A variable length binary data. Any parenthesised limit is ignored.
Datetime type A datetime type consists of a date and time value packed into an atomic type. The value is treated asif offset from midnight on 01-JAN-0001. Thus 0 seconds is equivalent to 00:00:00 01-JAN-0001.
When used directly, datetime fields are coerced to and from char fields that hold a string representationof the value. The format of the string representation can be configured to suit the user; please see thePolyhedra User's Guide for more information.
Various functions are provided for creating and manipulating datetime fields, and for extracting parts ofthe datetime value. For example
date('1-APR-1982') -- creates a date
add_months(date('1-APR-1982'), 2) -- increments by two months
the_month(date('1-APR-1982')) -- extracts the month value
SQL Reference Command reference
65
to_months(date('1-APR-1982')) -- returns number of months-- since 01-JAN-0001
get_date(date('1-APR-1982')) -- returns a string-- representation
Addition and subtraction of datetime types is allowed. The result is a datetime value. For example:
date('1-APR-1982') + time('11:49:00')
Three functions return datetime values holding the current date, the current time, and the currentdatetime; they are today(), time(), and now() respectively.
This is just a small selection of the functions supported in SQL. See Appendix A for full details.
Support for SQL Aggregate functions is also provided. This functionality, however, does not supportthe use of ALL, DISTINCT, GROUP BY, or HAVING.
Array type A column can be declared as an array type. An array is a collection of foreign keys to a table. Arraysof built-in types are not supported.
An array type is specified as follows:
array of <table_name>
Domain type A column can be declared as a domain type. The domain must have been defined previously using thecreate domain command. A domain type is specified as follows:
<domain_name>
For example, the following defines a table with a column b whose type is a previously defined domaincalled mydomain:
create table mytable
(
a integer primary key,
b mydomain
);
Integer literalsLiterals consisting entirely of digits are considered to be of type integer. If the value is not within therange for the integer type (32-bit signed number), the resulting value is undefined. For example, thefollowing inserts a value for the intcol column that is undefined:
insert into test ( id, intcol ) values ( 1, 4294967295 );
Similarly if a literal consisting entirely of digits is used to specify a value for a real attribute then thevalue will be undefined if the integer value resulting from the literal is not within the range for theinteger type. Thus
insert into test ( id, realcol ) values ( 1, 4294967295 );
will result in an undefined value if the realcol attribute.
Real literalsLiterals consisting of digits with a decimal point are considered to be of type real. For example, thefollowing inserts a value for the realcol column of 4.29497e+09:
insert into test ( id, realcol ) values ( 1, 4294967295.0 );
Command reference SQL Reference
66
Expressions
An expression is a combination of one or more literals, identifiers, operators and function calls. Theconstraint on an expression depends on the data types that make up the expression. This sectionoutlines the data types supported and the syntax of expressions.
Simple expressions
An expression can take many forms. These include:
• a literal
• an identifier
• an execution parameter
• a function call
• a column reference
• a field attribute
• a combination of the above
Literal These are unchanging values of types integer, real and char. For example:
123, 68.4, -2.3e8, 'hello', "02-FEB-1961 00:00:00"
Identifier Identifiers are character strings that identify tables, columns and indexes. An identifier may also be afield attribute such as column-name.origin or column-name.time.
Execution parameter An execution parameter is an expression whose values is supplied by the client at run-time. Executionparameters may be used in place of any constant expression in an SQL statement. An executionparameter takes the form:
:<type>name where type is any SQL data type.
for example
:<integer>maxint
:<float>maxvalue
SQL Reference Command reference
67
If the type is omitted, the type is assumed to be char.
Example:
select * from tables where name = :myname
and depth = :<integer>mydepth;
Execution parameters can only be used from clients which support their use.
Function call The general syntax for a function call is as follows:
function-name ( [* { [ all distinct ] expr [ { ,expr }...] } ] )
For example: now() add_months(d,1) days(1)
There is no limit to the number of arguments passed to a function.
There is a host of built-in functions. See Appendix A.
Support for SQL Aggregate functions is also provided. This functionality does not currently include:
all, distinct, group by, having
Column reference A column reference references a column of a table. The referenced column must be of a built-in type.The general syntax is:
[table-name.][{column-name.}...]column-name
For example: Books.title, title, a.b.c
The table-name may only be omitted if the column-name itself is sufficient to refer to the columnunambiguously, in the context of the surrounding SQL statement. For example, you can write:
select name from tables
is equivalent to:
select tables.name from tables
Domain columns may not be referenced directly but their columns of built-in type can. For example:
t dom
x y
select dom from t; --illegal
select dom.x from t;
select dom.y from t;
Command reference SQL Reference
68
The values of shared or virtual columns may be accessed in any context as global constants byspecifying the full path name for that column. For example:
create table bob
( a integer primary key,
); create table info
( b integer primary key,
s integer shared -- info.s is shared
); select a, info.s from bob; -- info.s has global scope
Combination Any of the above types of expressions may be combined in the following ways (listed in order ofprecedence):
(expr) +expr -expr
expr * expr expr / expr
expr + expr expr - expr
expr expr
Conditions
A condition is one or more expressions combined using the comparison operators as follows: = equal to
<> not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
SQL Reference Command reference
69
A condition evaluates to true, false or unknown, and multiple conditions may be combined using: AND OR
Conditional formats include: (condition) condition [IS [NOT] truth-value]
condition AND condition
condition OR condition
NOT condition
expr = expr
expr <> expr
expr < expr
expr > expr
expr <= expr
expr >= expr
expr IS [NOT] NULL
expr [NOT] IN (expr, ...)
expr [NOT] IN (select-expression)
expr [NOT] LIKE pattern [ESCAPE escape-character]
Nested Queries
A limited form of SQL nested queries is supported. The IN operator supports expressions of the form,column-name [NOT] IN (select-expression)
where,
truth-value is TRUE, FALSE or UNKNOWN
select-expression is an SQL select statement returning a single column.
column-name is a column reference.
The type of the column specified by column-name must match the type of the column returned byselect-expression.
Outer references from a nested query to its containing query are not supported.
The LIKE operator
The LIKE operator is used in character string comparisons with pattern matching. expr evaluates to a column reference of type character string pattern evaluates to a character string literal escape-character if the ESCAPE clause is specified, then this evaluates to a
string literal of length 1
Notes
The pattern can include the following special characters for pattern matching:
• % matches zero or more characters
• _ matches exactly one character
Command reference SQL Reference
70
• The escape-character specifies a single character that can then be used in thepattern to escape a special character (including itself) so that it may be taken literally.
• Case is significant.
• NULL strings are never selected by LIKE or NOT LIKE.
SQL Reference Appendix A: Built-in functions
71
Appendix A: Built-in functions
The functions available in SQL are described in this section. The functions are described inalphabetical order.
add_months
datetime add_months(datetime, integer n)
Given a datetime value and a time interval in months, this function returns a datetime valueincremented by n months. The value of n may be positive or negative. If the new month does not haveenough days, the day is reduced until a valid date is obtained.
For example:
add_months(date('27-SEP-1992'),1)
returns: date('27-OCT-1992')
add_months(date('30-JAN-1992'),1)
returns: date('29-FEB-1992')
add_years
datetime add_years(datetime, integer n)
Given a datetime value and a number of years, this function returns datetime value incrementedby n years. The value of n may be positive or negative. The day may be altered slightly to prevent theformation of non-existent dates arising from leap years or other anomalies.
For example:
add_years(date('29-FEB-1992'),1)
returns: date('28-FEB-1993')
Appendix A: Built-in functions SQL Reference
72
binaryToHexString
char binaryToHexString(binary)
Returns the hexadecimal string representing the given binary value.
Example: binaryToHexString(x’0102030405’)
returns: ’0102030405’
bitAnd
Returns the bit-wise AND of its parameters.
integer bitAnd(integer, ...)
This function can take one or more integer parameters.
Example: bitAnd(9, 3, 1)
returns: 1
SQL Reference Appendix A: Built-in functions
73
bitGet
Returns the value of a specified bit.
integer bitGet(integer value, integer n)
Returns the value of the nth bit of value.
Example: bitGet(9, 3 )
returns: 1
bitOr
Returns the bit-wise OR of its parameters.
integer bitOr(integer, ...)
This function can take one or more integer parameters.
Example: bitOr(9, 3, 1)
returns: 11
Appendix A: Built-in functions SQL Reference
74
bitSet
Returns a value with specified bits set.
integer bitSet(integer value, integer n1, ... integer nn)
Returns value with the n1 ... nn bits set.
Example: bitSet(9, 2)
returns: 13
bitShift
Returns a value shifted left or right.
integer bitShift(integer value, integer count)
If count is positive, returns value shifted left by count bits. If count is negative, returns value shiftedright by count bits. The right shift is logical (0-fill). The result is undefined if the absolute value of n isgreater than or equal to the length of value in bits (32).
Example: bitShift(9, 2)
returns: 36
SQL Reference Appendix A: Built-in functions
75
bitShiftLeft
Returns a value shifted left by a specified number of bits.
integer bitShiftLeft(integer value, integer count)
Returns value shifted left by count bits. The result is undefined if n is negative or greater than orequal to the length of value in bits (32).
Example: bitShiftLeft(9, 2)
returns: 36
bitShiftRight
Returns a value shifted right by a specified number of bits.
integer bitShiftRight(integer value, integer count)
Returns value shifted right by count bits. The shift is logical (0-fill). The result is undefined if n isnegative or greater than or equal to the length of value in bits (32).
Example: bitShiftRight(9, 2)
returns: 2
Appendix A: Built-in functions SQL Reference
76
bitTest
Returns whether specified bits are set.
bool bitTest(integer value, integer n1, ... integer nn)
Returns True if all the bits bits n1 ... nn are set.
Example: bitTest(9, 2)
returns: False
bitUnset
Returns a value with specified bits cleared.
integer bitUnset(integer value, integer n1, ... integer nn)
Returns value with the n1 ... nn bits unset.
Example: bitUnset(9, 3)
returns: 1
SQL Reference Appendix A: Built-in functions
77
bitXOr
Returns the bit-wise XOR of its parameters.
integer bitXOr(integer, ...)
This function can take one or more integer parameters.
Example: bitXOr(9, 3, 1)
returns: 11
char_to_int
integer char_to_int(char)
This function takes an string value and converts it to an integer.
ConvertFromUCT
datetime convertFromUCT (datetime uct_timestamp, integer dst)
This function converts a timestamp from UCT to local time based on the time zone displacement for thecurrent session and a specified daylight saving time displacement. The uct_timestamp argumentspecifies a timestamp in UCT. The dst argument specifies a daylight displacement time in minutes. Thetimestamp returned is the result of adding the time zone displacement for the current session and thedaylight saving time displacement specified by dst to the UCT timestamp specified by uct_timestamp.
Appendix A: Built-in functions SQL Reference
78
ConvertToUCT
datetime convertToUCT (datetime local_timestamp, integer dst)
This function converts a timestamp from local time to UCT based on the time zone displacement for thecurrent session and a specified daylight saving time displacement. The local_timestamp argumentspecifies a timestamp in local time. The dst argument specifies a daylight saving time displacement inminutes. The timestamp returned is the result of subtracting the time zone displacement for the currentsession and the daylight saving time displacement specified by dst from the local timestamp specifiedby uct_timestamp.
date
datetime date(char 'date')
Converts the given date string to the equivalent datetime value. The string may not contain a timecomponent.
The string format is fixed at “%02d-%3M-%04y”. See the Polyhedra User's Guide for a description ofthe format.
datetime
datetime dateTime(char 'datetime')
Creates and returns a DateTime value from a string containing date and time components.
The string format is dependant on the international resources defined for the Polyhedra component atstart up. See the Polyhedra User's Guide for more information on internationalisation.
SQL Reference Appendix A: Built-in functions
79
dateTimeF
datetime dateTimeF(char 'datetime', char 'format')
Creates and returns a DateTime value from a string using a specific format. The format of the stringis explicitly defined in the format string and is not modified by internationalisation resources.
days
datetime days(integer n)
Given a time interval of n days, this function returns a datetime value representing days from thebeginning of time2. This function is useful for adding or taking days from a datetime value.
get_date
char get_date(datetime)
Returns a string representation of the date portion of the datetime value given. The string format isfixed at “%02d-%3M-%04y”. See the Polyhedra User's Guide for a description of the format.
get_datetime
char get_datetime(datetime d)
Returns a string representation of the datetime value given. The string format is dependant on theinternational resources defined for the Polyhedra component at start up. See the Polyhedra User'sGuide for more information on internationalisation.
2The beginning of time is defined as 1-JAN-0001 00:00:00. In 1752 the Julian calendar was superseded by the Gregoriancalendar. Eleven days, 3-SEP-1752 to 13-SEP-1752 inclusively, were lost on the realignment of the calendars.
Appendix A: Built-in functions SQL Reference
80
get_datetimef
char get_datetimef(datetime d, char format)
Returns a string representing the datetime value given in the specified format. The format of the stringis explicitly defined in the format string and is not modified by internationalisation resources.
get_time
char get_time(datetime)
Returns a string representation of the time portion of the datetime value given. The string format isdependant on the international resources defined for the Polyhedra component at start up. See thePolyhedra User's Guide for more information on internationalisation.
getBinInBinary
binary getBinInBinary(binary value, integer offset, integer length)
Returns an extract of the supplied binary value, consisting of length bytes starting at positionoffset. The bytes are numbered from zero; if the supplied binary is less than offset+lengthbytes long, the result will be truncated accordingly (with a zero-byte result if the original value was lessthan offset bytes long.
Example: getBinInBinary(x’01020304050607’, 2, 3)
returns: x’030405’
getConnection
integer getConnection()
Returns the value of the connection identifier for the client connection, responsible for a data update. It
SQL Reference Appendix A: Built-in functions
81
returns null when no connection initiated the transaction or when connection monitoring is not enabled.
getUser
char getUser()
Returns the name of the user that initiated the current transaction. If no user initiated the currenttransaction, because it was initialised within the RTRDB by a sub-system such as the historian, then thereturn value will be null. If security is disabled it will return the string 'SYSTEM'.
hexStringToBinary
binary hexStringToBinary(char)
Returns the binary value represented by the supplied string, assuming a hexadecimal encoding.
Example: hexStringToBinary(’0102030405’)
returns a binary value equivalent to the literal constant: x’0102030405’
Appendix A: Built-in functions SQL Reference
82
hours
datetime hours(integer n)
Given a time interval of n hours, this function returns a datetime value set to n hours from thebeginning of time3. The remaining fields are set to the default values. This function is useful foradding or taking hours from a datetime value.
int_to_char
char int_to_char(integer)
This function takes an integer value and converts it to a string.
last_day
datetime last_day(datetime)
Given a datetime value this function returns the end of the month datetime value.
local_time
datetime local_time(datetime)
This function takes a datetime value and converts to local time.
3The beginning of time is defined as 1-JAN-0001 00:00:00. In 1752 the Julian calendar was superseded by the Gregoriancalendar. Eleven days, 3-SEP-1752 to 13-SEP-1752 inclusively, were lost on the realignment of the calendars.
SQL Reference Appendix A: Built-in functions
83
lower
string lower(string)
This function returns a string with uppercase character data converted to lowercase.
microSeconds
datetime microSeconds(integer n)
Given a time interval of n microseconds, this function returns a corresponding datetime value.
milliSeconds
datetime milliSeconds(integer n)
Given a time interval of n milliseconds, this function returns a corresponding datetime value.
minutes
datetime minutes(integer n)
Given a time interval of n minutes, this function returns a datetime value set to n minutes from thebeginning of time5. The remaining fields are set to the default values. This function is useful foradding or taking minutes from a datetime value.
now
datetime now()
This function returns the current date and time as a datetime value. This function cannot be usedwithin an active query as the active query may be re-evaluated at arbitrary times.
Appendix A: Built-in functions SQL Reference
84
numberOfBytes
integer numberOfBytes(binary value )
Returns a count of the number of bytes in the supplied binary value
Example: numberOfBytes(x’010203040506070809’)
returns: 9
seconds
datetime seconds(integer n)
Given a time interval of n seconds, this function returns a datetime value set to n seconds from thebeginning of time. The remaining fields are set to the default values. This function is useful for addingor taking seconds from a datetime value.
setBinInBinary
binary setBinInBinary(binary value, integer offset, binary patch)
Returns a modified version of the supplied binary value, with the supplied patch applied at theindicated position (with the bytes being numbered from zero). If the value being patched is not longenough, it is first extended with sufficient zero bytes at the end to make it possible to be patched.
Examples: setBinInBinary(x’01020304050607’, 2, x’aabbcc’)
returns: x’0102aabbcc0607’
SQL Reference Appendix A: Built-in functions
85
setBinInBinary(x’01020304050607’, 9, x’aabbcc’)
returns:
x’010203040506070000aabbcc’
standard_time
datetime standard_time(datetime)
This function takes a local time datetime value and converts to standard time. Standard time is hostsystem dependent, but it is usually Greenwich Mean Time (Common Universal Time).
the_day
integer the_day(datetime)
Given a datetime value, this function retrieves the days and returns an integer value in the rangeof 1 to 31.
the_hour
integer the_hour(datetime)
Given a datetime value, this function retrieves the hours and returns an integer value in the rangeof 0 to 23 where 0 is midnight.
the_microsecond
integer the_microsecond(datetime)
Given a datetime value, this function retrieves the microseconds and returns an integer value inthe range of 0 to 99999.
Appendix A: Built-in functions SQL Reference
86
the_millisecond
integer the_millisecond(datetime)
Given a datetime value, this function retrieves the milliseconds and returns an integer value inthe range of 1 to 999.
the_minute
integer the_minute(datetime)
Given a datetime value, this function retrieves the minutes and returns an integer value in therange of 0 to 59.
the_month
integer the_month(datetime)
Given a datetime value, this function retrieves the months and returns an integer value in therange of 1 to 12 where 1 is January.
the_second
integer the_second(datetime)
Given a datetime value, this function retrieves the seconds and returns an integer value in therange of 0 to 59.
SQL Reference Appendix A: Built-in functions
87
the_weekday
integer the_weekday(datetime)
Given a datetime value, this function retrieves the weekday and returns an integer value in therange of 0 to 6 where 0 is Sunday.
the_year
integer the_year(datetime)
Given a datetime value, this function retrieves the years and returns an integer value in the rangeof 1 to 8000.
time
datetime time(char 'time-syntax')
Given a string holding a time value, this function returns a corresponding datetime value. The stringmay not contain a date component.
The string format is dependant on the international resources defined for the Polyhedra component atstart up. See the Polyhedra User's Guide for more information on internationalisation.
to_days
integer to_days(datetime)
This function is useful for comparing dates using day intervals. The function returns the number ofdays between the datetime value and the beginning of time4.
4The beginning of time is defined as 1-JAN-0001 00:00:00. In 1752 the Julian calendar was superseded by the Gregoriancalendar. Eleven days, 3-SEP-1752 to 13-SEP-1752 inclusively, were lost on the realignment of the calendars.
Appendix A: Built-in functions SQL Reference
88
to_hours
integer to_hours(datetime)
This function is useful for comparing dates using hour intervals. The function returns the number ofhours between the datetime value and the beginning of time.
to_minutes
integer to_minutes(datetime)
This function is useful for comparing dates using minute intervals. The function returns the number ofminutes between the datetime value and the beginning of time6.
to_months
integer to_months(datetime)
This function is useful for comparing dates using month intervals. The function returns the number ofmonths between the datetime value and the beginning of time.
today
datetime today()
This function returns today's date as a datetime value. The time part is set to midnight 00:00:00.This function cannot be used within an active query.
upper
string upper(string)
This function returns a string with lowercase character data converted to uppercase.
SQL Reference Appendix B: Conformity with ANSI SQL
89
Appendix B: Conformity with ANSI SQL
Omissions from ANSI SQL (ISO 9075, 1989)
The following have been omitted from the RTRDB supported SQL:
• Privilege definitions (section 6.10)
• Module Language (section 7)
• Close statement (section 8.1)
• Commit statement (section 8.2)
• Declare cursor (section 8.3)
• Delete statement: positioned (section 8.4)
• Fetch statement (section 8.6)
• Open statement (section 8.8)
• Rollback statement (section 8.9)
• Embedded Select statement (section 8.10)
• Update statement: positioned (section 8.11)
• Embedded SQL host programs (annex A to F)
• Indicators (part of section 5.6)
• Authorisation (part of section 6.1)
• Set functions (section 5.8)
• Between predicate (section 5.12)
• Qualify predicate (section 5.16)
• Exists predicate (section 5.17)
• Group By clause (section 5.22)
• Having clause (section 5.23)
• Subqueries (section 5.24)
• Query specification (section 5.25)
Appendix B: Conformity with ANSI SQL SQL Reference
90
Changes from ANSI SQL
Empty stringThe standard (ANSI SQL ISO 9075, 1989 section 5.2) appears to indicate that a character string literalmay not be empty. The syntax has been extended to allow a character string literal to contain an emptystring.
Case insensitivityThe standard states that all keywords are in upper case. The standard has been extended so thatkeywords are case insensitive and may be written in any case. For example, CREATE, create andCReaTe are recognised as the same keyword.
Naming rulesThe standard states that names of identifiers should not exceed more than 18 characters. SQL has beenextended so that there is no limit to the length of names. The standard states that all the characters of aname should be in upper case letters. In this version the characters may be upper or lower case.
Additional keywordsSeveral keywords have been added to facilitate the extra syntax. These include:ADD COMPUTING INDEX PURGING
ALTER DATETIME LOAD SAVE
ARRAY DERIVED LOGGED SHARED
BINARY DOMAIN LOGGING TRANSIENT
BOOL DROP MODIFY TRUE
BUT EVERY OLD VIRTUAL
CHANGE FALSE PERSISTENT
All reserved words defined by the standard are defined for the parser even if they are not used by thisimplementation for compatibility purposes.
Query syntaxThe DECLARE CURSOR (ANSI SQL ISO 9075, 1989 section 8.3) and associated syntax has beenomitted. The cursor syntax was a jacket around the query specification and its removal brings the querysyntax up to the top level.
As a result of this:
• the SELECT statement (query-specification) can now be carried out at the toplevel.
•••• ORDER BY is made a trailing clause of the SELECT statement.
SQL Reference Index
91
Index
add_months, 71add_years, 71add-item, 18Additional keywords, 90Alter domain, 13alter schema, 15Alter table, 16alter-item, 19ANSI SQL
changes, 90conformity, 89
ANSI standard ISO 9075, 1Array type, 65bitAnd, 72bitGet, 73bitOr, 72, 73, 80, 81, 84bitSet, 74bitShift, 74bitShiftLeft, 75bitShiftRight, 75bitTest, 76bitUnset, 76bitXOr, 77Built-in
data types, 64functions, 71
call, 24Changes (ANSI SQL), 90char_to_int, 77Column
constraint, 36definition, 35redefn, 23references, 67shared columns, 8
Combination of expressions, 68Command reference, 11Conditions, 68Conformity with ANSI SQL, 7, 89Conventions
document conventions, iiiConvertFromUCT, 77ConvertToUCT, 78Create domain, 26Create index, 28Create schema, 30Create table, 32Data types, 64Database (saving the database), 8date, 78dateTime, 78Datetime type, 64dateTimeF, 79
days, 79Definition
of columns, 35Delete from, 43Detailed descriptions of SQL statements, 11Document
conventions, iiiDomain type, 65Drop domain, 44Drop index, 45Drop table, 46Drop view, 47drop-item, 20Enhancements, 7Example
inheritance, 8Example layout, 12Execution parameters, 66Expressions, 66
combination of different types, 68conditions, 68simple, 66
Extensions to SQL, 1Function
built-in functions, 71Function
calls, 67Functions
add_months, 71add_years, 71bitAnd, 72bitGet, 73bitOr, 72, 73, 80, 81, 84bitSet, 74bitShift, 74bitShiftLeft, 75bitShiftRight, 75bitTest, 76bitUnset, 76bitXOr, 77char_to_int, 77, 78date, 78dateTime, 78dateTimeF, 79days, 79get_date, 79get_datetime, 79get_datetimef, 80get_time, 80getConnection, 81hours, 82int_to_char, 82last_day, 82
Index SQL Reference
92
local_time, 82lower, 83microSeconds, 83milliSeconds, 83minutes, 83now, 83seconds, 84standard_time, 85the_day, 85the_hour, 85the_microsecond, 85the_millisecond, 86the_minute, 86the_month, 86the_second, 86the_weekday, 87the_year, 87time, 87to_days, 87to_hours, 88to_minutes, 88to_months, 88today, 88upper, 88
get_date, 79get_datetime, 79get_datetimef, 80get_time, 80getConnection, 81getUser, 81grant, 48hours, 82Identifiers, 66Indexes (creation and deletion), 8Inheritance, 7
diagram example, 8insert into, 51int_to_char, 82Keywords (additional), 90last_day, 82Layout of examples, 12Literals, 66local_time, 82lower, 83microSeconds, 83milliSeconds, 83minutes, 83modify-item, 21Naming rules, 5now, 83Object-oriented, 7Object-oriented
design, 1
Overview of SQL, 1Parameters (execution parameters), 66privilege, 50Re-definition
of columns, 23Reference (column references), 67rename-item, 22Reserved words, 6revoke, 53RTRDB, 1Saving the database, 8seconds, 84select, 56send, 60, 61Shared columns, 8Simple expressions, 66SQL
conformity with ANSI SQL, 7extensions, 1lexical conventions, 5overview, 1statements (detailed descriptions of), 11
standard_time, 85Statements (summary of SQL statements), 11Summary
of enhancements, 7of SQL statements, 11
table-constraint-definition, 38the_day, 85the_hour, 85the_microsecond, 85the_millisecond, 86the_minute, 86the_month, 86the_second, 86the_weekday, 87the_year, 87time, 87to_days, 87to_hours, 88to_minutes, 88to_months, 88today, 88Type
array, 65data types, 64datetime, 64domain, 65types of SQL statements, 11
update, 62upper, 88Words
reserved, 6