Daffodil DB SQL Reference Guide
Daffodil DB SQL Reference Guide
Version 4.0
February 2004
Copyright Daffodil Software Limited
Sco 42, 3rd Floor
Old Judicial Complex, Civil Lines
Gurgaon - 122001
Haryana, India.
www.daffodildb.com
Preface ................................................................................. 9
Purpose......................................................................................... 9
Audience ....................................................................................... 9
Conventions ...................................................................... 10
Related Documentation .................................................... 11
Keywords ........................................................................... 12
Reserved Words ......................................................................... 12
Non-Reserved Words ................................................................. 16
Identifier ............................................................................. 19
Regular Identifier......................................................................... 19
Delimited Identifier ...................................................................... 20
Data Types ......................................................................... 21
Predefined Type.......................................................................... 21
Character String Type ..............................................................................................22
Character or Char.............................................................................................................23
Character Varying or Char Varying or Varchar or Varchar2 .........................................24
Character Large Object or Char Large Object or CLOB or Long Varchar.....................25
Binary Large Object String Type .............................................................................26
Binary ................................................................................................................................26
Varbinary ..........................................................................................................................27
BLOB or Long Varbinary..................................................................................................28
Numeric Type...........................................................................................................29
Exact Numeric Type ..........................................................................................................29
NUMERIC or DECIMAL or DEC or NUMBER................................................................. 30
INTEGER or INT ................................................................................................................. 31
SMALLINT .......................................................................................................................... 31
LONG or BIGINT ................................................................................................................ 32
BYTE or TINYINT .............................................................................................................. 33
Approximate Numeric Type...............................................................................................34
Float...................................................................................................................................... 34
Real....................................................................................................................................... 35
Double Precision................................................................................................................... 36
Boolean..............................................................................................................................37
Date-time Type ..................................................................................................................38
Date....................................................................................................................................... 38
Time...................................................................................................................................... 39
Time Stamp........................................................................................................................... 40
Domain Name ............................................................................. 40
Audience
This guide is intended to act as a ready reference tool for software developers building Daffodil
DB applications. This guide assumes that that you are familiar with the following concepts:
This section describes documentation syntax conventions. Syntax conventions convey specific
information on keywords and clauses in the SQL statements described in the document.
Syntax Conventions
Each SQL statement uses certain types of capitalization, formatting, and punctuation that describe
the attributes of different portions of the statement.
UPPERCASE If a portion of an SQL statement occurs in UPPERCASE, then the capitalized
words are keywords, which are usually required in the SQL statement or clause.
Keywords are not case sensitive, and they must be spelled exactly the way they
display in the document.
[] Clauses in an SQL statement that occur between [brackets] are optional. If an
optional clause has several components or keywords, they occur within brackets.
{} Curly Braces denote a choice among mandatory elements. They enclose a set of
options, separated by vertical bars ( | ). You must choose at least one of the
options.
Ellipses in an SQL statement have similar meaning as etc. It denotes that a
series of keywords, clauses, or variables that precede the ellipses can go on
indefinitely.
| Vertical bars in SQL statement separate a set of options.
(),; Parentheses and other punctuation marks are required elements. Enter them as shown
in syntax diagrams.
Daffodil DB Getting Designed to help new and intermediate Daffodil DB users navigate and
Started Guide perform common tasks like How to start and stop Daffodil DB,
Understanding key variables used by Daffodil DB, User documentation
bundled with Daffodil DB. Also briefly describes Daffodil DB Editions
and Tools
Daffodil DB System Describes the architecture of Daffodil DB and provides the information
Guide that the server administrator might need to keep Daffodil DB running
with high performance and reliability in a server framework or a multi-
user application server. Also describes the standards on which Daffodil
DB had been built, transaction capabilities and some of the unique
features supported by Daffodil DB.
Daffodil DB JDBC Explains how to use Daffodil DB and JDBC technology to develop
Reference Guide applications. It describes the basic Daffodil DB and JDBC concepts like
JDBC 3.0 features supported by Daffodil DB, how to create and access
Daffodil DB databases through JDBC API, Daffodil DB support for
JDBC and JTA and how to use Daffodil DB in a Distributed Transaction
Processing environment.
Daffodil DB Tools Explains how to use Daffodil DB Browser with Embedded as well as
Guide Server versions of Daffodil DB. Describes how to perform various
database operations on Daffodil DB using Daffodil DB Browser such as
creating a database, creating database objects, manipulating data, creating
triggers etc.
Reserved Words
Daffodil DB reserves certain keywords as Reserved Words which cannot be used, as an identifier for a table,
column, or index, or as a correlation name defined in a SELECT statement, unless you delimit them. A
delimited identifier is an identifier specified in double quotes. Any word, including keywords, can be a
delimited identifier. Daffodil DB Reserved Words are:
NOTE: Words listed here are SQL reserved words and should not be used. Some of these
keywords may not be supported in the current version, but are reserved for future versions of
Daffodil DB.
A CHAIN CONVERT
a CHAR_LENGTH COS
ABS CHARACTER_LENGTH COT
ACOS CHARACTER_SET_CAT COUNT
ALOG
ACTION COUNTRY
CHARACTER_SET_NA
ADA CURDATE
ME
ALIAS CURSOR_NAME
CHARACTER_SET_SCH
ASCII EMA CURTIME
ASENSITIVE CHARACTERISTICS CURTIMESTAMP
ASIN CHECKED D
ASSIGNMENT CLASS_ORIGIN d
ASYMMETRIC COALESCE DATABASE
ATAN COBOL DATESPAN
ATAN2 COLLATION_CATALOG DATETIME_INTERVAL
_CODE
ATOMIC COLLATION_NAME
DATETIME_INTERVAL
ATTRIBUTE COLLATION_SCHEMA
_PRECISION
AUTOINCREMENT COLUMN_NAME
DAYNAME
AVG COMMAND_FUNCTION
DAYOFMONTH
B COMMAND_FUNCTION
DAYOFWEEK
b _CODE
DAYOFYEAR
BETWEEN COMMITTED
DECODE
BIT_LENGTH CONCAT
DEFINED
BITVAR CONDITION_IDENTIFIE
R DEFINER
BOTH
CONDITION_NUMBER DEGREES
C
CONNECTION_NAME DERIVED
c
CONSTRAINT_CATALO DIFFERENCE
CALLED G DISPATCH
CARDINALITY CONSTRAINT_NAME DUMP
CATALOG_NAME CONSTRAINT_SCHEMA DYNAMIC_FUNCTION
CEILING CONTAINS
NOTE: Words listed here are SQL Non-Reserved words and can be used freely. Some of these
Non-Reserved Words may not be supported in the current version, but are reserved for future
versions of Daffodil DB.
Delimited Identifier
A delimited identifier is an identifier specified in double quotes. Any word, including keywords, can be
a delimited identifier. Enclosing a name in double quotation marks preserves the case of the name.
A reserved word can be part of an identifier, such as DEFAULT_TABLE, only to the extent when it is
not exactly the same as the keyword itself.
Syntax
<delimited identifier> ::= <double quote> <delimited identifier body>... <double quote>
<delimited identifier body> ::= <Simple Latin Letter>| <Special Characters>| <digit>
Simple Latin Letter
Simple Latin Letter is a collection of simple Latin upper case letter and a collection of simple
Latin lower case letter. It means delimited identifier can contain any alphabetic character.
Special Characters
Special Characters is a collection of special character symbols like !@#$%^&*()-=+etc. and any
digit (0-9). It means delimited identifier can contain any special character, as double quotes
delimit the meaning of these characters in the identifier.
The enclosing quotation marks are not the part of an identifier; they indicate only its beginning and
end. To include a double quotation mark character in a delimited identifier, precede it with another
double quotation mark.
Example
Valid Delimited Identifiers are:
SELECT (double quotes delimit the meaning of reserved word Select)
$1234 (double quotes delimit the meaning of special character $)
Predefined Type
These are the data types defined by Daffodil DB. They are:
Character String
Binary Large Object String
Numeric
Boolean
Date-time
Syntax
<predefined type> ::=
<character string type>
|<binary large object string type>
| <numeric type>
| Boolean
| <date-time type>
Size N.A
Maximum Size 4K
Example
CHARACTER (n) or Char (n)
where, n represents the desired length of the character string. The length parameter may take any
value from 1 to 4192. If length is not specified during the declaration, then 1 is taken by default.
Size N.A
Maximum Size 4K
Example
VARCHAR (n) or VARCHAR2 (n) or CHAR VARYING (n) or CHARACTER VARYING (n)
or VARCHAR or VARCHAR2
It can accept any length of character string up to n characters in length. The length parameter may
take any value from 1 to 4192.
Size N.A
Example
CLOB (n) or CHAR LARGE OBJECT (n) or CHARACTER LARGE OBJECT (n) or LONG
VARCHAR (n)
It can accept any length of character string up to n characters in length. The length parameter may
take any value from 1 to 1073741823. If large object length is not specified then 1073741823, is
taken by default.
Binary
The BINARY data type accepts binary strings, of a fixed length. Length of binary string should be
specified in the data type declaration.
Syntax binary[(n)]
Size N.A
Maximum Size 4K
BINARY (n)
Where, n represents desired length of the binary string. The length parameter may take any value
from 1 to 4192. If no length is specified during the declaration, 1 is taken as default length.
Size N.A
Maximum Size 4K
Example
VARBINARY (n) or VARBINARY
It can accept any length of binary string up to n characters in length. The length parameter may
take any value from 1 to 4192. If no length is specified during the declaration, the default length is
1.
Size N.A
Maximum Size 1 GB
Example
BLOB(n) or LONG VARBINAY(n)
It can accept any length of binary string up to n characters in length. The length parameter may
take any value from length 1 to 1073741823. If large object length is not specified, then
1073741823 is taken by default.
Size N.A
These data types can be declared in any one of three different ways as illustrated.below.
Examples
DECIMAL Precision defaults to 38, Scale defaults to 0
DECIMAL (p) Scale defaults to 0
DECIMAL (p, s) Precision and Scale are defined by the user
NUMERIC Precision defaults to 38, Scale defaults to 0
NUMERIC (p) Scale defaults to 0
NUMERIC (p, s) Precision and Scale are defined by the user
DEC Precision defaults to 38, Scale defaults to 0
DEC (p) Scale defaults to 0
DEC (p, s) Precision and Scale are defined by the user
NUMBER Precision defaults to 38, Scale defaults to 0
NUMBER (p) Scale defaults to 0
NUMBER (p, s) Precision and Scale are defined by the user
In the above examples, p is an integer representing precision and s is an integer representing scale.
Size 4
SMALLINT
The SMALLINT data type accepts a 16 bit signed integer value with an implied scale of zero. It
stores any integer value between the range 2^ -15 and 2^15 1 (i.e. 32768 to 32767).
Syntax smallint
Corresponding Compile-Time Java Type java.lang.Short
JDBC Metadata Type (java.sql.Types) SMALLINT
Default Value Null
Minimum Value -32768
Maximum Value 32767
Size 2
Maximum Size N.A
Examples of SMALLINT Valid Values
-32768
0
32767
The LONG or BIGINT data type can accept numeric values up to 8 bytes. It stores any integer
value between the range of 9223372036854775807 and -9223372036857447808.
Syntax long, bigint
Size 8
Size 1
Float
The FLOAT data type accepts a double precision floating point number value. If no precision is
specified during the declaration, the default precision is 15.
Syntax float[(n)]
Size 4
Maximum Size 15
Size 4
The DOUBLE PRECISION data type accepts a double precision floating point value. No
parameters are required when declaring a DOUBLE PRECISION data type.
Syntax double precision
Size 8
Size 1
Date
The DATE data type accepts date values, consisting of Year, Month, and Day. Date values
should be specified in the form YYYY-MM-DD.
Month values must be between 1 and 12.
Day values should be between 1 and 31 depending on the month and Year values should be
between 0 and 9999.
Values assigned to the DATE data type should be enclosed in single quotes, preceded by the
keyword DATE.
Syntax date
Size 10
Example
DATE '1999-04-04'.
Size N.A
Maximum Size 9
Example
TIME '07:30:00'.
Size N.A
Maximum Size 9
Example
TIMESTAMP '1999-04-04 07:30:00'.
If the values are not in the specified ranges then Daffodil DB will convert them into valid values.
Like if date is specified as 2001-12-31 then it will become 2002-01-01.
Domain Name
It is the name of the domain which represents data type with all its properties and constraints for
value. Domains are defined, mainly when same properties of the data types are required
frequently.
Literals are a type of expression that specifies a constant value (they are also called constants).
There are various types of literals like Numeric Literal, Character String Literal, and Date-Time Literal
etc.
<Literals>::=
<Character String Literal>
| <Date-Time Literal>
| <Numeric Literal>
| <Boolean Literal>
A digit is one of 0, 1, 2, 3, 4, 5, 6, 7, 8 or 9.
e or E indicates that the number is specified in scientific notation. The digits after E specify
exponent and digits before E specify mantissa.
Examples of <Rep Digit> valid values
0
22
33
Examples of <Period> <Rep Digit> valid values
23
3
Example of <Rep Digit> <period> <Rep Digit> valid values
22.22
2.33
33.3
Example of <Rep Digit> E <Rep Digit> valid values
2E3
2E34
Date Literal
Date Literal is used to specify a constant Date value in a specific format. This date value can be
used in SQL Statements and Functions.
Format for specifying a date literal is: DATE YYYY-MM-DD
Syntax
DATE <unsigned integer> <hyphen> <unsigned integer> <hyphen> <unsigned integer>
<unsigned integer>::= <Rep Digit>
<Rep Digit>::= <digit>. . .
<hyphen>::= -
Examples of valid Date Literals
DATE 2002-06-28
DATE 2001-06-28
Time Literal
Time Literal is used to specify a constant Time value in a specific format. This Time value can
be used in SQL Statements and Functions.
Format for specifying a time literal is: TIME HH:MM:SS
Syntax
TIME <unsigned integer> <colon> <unsigned integer> <colon> <unsigned integer>
<unsigned integer>::= <Rep Digit>
<Rep Digit>::= <digit>. . .
<colon>::= :
Examples of valid Time Literals
TIME 12:06:12
TIME 13:06:28
TimeStamp Literal is used to specify a constant TimeStamp value in a specific format. This
TimeStamp value can be used in SQL Statements and Functions.
Format for specifying a TimeStamp literal is: TIMESTAMP YYYY-MM-DD HH:MM:SS
Syntax
TIMESTAMP <unsigned integer> <hyphen> <unsigned integer> <hyphen> <unsigned integer>
<space> <unsigned integer> <colon> <unsigned integer> <colon> <unsigned integer>
unsigned integer>::= <Rep Digit>
<Rep Digit>::= <digit>
<colon>::= :
<space>::=
Example of valid Timestamp Literals
TIMESTAMP 2002-06-28 12:06:12
TIMESTAMP 2001-06-28 12:06:28
CC
0
25
20
20
CC
0.0
1.0
0.0
0.0
CC
0.0
-0.13235175009777303
0.9129452507276277
0.9129452507276277
Power Function
The power function is used to return value of the first argument raised to the power of the second
argument.
Syntax
POWER <left paren> <numeric expression> <comma> <numeric expression> <right paren>
If the second argument is positive or negative zero, then the result is 1.0.
If the second argument is 1.0, then the result is the same as the first argument.
Example
Select Power (ParentMarksCarryingForward, 2) as C from Exam
The above query results in a Result Set containing value of the column
ParentMarksCarryingForward raised to the power 2 under column heading C.
Result
CC
0.0
625.0
400.0
400.0
CC
0.7315948009490967
0.7320427298545837
0.7320427298545837
SQRT Function
SQRT Function calculates square root of a numeric expression passed as an argument.
Syntax
SQRT <left paren> <numeric expression> <right paren>
Numeric Expression is passed as an input to the sqrt function. The function calculates and returns
square root of the numeric expression.
Example
Select SQRT (ParentMarksCarryingForward) as C from Exam
The above query returns square root of ParentMarksCarryingForward under column heading C
in the Result Set.
Result
CC
0.0
5.0
4.47213595499958
4.47213595499958
CC
25
20
20
FLOOR Function
The Floor function returns the largest (closest to positive infinity) double the value that is not
greater than the argument and is equal to a mathematical integer.
Syntax
FLOOR <left paren> <numeric expression> <right paren>
If the argument value is already equal to a mathematical integer, then the result is the same as the
argument, it means Largest integer <= number.
Argument passed is a Numeric Expression.
Example
Select FLOOR (ParentMarksCarryingForward) as C from Exam where ParentMarksCarryForward
>0
Result
CC
25
20
20
CC
25
20
20
LOG Function
The Log function returns the natural logarithm (base e) of double the value passed as an argument.
Syntax
LOG <left paren> <numeric expression> <right paren>
If the argument is less than zero, then the result is NaN.
If the argument is positive infinity, then the result is positive infinity.
If the argument is positive zero or negative zero, then the result is negative infinity.
Argument passed is a Numeric Expression.
Example
Select LOG (-23) as C from Post
Result
CC
NaN
NaN
NaN
CC
3.1354942159291497
3.1354942159291497
3.1354942159291497
EXP Function
The EXP function returns the exponential number e (i.e., 2.718...) raised to the power of double
the value passed as an argument.
Syntax
EXP <left paren> <numeric expression> <right paren>
Exponential function of an argument passed.
Argument passed is a Numeric Expression.
Example
Select EXP (ParentMarksCarryingForward) as C from Exam where ParentMarksCarryingForward
>0
Result
C
7.200489933738588E10
4.8516519540979037E8
4.8516519540979037E8
Result
CC
1.0
-0.9912028118634736
0.40808206181339196
0.40808206181339196
TAN Function
The TAN function returns the trigonometric tangent of an angle.
Syntax
TAN <left paren> <numeric expression> <right paren>
If the argument is NaN or infinity, then the result is NaN.
Argument passed is Angle in Radians.
Example
Select TAN (ParentMarksCarryingForward) as C from Exam
The above query results in a Result Set containing trigonometric tan value of the column
ParentMarksCarryingForward under column heading C.
Result
CC
0.0
-0.13352640702153587
2.237160944224742
2.237160944224742
CC
Infinity
-7.489155308722675
0.44699510899489167
0.44699510899489167
ACOS Function
The ACOS function returns the arc cosine of an angle, in the range of 0.0 through pi.
Syntax
ACOS <left paren> <numeric expression> <right paren>
If the argument is NaN or its absolute value is greater than 1, then the result is NaN.
Parameter passed is double the value whose arc cosine is to be returned.
Function returns arc cosine of the argument.
Example
Select ACOS (ParentMarksCarryingForward) as C from Exam
The above query results in a Result Set containing trigonometric arc COS value of column
ParentMarksCarryingForward under column heading C.
Result
CC
1.5707963267948966
NaN
NaN
NaN
NaN
NaN
NaN
ATAN Function
The ATAN function returns the arc tangent of an angle, in the range of -pi/2 through pi/2, where
value of pi is 3.14
Syntax
ATAN <left paren> <numeric expression> <right paren>
If the argument is NaN or infinity, then the result is NaN.
Argument passed is double the value whose arc tangent is to be returned.
Returns arc tangent of the argument.
Example
Select ATAN (ParentMarksCarryingForward) as C from Exam
The above query results in a Result Set containing trigonometric arc tan value of the column
ParentMarksCarryingForward under column heading C.
Result
CC
0.0
1.5308176396716067
1.5208379310729538
1.5208379310729538
CC
572.9577951308232
572.9577951308232
572.9577951308232
RADIANS Function
The Radians function converts an angle measured in degrees to the equivalent angle measured in
radians.
Syntax
RADIANS <left paren> <numeric expression> <right paren>
Argument passed is an angle, in degrees.
Function returns measurement of the angle passed in radians.
Example
Select RADIANS (180) as RADIANS from Exam
Result
RADIANS
3.14159265358979323
3.14159265358979323
3.14159265358979323
3.14159265358979323
PIPI
3.141592653589793
3.141592653589793
3.141592653589793
3.141592653589793
ATAN2 Function
The ATAN2 function converts the rectangular coordinates (b, a) to polar (r, theta).
This method computes the phase theta by computing the arc tangent of a/b in the range of -pi to pi.
Syntax
ATAN2 <left paren> <numeric expression> <comma> <numeric expression> <right paren>
First Argument passed to a function is double the value, i.e. b.
Second Argument passed to a function is double the value, i.e. a.
Function returns theta component of the point (r, theta) in polar coordinates that corresponds to the
point (b, a) in Cartesian coordinates.
Example
Select ATAN2 (360, 45) as C from Exam
Result
PIC
1.446441332248135
1.446441332248135
1.446441332248135
1.446441332248135
CC
5.6715
5.6715
5.6715
SIGN Function
The Sign Function determines the sign of the numeric expression passed as an argument.
Syntax
SIGN <left paren> <numeric expression> <right paren>
Numeric Expression is passed as an argument.
If Argument passed is less than zero (number < 0) then the result is negative (-1)
If Argument passed is equal to zero (number == 0) then the result is zero (0).
If Argument passed is greater than zero (number > 0) then the result is positive (1).
Example
Select SIGN (-1) as C from Post
Result
CC
-1
-1
-1
The trunc function returns a number truncated to a certain number of decimal places.
Syntax
trunc (expression)
Examples:
DAYNAME(DateOfJoining)
WEDNESDAY
TUESDAY
FRIDAY
SUNDAY
SATURDAY
TUESDAY
TUESDAY
SUNDAY
DAYOFMONTH Function
An integer from 1 to 31 representing day of the month in a date is returned upon calling the
DAYOFMONTH function.
Syntax
DAYOFMONTH <left paren> <expression> <right paren>
Example
Select DayOfMonth (DateOfJoining) from Teacher
Result
DayOfMonth(DateOfJoining)
17
1
25
25
29
15
15
25
DayOfWeek(DateOfJoining)
4
DAYOFYEAR Function
An integer from 1 to 366 representing day of the year in a date is returned on executing the
DAYOFYEAR function.
Syntax
DAYOFYEAR <left paren> <expression> <right paren>
Example
Select DayOfYear (DateOfJoining) from Teacher
Result
DayOfYear(DateOfJoining)
108
182
268
298
241
258
258
298
Week(DateOfJoining)
16
27
39
44
35
38
44
MONTH Function
An integer from 1 to 12 representing month component of a date is returned on executing the
MONTH function.
Syntax
MONTH <left paren> <expression> <right paren>
Example
Select MONTH (DateOfJoining) from Teacher
Result
MONTH(DateOfJoining)
4
7
9
10
8
9
9
10
YEAR(DateOfJoining)
1996
1997
1998
1998
1998
1998
1998
1998
MONTHNAME Function
A character string representing month component of a date is returned on executing the
MONTHNAME function.
The name for the month is specific to the data source.
For Example Data Source is: (January, February, March, December)
Syntax
MONTHNAME <left paren> <expression> <right paren>
Example
Select MONTHNAME (DateOfJoining) from Teacher
Result
MONTHNAME(DateOfJoining)
APRIL
JULY
SEPTEMBER
OCTOBER
SEPTEMBER
OCTOBER
OCTOBER
HOUR(CURRENT_TIME)
18
18
18
18
MINUTE Function
An integer from 0 to 59 representing minute component of time is returned on executing the
MINUTE function.
Syntax
MINUTE <left paren> <expression> <right paren>
Example
Select MINUTE (CURTIME ()) from Teacher
Result
MINUTE(CURRENT_TIME)
32
32
32
32
SECOND(CURRENT_TIME)
34
34
34
34
TIMESTAMPADD Function
The TIMESTAMPADD function returns the timestamp calculated by adding count number of the
interval(s) to timestamp. An interval may be one of the following:
SQL_TSI_FRAC_SECOND, SQL_TSI_SECOND, SQL_TSI_MINUTE,
SQL_TSI_HOUR, SQL_TSI_DAY, SQL_TSI_WEEK, SQL_TSI_MONTH,
SQL_TSI_QUARTER, or SQL_TSI_YEAR
Syntax
<timestamp denometers> ::=
SQL_TSI_FRAC_SECOND
| SQL_TSI_SECOND
| SQL_TSI_MINUTE
| SQL_TSI_HOUR
| SQL_TSI_DAY
| SQL_TSI_WEEK
| SQL_TSI_MONTH
| SQL_TSI_QUARTER
| SQL_TSI_YEAR
<timestampadd function> ::=
TIMESTAMPADD <left paren> <timestamp denometers> <comma> <expression1><comma>
<expression2> <right paren>
2002-06-30 03:12:12.0
2002-06-30 03:12:12.0
2002-06-30 03:12:12.0
TIMESTAMPDIFF Function
The TIMESTAMPDIFF function returns an integer representing the number of interval by which
timestamp2 is greater than timestamp1.
Interval may be one of the following:
SQL_TSI_FRAC_SECOND, SQL_TSI_SECOND, SQL_TSI_MINUTE, SQL_TSI_HOUR,
SQL_TSI_DAY, SQL_TSI_WEEK, SQL_TSI_MONTH, SQL_TSI_QUARTER, or
SQL_TSI_YEAR
Syntax
TIMESTAMPDIFF <left paren> <timestamp denometers> <comma> <expression1> <comma>
<expression2> <right paren>
Timestamp Denometers
This argument specifies the interval of Time Stamp whose count is to be returned. For various
types of intervals, refer to the previous function.
Expression1
Expression1 represents Time Stamp, which is subtracted from the second argument. Declared data
type of an expression is TimeStamp.
Expression2
Expression2 represents Time Stamp from which first argument is subtracted. Declared data type of
an expression is TimeStamp. Return type of a function is count of the intervals.
Example
Select TIMESTAMPDIFF (SQL_TSI_SECOND, TIMESTAMP '2002-06-28 17:12:12',
TIMESTAMP '2002-05-28 7:7:7') AS "TIME DIFFERENCE IN SECONDS" from Exam
Result
-10
-10
-10
CURDATE Function
The CURDATE function returns the Current Date of an SQL Session. The declared data type of
the function is DATE.
Syntax
CURDATE <left paren> <right paren>
Example
Select CURDATE () as CURDATE from Exam
Result
CURDATE
2003-10-30
2003-10-30
2003-10-30
2003-10-30
SYS_DATE
2005-02-22 11:20:41.874
2005-02-22 11:20:41.874
2005-02-22 11:20:41.874
2005-02-22 11:20:41.874
CURTIME Function
The CURTIME function returns Current Time of an SQL Session. The declared data type of the
function is TIME.
Syntax
CURTIME <left paren> <right paren>
Example
Select CURTIME () as CURTIME from Exam
Result
CURTIME _TIME
18:32:23
18:32:23
18:32:23
18:32:23
CURTIMESTAMP
2002-06-28 17:12:46.0
2002-06-28 17:12:46.0
2002-06-28 17:12:46.0
2002-06-28 17:12:46.0
DATE Function
Date function extract date from timestamp. Argument passed to the function is timestamp and
declared data type of the function is DATE.
Syntax
DATE <left paren> <expression> <right paren>
Example
Select DATE (Timestamp 2002-06-30 12:12:12) as DateOfJoining from Teacher
Result
(DateOfJoining)
2002-06-30
2002-06-30
2002-06-30
2002-06-30
(TimeOfJoining)
17:12:12
17:12:12
17:12:12
17:12:12
TIMESTAMP Function
Syntax
TIMESTAMP(<string>, '<format>')
Following is a list of options for the format parameter. These parameters can be used in many
combinations.
Parameter Explanation
YY Year 01
MI Minutes 0-59
SS Seconds 0-59
e.g.
'MONTH' =JANUARY
'Month' = January
Examples
When a date format is used by STRING or TIMESTAMP they return part of the date/time. When
used by TRUNC, they will return the first day of the period.
Trunc Function
Syntax
If the format parameter is omitted, the trunc function will truncate the date to the nearest day.
Parameter Explanation
HH, HH12, HH24 Hour - Trunc to the beginning of the current hour
Examples
ASCII VALUE
66
69
77
83
83
LEFT MOST
Cath
John
Cath
John
Woll
Vali
Lieb
Will
Tove
Wink
RIGHT MOST
ine
ohn
the
ohn
oll
ine
big
ams
era
eld
SPACES
Replace Function
The String function Replace, replaces all the occurrences of string2 in string1 with String3.
Syntax
REPLACE <left paren> <String Expression> <comma> <String Expression> <comma> <String
Expression> <right paren>
Second String Expression is a substring in the First String Expression to be replaced with the third
String Expression.
Examples
Select replace (TeacherName,'Mr.','Shri') AS REPLACEMENT from Teacher
The above query replaces all the occurrences of String Mr. with String Shri in the
TeacherName Column of the Teacher Table.
Result
REPLACEMENT
Shri Agregado
Shri Brumfield
Ms. McKelvey
Shri Everett
Shri Verstrepen
Shri Haight
Ms. Hartenfeld
Shri Henry
REPEAT_TWO_TIMES
PrincipalPrincipal
Vice PrincipalVice Principal
TeacherTeacher
Soundex Function
The scalar function SOUNDEX returns a character string, which is data source-dependent,
representing sound of words in a string; it could be a four-digit SOUNDEX code, a phonetic
representation of each word, etc.
Syntax
SOUNDEX <left paren> <String Expression> <right paren>
Examples
Select soundex (StudentName) AS SOUNDEX_CODE from Student
The above query retrieves a four-digit code for each student name from the Student table.
Result
SOUNDEX_CODE
C365
J500
C300
J500
W400
V450
L120
W452
T160
W521
REPLACEMENT
Shri Agregado
Shri Brumfield
Shri McKelvey
Shri Everett
Shri Verstrepen
Shri Haight
Shri Hartenfeld
Shri Henry
DIFFERENCE
Syntax
CONCAT <left paren> <String Expression> <comma> <String Expression> <right paren>
First String Expression is a String in which another String needs to be concatenated.
Second String Expression is a String to be concatenated with the First String Expression.
Examples
Select concat (StudentName, 'Calera') AS "NEW NAMES" from Student
The above query retrieves student names after appending Calera with each student name from
the Student table.
Result
NEW NAMES
Catherine Calera
John Calera
Cathe Calera
John Calera
Woll Calera
Valine Calera
Liebig Calera
Williams Calera
Tovera Calera
WinkField Calera
FIND JOHN
mr. agregado
mr. brumfield
ms. mckelvey
mr. everett
mr. verstrepen
mr. haight
ms. hartenfeld
mr. henry
MR. AGREGADO
MR. BRUMFIELD
MS. MCKELVEY
MR. EVERETT
MR. VERSTREPEN
MR. HAIGHT
MS. HARTENFELD
MR. HENRY
Catherine
John
Cathe
John
Woll
Valine
Liebig
Williams
Tovera
WinkField
Catherine
John
Cathe
John
Woll
Valine
Liebig
Williams
Tovera
WinkField
CHAR VALUE
A
Length Function
The string function LENGTH returns the number of characters in a string, excluding trailing blanks.
Syntax
LENGTH <left paren> <String Expression> <right paren>
String Expression is a String for which length is to be calculated.
Examples
Select length (TeacherName) AS LENGTH from Teacher
The above query retrieves a number of characters in the teacher name column from Teacher table.
Result
LENGTH
12
13
12
11
14
SUB_STRING
STRING_EQUALITY
True
false
false
false
false
false
false
false
The dump function returns a varchar2 value that includes the datatype code, the length in
bytes, and the internal representation of the expression.
Syntax
start_position and length are optional parameters. They determine which portion
of the internal representation to display. If these parameters are omitted, the dump
function will display the entire internal representation in decimal notation.
Examples:
The initcap function sets the first character in each word to uppercase and the rest to
lowercase.
Syntax
initcap (string1)
where string1 is the string argument whose first character in each word will be
converted to uppercase and all remaining characters converted to lowercase.
Examples:
Syntax
where value can either be a number or date that will be converted to a string.
Examples
Select string (sysdate, 'Month DD, YYYY') from dual July 09, 2003
Select string (sysdate, 'FMMonth DD, YYYY') from dual July 9, 2003
Select string (sysdate, 'MON DDth, YYYY') from dual JUL 09TH, 2003
Select string (sysdate, 'FMMON DDth, YYYY') from dual 'JUL 9TH, 2003
The trim function removes all specified characters either from the beginning or the ending
of a string.
Syntax
If none of these are chosen (i.e. leading, trailing & both), the trim function will remove
trim_string from both the beginning and end of string1.
Examples:
DATABASE NAME
school
school
school
school
User()
daffodil
daffodil
daffodil
daffodil
POST_NAMES
Principal
VicePrincipal
Teacher
NULLIF function
The NULLIF function compares two values and does the following.
Syntax
Example:
The query below will return null, if the ExamID column is equal to the StudentID column
for a Student.
Syntax
default is optional. If no matches are found, the decode function will return
default. If default is omitted, then the decode statement will return null (if
no matches are found).
For Example:
Select StudentName,
decode (StudentID, 100, 'FIRST',
101, 'SECOND', 102, 'THIRD', 'PASS') result from Student
The above query will return the student name with his position in the class. If the student
ID doesn't match with the cases in the query, PASS will be the output.
The query stated above is another form of SELECT queries, where we have used TOP function to
list the top 5 students from the list. To display implementation of the mathematical expression in
SELECT statement, we have calculated the percentage taking maximum marks as 500. Alsothe
column aliasing has been used in the query, where first column has been renamed to Percentage.
COUNT(*)
3
Result of the query mentioned above is simply count of the record in the Table Post.
Avg
AVG is an Aggregate function used to calculate average of the values corresponding to a column
specified as its argument.
SELECT AVG (ABS (marks)) AS AVERAGE FROM MarksRecord GROUP BY ExamID
Result
AVERAGE
79.91666..
SUM(marks*2)
956
In the above example, result will be sum of all the marks multiplied by 2 corresponding to the
student whose StudentId is 5.
Max/Min
MAX is an Aggregate function that finds the maximum value among all the available values
corresponding to a column specified as its argument. On the contrary, MIN is an aggregate
function that selects minimum value among all the available values corresponding to a column
specified as its argument.
All aggregate functions except COUNT (*) and GROUPING ignore nulls. COUNT never returns
Null, returns either a number or zero. For all the remaining aggregate functions, if data set
contains no rows, or contains only rows with nulls as arguments to the aggregate function, then the
function returns NULL. Nesting of Aggregate functions is also possible. For example, the
following example calculates the average of the maximum marks of all the Exams held.
MAX(marks)
99
In the above example, result will be Maximum marks in all the exams except that for which
ExamID is 5.
User Defined Functions works simply as a value expression. So where ever a value expression
comes, UDF can be made use of.
User Defined Functions are similar to procedures and views and can accept an input, perform
some work, and then return some value as output. Then what are the major advantages of a UDF
compared to views and procedures?
Stored procedures can't be part of a SELECT statement, except to set a variable. A User
Defined Function can. You can include it right there in the SELECT statement just like a
column.
In addition, a main benefit is the numerous places that a User Defined Function fits. You
can break out complex work into reusable segments; then the developers or end users can
get at the resulting recordset without having to know all that logic. This also allows you to
create object-style databases, so that the User Defined Function can change and the calling
code doesn't have to.
One of the most powerful tools in programming is recursion. Recursion is similar to a loop, with
has one major difference. A loop sets up a condition and then executes a block of code until the
condition is met. In contrast, recursion calls itself a number of times, using answers that it
provides as an input. Daffodil DB supports recursion in both UDF and procedures.
Syntax
<SQL-invoked Function> ::= CREATE FUNCTION <routine name> <SQL parameter declaration
list> <return clause> <routine characteristics> <routine body>
<SQL parameter declaration list> ::= <left paren> [ <SQL parameter declaration> [ { <comma>
<SQL parameter declaration> }... ] ] <right paren>
<SQL parameter declaration> ::= [ <parameter mode> ] [ <SQL parameter name> ] <parameter
type>
Numeric Expression
Numeric Expression is a type of expression that can be used to perform numeric operations.
Boolean Expression
Boolean Expression is a type of expression that returns a Boolean value. Boolean Precedence is to
be applied properly while solving any Boolean Expression.
String Expression
String Expression represents a set of characters. Two String Expressions can be joined together
through concatenation operator.
Expression Primary
Expression Primary can either be a SubQuery, Constant, Column Reference, Multi-Valued
Expression or a Parenthesized Expression.
Expression Precedence
Precedence of operations from highest to lowest is:
(), ?,
unary + and -
*, /, || (concatenation)
binary + and -
NOT
AND
OR
?: (Conditional)
You can explicitly specify precedence by placing expressions within parentheses. An expression
within parentheses is evaluated before any operations outside the parentheses are applied to it.
Numeric Expression
Numeric Expression is any kind of valid expression that contains plus sign, minus sign, asterisk
and/or solidus in between two Numeric Expressions or it could be a simple factor. Numeric
Expression is used to perform arithmetic operations. A valid plus or a minus sign can also be
applied in a valid Numeric Expression. All the Numeric Expression will be evaluated by applying
the proper Expression Precedence as mentioned above.
Syntax
<Numeric Expression> ::=
<term>
| <Numeric Expression> <minus sign> <term>
| <Numeric Expression> <plus sign> <term>
<term> ::=
<factor>
| <term> <asterisk> <factor>
| <term> <solidus> <factor>
<factor> ::=
[ <sign> ] <Numeric primary>
<Numeric Primary> ::=
<Expression Primary>
<Numeric Functions>
| <Date Time Functions>
<sign> ::= <plus sign> | <minus sign>
<plus sign> ::= +
<minus sign> ::= -
<asterisk> ::= *
<solidus> ::= /
2 Vice Principal 2
3 Teacher 3
Example 2
Select * from post where TRUE
Here in the above example simply TRUE is also an example of valid Boolean Expression.
Result
1 Principal 1
2 Vice Principal 2
3 Teacher 3
name
Mr. Principal
Mr. Vice Principal
Mr. Teacher
Example 2
Select DAYNAME (Date '2002-12-24') as "Day Name" from Post
Result
DAYNAME
Tuesday
Arithmetic is performed so as to maintain integrity of the datetime data type that is the result of
datetime term or datetime expression. Daffodil DB also supports Addition/Subtraction using (+)
and () operator in Date and Timestamp data types.
Syntax
a - 30
-----
2003-08-04
1 row(s) selected
b - 30
-----
2003-07-04 11:01:11.0
1 row(s) selected
a + 20
-----
2003-09-23
1 row(s) selected
20 + a
-----
2003-09-23
1 row(s) selected
b + 20
-----
2003-08-23 11:01:11.0
1 row(s) selected
Table SubQuery
Row SubQuery
Scalar SubQuery
Degree
Degree refers to the number of records that are resulted from a Query.
Cardinality
Cardinality refers to the number of columns that are selected in a Query.
Table SubQuery
Table SubQuery is the one for which both degree and cardinality can be greater than or equal to 0
Row SubQuery
Row SubQuery is the one for which degree is 1 while cardinality can be greater than or equal to 0.
Scalar SubQuery
Scalar SubQuery is the one for which both degree and cardinality are 1.
Example 1
Select schoolName from School where Exists (Select schoolID, schoolName from Classes where
schoolID > 0)
In the above query, the inner query will be an example of Table SubQuery if it returns more than a
single record for the studentID.
Result
schoolName
EmailAddress
info@arthuormorganschool.org
Example 3
Select PhoneNumber from School where Exists (Select Distinct schoolID from Classes where
schoolID > 0)
In the above query, inner query will be an example of Scalar SubQuery, if it returns a single record
for the studentID.
Result
PhoneNumber
1-828-875-4262
PostID
1
2
3
Example 2
Select a.postID from post a
In the above example a.postId is also an example of Column Reference.
dshjh^&*%or SELECT is an example of valid delimited identifier.
Result
PostID
2
3
Parenthesized Expression
A Parenthesized Expression is simply an expression enclosed with left and right parenthesis.
Syntax
<Parenthesized Expression> ::= <left paren> <Expression> <right paren>
Example
(a * b + c / d) is a valid parenthesized expression.
Comparison Predicate
The COMPARISON predicate compares two values and returns TRUE or FALSE depending on
whether the two values have been compared successfully or not.
Syntax:
<comparison predicate> ::=
<Expression1> <comp op> <Expression2>
<Expression1> ::= <Expression>
<Expression2> ::= <Expression>
<comp op> ::=
<equals operator>
| <not equals operator>
| <less than operator>
| <greater than operator>
| <less than or equals operator>
| <greater than or equals operator>
Expression
An expression can be one of the following:
LITERAL - quoted string, numeric value, datetime value.
FUNCTION CALL - reference to a built-in SQL function.
SYSTEM VALUE - Current date, Current user.
NUMERIC, BOOLEAN or STRING Expression - Combining Sub Expressions using Operators.
Expression1 and Expression2 further define an Expression. Talking Multi-Valued COMPARISON
PREDICATE means an expression of the following type.
(ExpressionA1. . . ExpressionAN) <comp op> (ExpressionB1. . . ExpressionBN)
Here ExpressionA1 will be compared with ExpressionB1, ExpressionA2 will be compared with
ExpressionB2,. . . and so on ExpressionAN will be compared with ExpressionBN.
<> Not Equal to Returns TRUE, if first value is not equal to the second value
< Less Than Returns TRUE, if first value is less than the second value.
> Greater Than Returns TRUE, if first value is greater than the second value.
<= Less Than or Returns TRUE, if first value is less than or equal to the second
Equal to value
>= Greater than or Returns TRUE, if first value is greater than or equal to the second
Equal to value.
Example
Let us take the following examples that are using comparison predicates where results (TRUE,
FALSE) are based on the values of the column,
SchoolID = 1 and StudentID <= 2 evaluates to TRUE if SchoolID is 1 and StudentID is less than
or equal to 2.
Select School.PhoneNumber, Student.StudentID, Student.StudentName, ClassID from School,
Student where SchoolID = 1 and StudentID <= 2
will return TRUE for all the records for which SchoolID is 1 and StudentID of the Students
belonging to that school have value less than or equal to 2.
Result
1-828-675-4262 1 Catherine 1
1-828-675-4262 2 John 1
info@arthurmorganschool.org 5 Wool
Between
BETWEEN operates on three expressions. The expression1s value is checked for comparison in
the range of expression2 and expression3.
Symmetric
When SYMMETRIC is specified, then the boundary values of the range of expression2 and
expression3 are not taken into account when the expression1s value is checked for any match in
the specified range.
Asymmetric
When ASYMMETRIC is specified, then the boundary values of the range of expression2 and
expression3 are also taken into account when the expression1s value is checked for any match in
the specified range.
For both BETWEEN and NOT BETWEEN, ASYMMETRIC is default.
Not Between
Not Between operates again on the three expressions. But, now the expression1s value is
checked for comparison outside the range of the expression2 and expression3.
98 1 1 1
87 1 2 1
99 1 3 1
78 1 4 1
52 1 5 1
77 1 6 1
98 1 1 1
87 1 2 1
99 1 3 1
78 1 4 1
52 1 5 1
77 1 6 1
StudentID
Example 2
Select studentName from student where studentName like '%a%e'
On executing the above query, all studentNames will be selected from Students that contain a
and ends with e like Catherine, Cathe, and Valine.
StudentName
Catherine
Cathe
Valine
Exists Predicate
This quantified operator verifies the existence of rows. The Boolean result of an EXISTS the
number of rows returned by the SubQuery determines predicate.
For EXISTS, the Boolean result is TRUE if SubQuery returns at least one row and FALSE if
SubQuery does not return any row.
Syntax
<exists predicate> ::= EXISTS <table subquery>
<table subquery> ::= <subquery>
<subquery> ::= <left paren> <query expression> <right paren>
Here EXISTS is a keyword that checks the existence of records in the query referred to by <table
subquery>.
Table SubQuery
Table SubQuery is a SubQuery listed in the Parent Query and succeeds the keyword EXISTS.
EXISTS
As explained above, EXISTS returns TRUE if the SubQuery returns at least one row, otherwise
FALSE is returned.
Examples
Select * from Marksrecord where EXISTS (select examID from Exam where examID = 3)
In the above query, if the result of the inner SubQuery comes out with the number of records more
than 0 then all EXISTS Predicate will return true and all records of the Marksrecord table will be
displayed.
Result
98 1 1 1
87 1 2 1
99 1 3 1
78 1 4 1
52 1 5 1
. ..
Mr. 2 1966-07-27
Brumfield
1 Prose 2 3 1
2 Prose 2 2 6
3 Prose 2 2 6
4 Botany 1 1 8
5 Zoology 1 2 8
20 Fundamentals 6 3 5
21 Memory 6 2 5
22 Basic 6 1 5
1 Prose 2 3 1
2 Prose 2 2 6
3 Prose 2 2 6
4 Botany 1 1 8
5 Zoology 1 2 8
. .. .. ..
The above table shows the first five results that satisfy the query.
Example 3
Select * from ClassProperties where owed ted < ANY (select __rowId from Subject where
subjectName <> Computers)
All the records from ClassProperties will be selected for which SubjectId is greater than any
owed selected by a SubQuery.
Result
Above result shows first five records, which satisfy the given query.
Syntax
columnorindexname - is the name of a specific column or name of a full-text index. Name of the
index is used when index is created on more than one column.
search expression is the search criterion containing words, phrases and logical NOT, AND, OR
operators.
word - is a string of characters without spaces.
phrase - is one or more words with spaces between each word.
Full-text index can be created by the following syntax:
CREATE FULLTEXT INDEX <full-text index name> ON <table name><on column>
<on column> ::= <left paren> <column name list> <right paren>
full-text index name user defined full text index name.
table name name of the table, which is required to be full text enabled.
column name list name of the column(s) on which full text index is to be created.
Example 1. The following query retrieves names of the students living in New York, from the
Student table.
SELECT StudentName FROM student where contains (StudentAddress,"NY")
Result
StudentName
Cathe
Tovera
Example 2. The following query retrieves names of the students from the Student table having
Palace or Park in their address field.
SELECT StudentName FROM student where contains (StudentAddress,"Palace" | "Park")
Result
StudentID StudentName
2 John
3 Cathe
8 Williams
Example 3. The following query retrieves names of the students from the Student table living near
Airport in Columbia.
SELECT StudentName FROM student where contains (StudentAddress,"AirPort" | "Columbia")
Result
StudentName
Liebig
Example 4. The following query retrieves names of the students from the Student table not living
in New York and NewZelands.
SELECT studentID, StudentName FROM student where contains (StudentAddress, Not ("NJ" |
"NY"))
Result
StudentID StudentName
1 Catherine
2 John
4 John
5 Woll
7 Liebig
8 Williams
10 WinkField
CREATE Database
Syntax
CREATE DATABASE <database name> [ FILESIZE <equals operator> <large object length> ]
[ FILEGROWTH <equals operator> <unsigned integer> ]
[ UNICODE SUPPORT <truth value> ]
[ USER <user name> PASSWORD <password name> ]
<large object length> ::= <unsigned integer> | <unsigned integer> <multiplier>
| <large object length token>
<truth value>::= True | False
database name
It is the name of the database being created.
Examples
This will create a database called ANSII for USER ANSII with the FILESIZE = 6m,
FILEGROWTH = 12 and UNICODESUPPORT = TRUE.
DROP Database
Syntax
DROP DATABASE <database name> USER <user name> PASSWORD <password name>
Database name
It is the name of the database, which needs to be dropped. For <database name>, any existing
database name can be used.
USER <user name >
The value for this parameter specifies the name of the user connecting to the database. There is no
default value for this parameter.
The value for this parameter specifies user password for connecting to the database. There is no
default value for this parameter.
Examples
This will drop the database called ANSII for USER ANSII.
Note: - No default value for USERNAME. If USERNAME is not specified, then an SQL Exception
will occur.
This includes:
Column Name
Column name is the name of the column structure within a table created with CREATE TABLE
statement. Column names must conform to the rules for identifiers and it must be unique in a
table.
Data type
The data type describes the type of data that can be stored in the column.
Match Types
MATCH FULL
Match Full specifies that for each row R1 of the referencing table, either the value of every
referencing column in R1 shall be a null value, or the value of every referencing column in R1
shall not be null and there shall be some row R2 of the referenced table such that the value of each
referencing column in R1 is equal to the value of the corresponding referenced column in R2.
On delete clause
The ON DELETE clause defines the rules for deleting specific columns on the specified table.
On update clause
The ON UPDATE clause defines the rules for updating specific columns on the specified table.
If the ON DELETE or ON UPDATE clauses are omitted, the default is NO ACTION.
Referential action
With column constraints you must specify at least one identifier. These are:
CASCADE- has the effect of dropping all SQL objects that are dependent on a particular object.
SET NULL- assigns null values to all components of the target column.
SET DEFAULT- assigns default values to all the components of the target column.
RESTRICT- takes care of what objects are dependent on the object being dropped and if there are
dependent objects, then the dropping of the object does not take place.
NO ACTION omits the ON DELETE clause.
Check constraint
The check constraint defines an explicitly named check constraint of one or more columns.
Syntax
CREATE SEQUENCE <local or schema qualified name>
[<initialize sequence> [<initialize sequence>...]]
<initialize sequence>::-
<sequence starter> <suinteger>
| <sequence type>
<sequence starter>:-
INCREMENT BY
| START WITH
<sequence type>:-
<maxvalue sequence>
| <minvalue sequence>
| <cycle in sequence>
<maxvalue sequence>:-
MAXVALUE <suinteger>
| NOMAXVALUE
<minvalue sequence>:-
MINVALUE <suinteger>
| NOMINVALUE
<cycle in sequence> ::=
CYCLE
| NOCYCLE
INCREMENT BY
This clause specifies the interval between sequence numbers. This integer value can be any
positive or negative integer, but it cannot be 0. The absolute of this value must be less than the
difference of MAXVALUE and MINVALUE. If this value is negative, then the sequence
descends. If the increment is positive, then the sequence ascends. If you omit this clause, the
default value of the interval becomes 1.
START WITH
This clause specifies the first sequence number to be generated. Use this clause to start an
ascending sequence at a value greater than its minimum or to start a descending sequence at a
value less than its maximum. For ascending sequences, the default value is the minimum value of
the sequence. For descending sequences, the default value is the maximum value of the sequence.
Note: - This value is not necessarily the value to which an ascending cycling sequence cycles after
reaching its maximum or minimum value.
CYCLE IN SEQUENCE
CYCLE
Specifying CYCLE will indicate that the sequence continues to generate values after reaching
either its maximum or minimum value. After an ascending sequence reaches its maximum value, it
generates its minimum value. After a descending sequence reaches its minimum, it generates its
maximum value.
NOCYCLE
Specifying NOCYCLE will indicate that the sequence cannot generate more values after reaching
its maximum or minimum value. This is the default value.
Example
CREATE SEQUENCE orders_seq
START WITH 1000
INCREMENT BY 1
NOCYCLE
This will create the sequence orders_seq in the default schema. This sequence provides numbers
when orders_seq.NEXTVAL or orders_seq.CURRENTVAL is called from any statement.
The first reference to orders_seq.nextval returns 1000. The second returns 1001. Each subsequent
reference will return a value 1 greater than the previous reference.
If you specify none of the following clauses, you create an ascending sequence that starts with 1
and increases by 1 with default upper limit. Specifying INCREMENT BY -1 only creates a
descending sequence that starts with -1 and decreases with no lower limit.
To create a sequence that increment without bound, for ascending sequences, omit the
MAXVALUE parameter or specify NOMAXVALUE. For descending sequences, omit
the MINVALUE parameter or specify the NOMINVALUE.
To create a sequence that stops at a predefined limit, for an ascending sequence, specify a
value for the MAXVALUE parameter. For a descending sequence, specify a value for the
MINVALUE parameter. Also specify the NOCYCLE. Any attempt to generate a sequence
number once the sequence has reached its limit results in an error.
To create a sequence that restarts after reaching a predefined limit, specify values for both
the MAXVALUE and MINVALUE parameters. Also specify the CYCLE. If you do not
specify MINVALUE, then it defaults value is 1).
Syntax
<maxvalue sequence>:-
MAXVALUE <suinteger>
| NOMAXVALUE
<minvalue sequence>:-
MINVALUE <suinteger>
| NOMINVALUE
<cycle in sequence> ::=
CYCLE
| NOCYCLE
MAXVALUE SEQUENCE
MAXVALUE
It specifies the maximum value, the sequence can generate.. MAXVALUE must be equal to or
greater than START WITH and must be greater than MINVALUE.
NOMAXVALUE
Specifying NOMAXVALUE indicates a maximum value of 9223372036854775807.
MINVALUE SEQUENCE
MINVALUE
It specifies the minimum value of the sequence. MINVALUE must be less than or equal to
START WITH and must be less than MAXVALUE.
NOMINVALUE
Specifyig NOMINVALUE indicates a minimum value of -9223372036857447808.
DROP Sequence
To drop a sequence use the SQL command DROP SEQUENCE.
Syntax
DROP SEQUENCE <local or schema qualified name>
<local or schema qualified name>
It is the name of the sequence to be dropped. For <local or schema qualified name> you may use
an existing sequence name.
Example
DROP SEQUENCE orders_seq
Example 2
Example 3
This example retrieves the Marks of the student for the StudentId passed.
CREATE PROCEDURE Procedure_Name (OUT var1 int, IN var2 Boolean, INOUT var3 int)
specific Specfic_Procedure_Name EXTERNAL
NAME Jar_Name:java.sql.Connection::SQLConnect(Javaparameter, Boolean, javaparameter);
Example-2
CREATE PROCEDURE Procedure_Name (IN a int, IN b Boolean) specific
Specfic_Procedure_Name EXTERNAL NAME Jar_Name:Connection::displayData (Integer,
Boolean)
Example-3
CREATE PROCEDURE Procedure_Name() specific Specfic_Procedure_Name EXTERNAL
NAME com.java.sql.Connection::setUrl()
Example-4
CREATE PROCEDURE Procedure_Name() specific Specfic_Procedure_Name EXTERNAL
NAME Statement::CreateStatement ()
Following are the types of statements that can be used in the body of the procedure:
1) Assignment statement: It is used for assigning values.
Syntax:
SET <assignment target> <equals operator> <assignment source>
<assignment target> ::= <target specification>
| <modified field reference>
| <mutator reference>
Example:
Set a = 1
3) Case statement: It is used to perform some action depending on the set of conditions. It is
also used to replace multiple if statements.
Syntax :
<case statement> ::= <simple case statement> | <searched case statement>
<simple case statement>::=
CASE <simple case operand 1>
<simple case statement when clause>...
[<case statement else clause>]
END CASE
<simple case operand 1> ::= <value expression>
<value expression> ::= <value expression primary>
| <row value constructor> | <value specification>
| <boolean value expression> | <datetime value expression>
| <string value expression> |<numeric value expression>
<simple case statement when clause> ::=
WHEN <simple case operand 2>
THEN <SQL statement list>
<case statement else clause> ::= ELSE <SQL statement list>
<searched case statement> ::=
CASE
<searched case statement when clause>... [<case statement else clause>]
END CASE
Example :
Case rollno
When 101 then insert into student(name) values('daisy');
When 102 then insert into student(name) values('sanya');
Else
insert into student (name) values ('john');
End case;
5) Iterate statement: This statement is used within a loop. When this statement is encountered,
control is transferred to the beginning of the loop.
Syntax :
<iterate statement> ::= ITERATE <statement label>
Example:
create procedure proc4() specific sproc4
as begin
begin
declare aa int;
set aa = 2;
lab :
repeat
if aa in (22,24,26,28,10) then
set aa = aa+3;
iterate lab;
else insert into school(schoolid,schoolname) values(aa,'a');
end if;
set aa = aa+3;
until aa>=10
end repeat;
end;
end;
Note: - In the above case, body of while loop will be executed 4 times, after that control will
exit of while loop (when a =5, condition will be true)
Example :
LOOP
Set a=1;
Set a=a+1;
END LOOP
Above shown is an infinite loop.
8) While statement :It is used to execute a group of statements repeatedly as long as search condition
is true.
Syntax:
<while statement> ::= [<beginning label> <colon>]
WHILE <search condition> DO
<SQL statement list>
END WHILE [<ending label>]
10) For Statement: For statement is another looping statement supported by Daffodil DB. Here the
loop will continue to execute unless and until the condition based on the cursor is met. For
statement is used as cursors. In for statement users need not externally open or close the cursor as
it internally handle the opening and closing of the cursor. Also Alias can be used in FOR statement
instead of FOR loop variable lists.
Syntax:
(This example will select studentid, studentname from table student where studentid >10 as alias
alias1 and insert alias1 values into columns employeeid,teachername of table teacher)
Example 2:
DECLARE id int;
DECLARE name varchar(20);
FOR id, name AS cursorTEMP SENSITIVE cursor for
select studentid, studentname from student where studentid>10
DO
Insert into teacher (employeeid,teachername) values (id,name);
END FOR;
(This example will select studentid, studentname from table student where studentid >10 into variables
id,name and insert values into columns employeeid,teachername of table teacher. Here cursor name is
cursorTEMP1 and sensitivity= sensitive)
Cursor
Operations in a relational database act on a complete set of rows. The set of rows returned by a
SELECT statement consists of all the rows that satisfy the conditions in the WHERE clause of the
statement. This complete set of rows returned by the statement is known as the Result Set.
Applications, especially interactive online applications, cannot always work effectively with the
entire Result Set as a unit. These applications need a mechanism to work with one row or a small
block of rows at a time. Cursors are a logical extension to Result Sets that let applications work with
the Result Set, row by row.
Syntax
If <cursor sensitivity > is not specified, then ASENSITIVE is implicit, otherwise cursor is
sensitive if SENSITIVE is specified, insensitive if INSENSITIVE is specified and asensitive if
ASENSITIVE is specified explicitly.
If an <updatability clause> of FOR UPDATE with or without a <column name list> is specified,
then INSENSITIVE shall not be specified and QE shall become updatable.
If WITH HOLD is specified, then the cursor specified by the <cursor specification> is said to be
a holdable cursor.
If WITH RETURN is specified, then the cursor specified by the <cursor specification> is said to
be a result set cursor.
Note: - In the example given above, a cursor named cursoremp is used to increment the salary of
all employees from department with department code 1 and to insert the incremented amount in
another table named emp_raise.
Syntax
[< beginning label > <colon>] FOR {<For loop variable name>...} AS [<cursor name> [<cursor
sensitivity>] CURSOR
FOR] <cursor specification> DO <SQL Statement List> END FOR [<Ending Label>] <semicolon>
<cursor sensitivity> ::= SENSITIVE | INSENSITIVE | ASENSITIVE
<cursor specification> ::= <query expression> [<order by clause>] [<updatability clause>]
<SQL Statement List> ::= {<SQL procedure statement>...}
<SQL procedure statement>::= <SQL Statements>
Example
Domain
A domain is a set of permissible values. A domain is defined in a schema and is identified by a
<domain name>. The purpose of a domain is to constraint the set of valid values that can be stored
in a column of a base table by various operations.
Syntax
<domain definition> ::= CREATE DOMAIN <domain name> [ AS ] <data type> [ <default
clause> ]
[ <domain constraint>... ]
<domain constraint> ::= [ <constraint name definition> ] <check constraint definition> [
<constraint characteristics> ]
Domain name
It is the name of the domain to be created.
Data Type
The data type description of the data type of the domain.
Default clause
Default Clause is used to define a default value for the domain.
Domain constraints
Domain constraint is a constraint that is specified for a domain. It is applied to all columns that are
based on that domain, and to all values directed to that domain.
Example
CREATE DOMAIN intdom as Integer check (value > 100)
This domain will have integer values with a constraint that the values should be greater than 100.
Suppose that the database already have a user cathe and have established connection with the database
with user name cathe and password cathe. Now the user can change the password by the following
statement:
Table
It is the name of the table on which index to be deleted was created.
Example
DROP INDEX TeacherNameIndex1 OF Teacher.
Above Example deletes the index TeacherNameIndex1 on table Teacher.
Table
It is the name of the table on which the FullText index to be deleted was created.
Example
DROP FULLTEXT INDEX TeacherNameIndex1 OF Teacher.
Above Example deletes the FullText index TeacherNameIndex1 on the table Teacher.
Schema - A schema is a logical grouping of tables, indexes, triggers, routines, and other
data objects under one qualifying name.
Syntax
DROP SCHEMA <schema name> <drop behavior>
<Drop behavior> ::= CASCADE
| RESTRICT
Schema name
The schema name refers to the unique name of the schema.
Drop behavior
If RESTRICT is specified, and if there are any tables or SQL routines or etc. in the schema name,
then the schema is not dropped and neither are the tables in the SQL routines. With CASCADE,
all tables, indexes, columns, constraints, triggers, and SQL routines etc. that are associated with
schema name are dropped along with the schema. RESTRICT is by default.
Example
Drop Schema SampleDatabaseSchema cascade
This is used to drop the schema SampleDatabaseSchema.
BEGIN
DECLARE
END;
Every unit of PSM must constitute a block. As a minimum there must be the delimiting words
BEGIN and END around the executable statements.
SELECT statements within PSM blocks are embedded SQL (an ANSI category). As such they
must return one row only. SELECT statements that return no rows or more than one row will
generate an error(but not in case of cursor). If you want to deal with groups of rows you must
place the returned data into a cursor. The INTO clause is mandatory for SELECT statements
within PSM blocks (which are not within a cursor definition), you must store the returned values
from a SELECT.
If PSM variables or objects are defined for use in a block then you must also have a DECLARE
section.
PSM blocks may be nested, nesting can occur wherever an executable statement could be placed
(including the declare section).
FOR LOOP statements can be used to nest PSM blocks. Daffodil DB also provides support for
accessing cursor columns in FOR LOOP statement using single variable. For learning more on
this, refer Cursor section.
Insert Statement
An INSERT statement creates a row or rows and stores them in the named table. The number of values
assigned in an INSERT statement must be the same as the number of specified or implied columns.
Syntax
INSERT INTO <insertion target> <insert columns and source>
<insertion target> ::=<table name> <insert columns and source> ::=<from subquery><from
constructor><from default>
<from subquery> ::= [ <left paren> <insert column list> <right paren> ] <query expression>
<from constructor> ::= [ <left paren> <insert column list> <right paren> ] <contextually typed
table value constructor>
<from default> ::= DEFAULT VALUES
<insert column list> ::= <column name list>
<contextually typed table value constructor> ::= VALUES <left paren> <Expression> [ {
<comma> <Expression> }] <right paren>
Table name
Table name is the name of a table in which the row will be inserted.
Insert Column list
Is a list of one or more columns in which data is to be inserted. Column list must be enclosed in
parentheses and delimited by commas. If a column is not in column list, Daffodil DB automatically
provides a value for the column if the column has a default value. If column list is specified then the
values inserted through the use of constructor or the SubQuery should come in the same order.
Contextually Type Value Constructor
Value Constructor specifies column values to be inserted in a table. There are two ways with
which we can specify column values to be inserted in a column. We can specify values for a
record of table or we can specify values for multiple records of a table like:
Values ( 1, 2,sapling), specify 1, 2 and sapling as the single record values. In this,
cardinality (i.e. no of columns) is 3.
Values ((1, 2,sapling), (2, 3,daffodil), (3, 4,transport)), specify values for 3 records.
In this, cardinality is 3.
Insert Columns and Source
There are 3 sources from which we can put values in the table through insert query.
From SubQuery
You can use the output from a SubQuery to insert values into the table specified by insertion
target. The following Constraints are applied
From SubQuery includes Insert Column List as an Optional Rule. It means value of this rule can
be null or not null.
This example is used to delete records from MarksRecord table where StudentID is 1 and
StudentID is same as StudentID in Student table.
DELETE FROM MarksRecord m where StudentID =1 and exists(Select StudentID from Student
s where s.StudentID=m.StudentID)
Select Statement
The SELECT Statement is a DQL (Data Query Language). It queries the database and retrieves
rows from the database, thus allowing the selection of one or many rows or columns from one or
many tables.
Syntax
SELECT [ <set quantifier> ] [ <top function> ] <select list> <table expression>
<set quantifier> ::= DISTINCT | ALL
<select list> ::= <select sublist> [ { <comma> <select sublist> }... ]
<table expression> ::=
<from clause>
[ <where clause> ]
[ <group by clause> ]
[ <having clause> ]
[ <order by clause> ]
<top function> ::= TOP <left paren> <unsigned integer> <right paren>
Select List
<select sublist> ::=<derived column> | <qualified asterisk>
<qualified asterisk> ::= <asterisk> | <asterisked identifier chain> <period> <asterisk>
<asterisked identifier chain> ::=<asterisked identifier> [ { <period> <asteriskedidentifier> }... ]
<asterisked identifier> ::= <identifier>
<derived column> ::=<Expression> [ <as clause> ]
<as clause> ::= [ AS ] <column name>
Distinct/All
These are the optional set quantifiers. DISTINCT specifies the discarding of the duplicate records
when the two or more records in the selected columns are same. ALL, on the contrary returns all
the records including the duplicate records.
TOP Function
The TOP Function displays the top n records from the result set, where n is the argument
passed to the function.
simply an asterisk, * , to select all the columns of the table in the FROM clause.
specific fields names to select selected columns.
some expression using the aggregate functions or some operator, etc.
Table expression
Table Expression lists the source of the tables from which the columns specified in the <select
list> are to be retrieved as well as the conditions that are to be applied over them. Table
Expression can be formed of the various clauses as indicated i.e. FROM clause that is mandatory
and WHERE clause, GROUP BY clause, HAVING clause and ORDER BY clause that are
optional. These clauses will be explained in detail later.
Example 1
Select * from Subject
SubjectID SubjectName
1 Biology
2 English
3 Mathematics
4 Science
5 Social Studies
The above query lists all the records from the Subject table. This is specified by the asterisk, *,
which is used to select all the rows from the table specified. Here the quantifier is by default ALL.
This means all the records, irrespective of whether there are any redundant records, will be
displayed. The above result shows the first 5 rows.
Example 2
To specify explicitly, the listing of all the records, ALL can be used as shown, which is otherwise
same as the query above.
Select all * from Subject
Example 3
To remove the duplicate records the keyword DISTINCT is used as shown below, which will
again list all the records of the Subject Table, but this time after dropping the duplicates.
Select distinct * from Subject
SubjectID SubjectName
1 Biology
2 English
3 Mathematics
4 Science
5 Social Studies
Here only the first five records of the query result have been shown.
Table or query name: includes name of the table from which we want to retrieve the data.We can
specify the name of table with its schema name or without schema name. If no schema name is
specified then ,the current schema is assumed.
Joined Table
It specifies the intermediate result table that is the result of either equi-join or an outer join. The
operators that could be applied are: CROSS JOIN, LEFT OUTER JOIN, RIGHT OUTER
JOIN, and FULL OUTER JOIN.
Joined Condition
It defines a search condition in which predicates can be combined.
This query, which is the simplest of all, lists the Name of the Exam, Maximum Marks for the
exam and the passing marks of the Exam as the output. We can also select more than one table
from in the Table Reference List, the example for which is listed next
Select t.TeacherName,t.DateOfJoining,t.salary,p.PostID
From Teacher as t, Post as p
Result
The result shows the first four rows of the result only.
The above query takes two tables in the from clause, but it is inefficient in the way that it lists out
all the records of the tables, i.e. displays the Cartesian Product of the two tables, which is not what
the user wants always. Here, though, only the first four records have been shown. The p.PostId
field shows the Cartesian product being carried out in the operation. This type of operations,
involving more than one table, need to be controlled. The next example shows exactly this, by
forcing the condition in the where clause.
select t.TeacherName, t.DateOfJoining, t.salary, p.PostID
from Teacher as t, Post as p
where t.PostID = p.PostID
Result
This is the basic query for the cross join. Since the classes table consists of 3 entries and the exam
table consists of 4 entries, the cross join of the two will result in 12 entries, i.e. 4 X 3 entries. But
here, only the first five rows have been displayed.
Qualified join:
The qualified join further is categorized into
Left Outer Join/ Left Join.
Right Outer Join/ Right Join.
Full Outer Join/ Full Join.
Left Outer Join/ Left Join:
In this case all the rows of the Left table will appear at least once. The Left Outer Join logical
operator returns each row that satisfies the join condition between the Left table and the Right
Here in the above shown result too, the first three and the last row of the result is displayed. The
last row shows that for the value in the right table, which did not find any corresponding value in
the left table, NULL values are assigned for the corresponding left table values.
This time, all the rows of first table and second table are displayed as the result. The rows in the
first table or the second table which have no matching value in the corresponding table are
displayed only once, with the other table value being Null value, i.e. if there is some row in the
first table which has no match in the second table, is shown once in the result, with the
corresponding value of the second table being NULL and vice versa.
The above query outputs the Name of the Teacher, Date of Joining, and, Salary from the Teacher
table for the employees whose EmployeeID is less than or equal to 3.
To take another example involving the implication of the Condition on the string valued fields, the
query follows:
select StudentName, RollNumber from Student where StudentName like 'Ca%'
Result
StudentName RollNumber
Catherine 1001
Cathe 1003
The above query lists the Names, Roll Numbers and Address of those students whose Name
begins with Ca. Thus, it will result in the output of two records. Here, like is the function that
selects only those records where name begins with Ca. For obtaining specific values, the <field
name> of string type, can also be used using the = operator just like its use in case of Integer
field types.
Clearly, the above query lists out the records of all the Teachers whose Salary is either 8500, or
10,000. The IN clause will be detailed later.
GROUP BY CLAUSE
A GROUP BY clause, part of a SELECT statement, groups a result into subsets that have
matching values for one or more columns. GROUP BY clause is optional and follows the
WHERE clause, and if WHERE clause is not present, it follows FROM clause. It operates on the
rows filtered by the WHERE clause. This clause performs the function of grouping the rows
based on the common values in the grouping columns. The GROUP BY clause restricts the rows
of the result set i.e, in each group, no two rows have the same value for the grouping column or
columns. NULLs are considered equivalent for grouping purposes.
If several single row columns are in a query, GROUP BY returns exactly as many rows as there
are distinct sets of values in all the single row columns involved in the query. If these columns
have five sets of values, five rows will result.
You typically use a GROUP BY clause in conjunction with an aggregate expression.
ClassID COUNT
1 5
2 5
The following query calculates the average marks of students according to their StudentID, i.e.,
average marks of all the students with STUDENTID = 1, average marks of all the students with
STUDENTID = 2, and so on.
select StudentID , Avg (Marks) as AVGS from Marksrecord Group By StudentId
Result
StudentID AVGS
1 81.0
2 82.0
3 78.0
4 79.0
And in this way, average marks for the students grouped by their StudentId will be displayed.
Here only till the StudentId = 4, have been displayed.
Example to show support for using scalar functions in Group By clause
Sorting will be performed on the result returned by this query by applying Group By on
the scalar function sqrt(postid) and postid
DateOfJoining COUNT
1996-04-17 1
1997-07-01 1
The above query first groups the result set by DateOfJoining and salary and then imposes the
condition of SALARY <= 8500, thus further filtering the final record set. The above result
contains just the first 2 rows of the result set.
Phone No.
(408)615-2250
1-828-675-
4262
In the above result, first three and the last record is displayed.
If the ALL is used with UNION operator, it retains the duplicate records. The syntax for the
UNION with ALL though remains the same as shown in the following query.
select School.PhoneNumber FROM School
UNION ALL
select Student.PhoneNumber FROM Student
Result
1-828-675-4262
(408)615-2250
(440) 238 -
7297
In this case, the result of the UNION queries, with the use of ALL or DISTINCT yields the same
result, because there are no duplicate records.
INTERSECT OPERATOR
The INTERSECT works opposite to the UNION operator. Unlike the UNION operator which
outputs the distinct records, the INTERSECT operator displays the records which are common for
both the queries. When ALL is used with INTERSECT (that is, INTERSECT ALL), duplicate rows
are not eliminated. In either case, each row of the derived table is a row from either TABLE1 or
TABLE2. By default, the Set Quantifier is DISTINCT
Syntax
<query expression body> INTERSECT [ <set quantifier> ] <query primary>
<query expression body> ::= <non-join query expression> | <joined table>
<query primary> ::= <non-join query primary> | <joined table>
<set quantifier> ::= DISTINCT | ALL
Example
select ClassID from Classes
INTERSECT
Select ClassID from Student
Result
ClassID
1
2
The above query displays the results in which the ClassID field have same values for both the
tables. If ALL is used with INTERSECT operator, it retains the duplicate records. The syntax for
the INTERSECT with ALL though remains the same as shown in the following query.
SubjectID
1
1
1
1
6
6
6
Because of the ALL keyword, after performing the INTERSECT, the lesser number of copies of
the records with same value, from either of the two tables, are displayed. In the above query ,
since, the number of records with value 2, in the ClassProperties is more than the number of
records with the same value in the Marksrecord, in the final result, three records are displayed.
StudentID RollNumber
1 1001
2 1002
3 1003
4 1004
The result shows first four records satisfying above query.
The above query, being the simplest one, lists the ID and Roll Numbers of the Students from the
STUDENT table. The result will be sorted by Roll Number in the Ascending order, by default.
Select StudentId, StudentName,
RollNumber from Student
Where StudentName like 'Ca%'
Order By RollNumber DESC, StudentID
Result
1 Catherine 1001
1 Principal 10000
3 Teacher 6000
The above query sorts the list of Teachers by their DateOfBirth, selecting the Name of the
Teacher, his/her Date of joining and Date of Birth. The DateOfBirth is aliased as DOB which is
then used in the Order By clause.
select a.EmployeeID as EmployeeID, a.DepartName as Department, b.PostName
from Teacher as a, Post as b
where a.PostID = b.PostID
Result
Simple Comment: A Simple Comment starts with 2 <minus sign> (--) and terminated with a
semicolon (;). Examples of Simple Comments are
Select * From --This is a Select Query Selecting All Records of a Table Student; Student
Delete From Name of table; Student where Condition for Delete; Studentid<10
Bracketed Comment: A Bracketed Comment starts with a <solidus> (/) immediately followed by
a <asterisk> (*) i.e. /* and terminated with <asterisk> immediately followed by a <solidus> i.e. */.
Examples of Bracketed comments are
Update Student /* Set name of student to John where Studentid is 10 */ Set StudentName = John
where Studentid =10
Rollback Statement
Rollback statement will undo all the changes made since the last completed Transaction i.e. since
the last COMMIT or ROLLBACK statement called.
Syntax
ROLLBACK [WORK] [ TO SAVEPOINT <Savepoint-Name> ]
Rollback erases all data modifications made since the start of the transaction or to a Save point. It
also frees resources held by the transaction. ROLLBACK without a Savepoint_name rolls back to
the beginning of the transaction. A transaction cannot be rolled back after a COMMIT statement is
executed.
Example
ROLLBACK to SAVEPOINT save_point1
Above example rollbacks all changes or data modifications made since the start of the transaction
to a save point name save_point1.
ROLLBACK WORK
Above example rollbacks all changes to the beginning of the transaction.
set schema abc.xyz; -> here abc is catalog name and xyz can be any identifier (schema
name)
Schemas are used for controlling security in Daffodil DB. When creating a user, they do not have
any access privileges to schemas of other users or other data objects within the database. The
Daffodil DB RDBMS only permits the schema or database owner to grant privileges on the data
objects within the schema.
Users can grant privileges to the following data objects in the schema:
Tables
Columns
Roles
SQL Procedures
Domain
The following table describes the privileges that users can grant to other users for tables and
columns.
Grant Statement
Use the GRANT statement to grant privileges on a data object.
Syntax
GRANT <privileges> TO <grantee> [ { <comma> <grantee> }... ] [ WITH GRANT OPTION ] [
GRANTED BY <grantor> ]
<Privilege> ::= <object privileges> ON <object name>
<object privileges> ::= ALL PRIVILEGES | <action> [ { <comma> <action> }... ]
<object name> ::= [ TABLE ] <table name> | DOMAIN <domain name> | <specific routine
designator>
<action>:: =
SELECT
| SELECT <left paren> <privilege column list> <right paren>
| DELETE
| INSERT [ <left paren> <privilege column list> <right paren> ]
| UPDATE [ <left paren> <privilege column list> <right paren> ]
| REFERENCES [ <left paren> <privilege column list> <right paren> ]
| USAGE
| TRIGGER
| EXECUTE
<grantor> ::= CURRENT_USER | CURRENT_ROLE
<grantee> ::= PUBLIC | <authorization identifier>
If you do not include one or more of these privileges in the GRANT statement, an error
will be raised.
If the optional column-names are not specified for the SELECT, INSERT, UPDATE,
REFERENCES and TRIGGER privileges, the GRANT is a table-level grant that allows
access to all present and future columns of the table.
If you execute a GRANT statement that contains privileges that you dont have or for
which you do not have the right to grant, then an error occurs.
You may only grant the EXECUTE privilege on an SQL Procedure.
Revoke Statement
Revoke Statement is used to revoke a role or a privilege from a user.
Syntax
REVOKE [GRANT OPTION FOR] <privileges> FROM
<grantee> [ { <comma> <grantee> }... ]
[GRANTED BY <grantor>]
<drop behavior>
<drop behavior>: CASCADE | RESTRICT
To revoke a role from a user, use the SQL command, REVOKE. This command revokes only the
privileges that the specified <grantor> granted to the <grantee>. If another <grantor> granted
the same privileges to the <grantee>, then the <grantee> will still have those privileges.
Note: - The syntax rule for the REVOKE syntax is similar to the GRANT statement. The major
difference is the additional RESTRICT or CASCADE keyword and the GRANT OPTION FOR
clause. The following describes the optional clauses GRANT OPTION FOR and RESTRICT or
CASCADE.
You may only revoke privileges, which you have granted.
GRANT OPTION FOR
If the optional GRANT OPTION FOR clause is used, the WITH GRANT OPTION right is
revoked, but the actual privilege itself is not revoked then CASCADE and RESTRICT may be
used in the same way as the normal REVOKE statement.
RESTRICT | CASCADE
If you specify the RESTRICT keyword, only privilege granted by you, will be revoked from the
specified user. If the specified user had grant option and has granted the same privilege to other
users, then there will be an error. If you specify CASCADE, only the privileges granted by you,
will be revoked from the specified user or any other privileges dependent on your grant.
Example 1
Following statement revokes the SELECT privilege on the TEACHER table from the user USER1.
REVOKE SELECT ON teacher FROM user1 restrict
Create Role
Creates a role to which the privileges can be granted.
Syntax
CREATE ROLE <role_name> [WITH ADMIN <grantor>]
<grantor> ::= CURRENT_USER | CURRENT_ROLE
role_name
It is the name of the role you are creating. For <role_name>, you can not use any existing user
name and reserve words.
WITH ADMIN_<grantor>
If WITH ADMIN <grantor> is not specified, then the grantor is the CURRENT_USER.
IF WITH ADMIN CURRENT_ROLE is specified, then the CURRENT_ROLE must not
be NULL.
Examples
If current user is USER1, this will create a role called PRINCIPAL whose owner will be the user
USER1. Privileges can now be granted to the role PRINCIPAL. The user USER1 can then grant
this role PRINCIPAL to other users, or to other roles. Once the role is granted to the users or to
other roles, these users and roles will have same level of privileges as was granted to the role
PRINCIPAL.
Syntax
role_name
It is the name of the role to be granted. You may grant more than one role.
Grantee
A role can be granted to users or to other roles.
You cannot grant a role to itself.
You cannot grant one role to a second role, and then attempt to grant the second role back
to the first. For example, you can grant Role (A) to Role (B) or Role (B) to Role (A), but
not both. Such a series of grants would result in a role grant cycle, which is not allowed.
Granting to PUBLIC grants the role to all present and future users and roles.
WITH ADMIN OPTION
If WITH ADMIN OPTION is specified, then the <grantee> can grant the role to other
users or roles.
Note: - To successfully execute this command, current users or roles must either be the role
owner. Or, the <grantor>s must have admin option for every role that they grant.
Examples
REVOKE
Use REVOKE to revoke a role from a user or another role. This command revokes only the roles
that the specified <grantor> granted to the <grantee>.
Please note that the syntax rule for the REVOKE syntax is similar to GRANT ROLE, except for
the following.
NOTE: You may only revoke roles, which you have granted.
If ADMIN OPTION FOR is specified, then only the admin option for the role is revoked.
Drop behavior
If you specify the RESTRICT keyword, If the specified <grantee> had the ADMIN
OPTION and granted the same privilege to other users, then privileges will be retained
otherwise revoked.
If you specify CASCADE, only the role granted by you, will be revoked from the
specified <grantee> and any other roles dependent on your grant.
Examples
Syntax
DROP ROLE <role_name>
Examples
DROP ROLE URole
NOTE: You may only drop roles, which you have created.
SET ROLE
Syntax
Usage Notes
To successfully execute this command, the current user must be the role owner, or a user
granted to use this role.
This statement will set the current role for the current user to either the role specified or to
the null value if NONE is specified.
Example 1
The following statement will set the role Principal and after that only those schema objects could
be accessed, for which the roles have been set for.
SET ROLE PRINCIPAL
DSE14=An aggregate may not appear in the where clause unless it is in a subquery contained in a
having clause or a SELECT list, and the being aggregated is an OUTER reference.
DSE27=Insufficient privileges.
DSE40=Cannot concatenate character data type value {0} to byte data type value {1}.
DSE201=A routine definition can have at most one <SQL-data access indication>.
DSE206=A routine definition can have at most one <parameter style clause>.
DSE224=Catalog name in constraint definition does not match catalog of table defintion.
DSE225=Catalog name can not be changed as table name or schema name does not exist.
DSE226=Catalog name in schema definition and table definition for table {0} does not match.
DSE227=Catalog name in the view definition is not matching with that of schema definition.
DSE228=Catalog name of the trigger definition is not matching with that of schema definition.
DSE250=Column names in each table must be unique. Column name {0} in table {1} is specified
more than once.
DSE251=ALTER TABLE DROP COLUMN statement failed because column {0} does not exist in
table {1}.
DSE252=ALTER TABLE DROP COLUMN statement failed because {0} is the only data column in
table {1}. A table must have at least one data column.
DSE264=Column descriptor does not exist. TABLE CATALOG {0} TABLE SCHEMA {1} TABLE
NAME {2} COLUMN NAME {3} PRIVILEGE TYPE {4}.
DSE265=Table descriptor does not exist. TABLE CATALOG {0} TABLE SCHEMA {1} TABLE
NAME {2} PRIVILEGE TYPE {3}.
DSE272=Cannot use duplicate column names in index key list. Column name {0} listed more than
once.
DSE274=Trigger {0} uses the invalid column/columns {1} in trigger column list.
DSE288=ALTER TABLE DROP CONSTRAINT statement failed because constraint {0} is being
referenced foreign key constraint {1}.
DSE297=Invalid data.
DSE339=Domainconstraint does not exist. Catalog: {0} schema: {1} constraint: {2}.
DSE358=Exception.
DSE382=INSERT statement conflicted with FOREIGN KEY constraint {0}. The conflict occurred in
table {1}.
DSE401=Illegal call.
DSE415=Invalid fetch direction. In case of type forward, only fetch forward is valid direction.
DSE484=Insert failed.
DSE504=Invalid column.
DSE520=Invalid grantor.
DSE531=Invalid query.
DSE538=Invalid URL.
DSE562=List is empty.
DSE731=The variable name {0} has already been declared. Variable names must be unique within a
stored procedure.
DSE752=Number of columns in query expression and view column list are not equal.
DSE773=The value you entered is not consistent with the data type or length of the column.
DSE775=Old or old row, new or new row, old table, and new table shall be specified at most once each
within the <old or new values alias list>.
DSE776=Old row alias can not be specified with insert type of event.
DSE778=Old table alias can not be specified with insert type of event.
DSE825=Query failed.
DSE836=Range is exceeding {0} start position {1} is greater than length of blob {2}.
DSE875=Role authorization descriptor does not exist. Role name: {0} grantee: {1}.
DSE883=Rowset is read-only.
DSE907=Schema owned by {0} has not granted drop privilege to this user.
DSE925=Some problem.
DSE940=Statement is closed.
DSE945=Sum or avg aggregate function can not accept character string as argument.
DSE946=Syntax error.
DSE975=Length {0} of column {1} can not be less than 128 for default clause
DSE983=The length {0} can not be greater than valid length {1}.
DSE1018=Type {0}.
DSE1024=mismatched type.
DSE1026=Column {0} is not the same data type as referencing column {1}.
DSE1032=Violation of UNIQUE KEY constraint {0}. Cannot insert duplicate key in object {1}.
DSE1036=Unsupported format.
DSE1086=There are no primary or candidate keys in the referenced table {0} that match the
referencing column list in the foreign key {1}.
DSE1090=Create View failed because no column name was specified for functional column.
DSE1139={0} type column privilege already exists for grantor {1} grantee {2} table {3} column name
{4}.
DSE1148={0} type usage privilege already exists for GRANTOR {1} GRANTEE {2} object {3}.
DSE1149={0} type routine privilege already exists for grantor {1} grantee {2} routine {3}.
DSE1152=Method specification already exists for SPECIFIC CATALOG {0} SPECIFIC SCHEMA
{1} SPECIFIC NAME {2}.
DSE1179=Catalog name is not same in object name {0} and schema descriptor {1}.
DSE1208=Invalid username/password.
DSE1209=Insufficient privileges.
DSE1216=Invalid status{0}.
DSE1251={0} statement conflicted with CHECK constraint {1} defined as {2}. the conflict occurred
in table {3}.
DSE1255=Violation of PRIMARY KEY constraint {0}. Cannot insert duplicate key in object {1}.
DSE1256=Insert error: column name or number of supplied VALUES does not match table definition.
DSE1257=The name {0} is not permitted in this context. Only constants, expressions, or variables
allowed here. Column names are not permitted.
DSE1259=Some column has been updated with value not satisfying the query.
DSE1274=Problem in Execution of Trigger For Table {0} While Performing Action [{1}] due to {2}.
DSE1284=INSERT statement conflicted with FOREIGN KEY constraint {0} MATCH PARTIAL.
Cannot update the NULL values in all referencing column(s).
DSE1285=INSERT statement conflicted with FOREIGN KEY constraint {0} MATCH PARTIAL.
Cannot insert the NULL values in all referencing column(s).
DSE1288=UPDATE statement conflicted with UNIQUE KEY constraint {0}. The conflict occurred in
table {1}.
DSE1289=UPDATE statement conflicted with PRIMARY KEY constraint {0}. The conflict occurred
in table {1}.
DSE1290=UPDATE statement conflicted with FOREIGN KEY constraint {0}. The conflict occurred
in table {1}.
DSE1291=Cannot insert the value NULL into column {0}, table {1}; column does not allow nulls.
INSERT failed.
DSE1292=Cannot update the value NULL into column {0}, table {1}; column does not allow nulls.
UPDATE failed.
DSE1295=There are {0} columns in the INSERT statement than values specified in the values clause.
the number of values in the VALUES clause must match the number of columns specified in the
INSERT statement.
DSE1303=Invalid column {0} has been used in trigger action for table {2}.
DSE1309=Invalid password
DSE2006=Record is partial.
DSE2013=Type {0}.
DSE2025={0}.
DSE2027=Cannot add database with more than one file and numtifile support as FALSE.
DSE2028=Length of new files :: {0} initial size :: {1} increment factor is not possible with the
database files u r trying to ADD.
DSE2030=File size :: {0},initial size :: {1}, increment factor :: {2} not posssible.
DSE2038=Element is deleted.
DSE2041=NODE IS NONLEAF
DSE2051=Either path specified for database or database name is too long which exceeds OS limits.
DSE3521=View Tables from SQl Hierarchy does not match fully with the Plan Hierarchy
DSE3533=Columnnames specified in from sub query and derived column list are not equal in length.
DSE3541=A column has been specified more than once in the order by list. Columns in the order by
list must be unique.
DSE3543=ORDER BY items must appear in the select list if the statement contains a UNION
operator.
DSE3544=Order Column {0} not present in selectList of query involving set operator.
DSE3545=The ORDER BY position number {0} is out of range of the number of items in the select
list.
DSE3566=Having clause can not be given without any aggregate columns or group by
DSE3571=Collator of column {0} and column {1} does not match, hence we cannot compare
DSE3802=Not found.
DSE4107=Invalid data type {0} is passed for argument {1} in function {2}.
DSE4109=Invalid operator for data type. operator EQUALS minus, type EQUALS {0}.
DSE4111=The {0} aggregate operation cannot take a {1} data type as an argument.
DSE4112=Syntax error converting the {0} value {1} to a column of data type {2}.
DSE4114=The BLOB,CLOB data types cannot be compared or sorted, except when using is null
operator.
DSE4116=Iterator not alligned to any valid location. (First call beforefirst() or first()).
DSE4117=Iterator not alligned to any valid location. (First call afterlast() or last()).
DSE4121=Syntax error converting the {0} value {1} to a column of data type {2} and value {3}.
DSE5003=Invalid Event (Listener fired with SELECT Type Event with Operation Type update)
DSE5008=There are no primary or candidate keys in the referenced table {0} that match the
referencing column list in the foreign key {1}.
DSE5010=Schema contains some Database Objects i.e. tables, views, Domains, Routines, Triggers etc.
Can not be dropped
DSE5015=Not a valid view both materialized and INTO tablename should be specified
DSE5041=Number of Parameter Infos for client parameters {0} are more than parameters in query
{1}.
DSE5102=Cannot drop materailized view {0}, because this view is not a materailized view.
DSE5514=Absoulte of the INCREMENT value must be less than or equal to MAXVALUE minus
MINVALUE and Should not be ''0''
DSE5522=Database is in use.
DSE5524=Remove ChildServerSession.
DSE5530=Sessionid list contains only one element.No Start save point exists.
DSE5543=System Database is not properly created, delete the directory from the path first.
DSE5548=Column name {0} appears more than once in the result column list.
DSE5574=Can't take backup as Source Path And Destination Path are same.
DSE5579=Backup correpted - some files are either removed or deleted from path - Start backup after
removing all files from the path.
DSE6006=ORDER BY columns must appear in the select list if DISTINCT is contained in Select List.
DSE6011=Contains clause not supported for queries involving more than one table or view.
DSE7001=Foreign key {0} has implicit reference to object {1} which does not have a primary key
defined on it.
DSE7002=Number of referencing columns in foreign key differs from number of referenced columns,
table {0}.
DSE7006=Foreign key {0} references invalid column {1} in referenced table {2}.
DSE7007=Foreign key {0} references invalid column {1} in referencing table {2}.
DSE7008=Cannot alter table {0} because this table does not exist in database.
DSE7009=Cannot drop the table {0}, because it does not exist in the database.
DSE7010=Cannot drop the view {0}, because it does not exist in the database.
DSE7052=[rsb]one record is already taken for insertion FIRST COMMIT that and then try again.
DSE7053=[rsb]Invalid call.
DSE7057=Cannot drop the index {0} from table {1}, because it does not exist in the database.
DSE7065=Cannot drop the trigger {0}, because it does not exist in the database.
DSE7069=Illegal Mapping.
DSE7074=More than one key specified in column level FOREIGN KEY constraint, table {0}.
DSE7077=Column names in each view must be unique. Column name {0} in view {1} is specified
more than once.
DSE7078=ALTER TABLE DROP COLUMN statement conflicted with FOREIGN KEY constraint
{0}. The conflict occurred in table {1}, column {2}.
DSE7079=ALTER TABLE ALTER COLUMN SET DEFAULT statement failed because column {0}
does not exist in table {1}.
DSE7080=ALTER TABLE ALTER COLUMN DROP DEFAULT statement failed because column
{0} does not exist in table {1}.
DSE7082=ALTER TABLE DROP COLUMN statement conflicted with TRIGGER {0}. The conflict
occurred in table {1}, column {2}.
DSE7083=ALTER TABLE DROP COLUMN statement conflicted with CHECK constraint {0}. The
conflict occurred in table {1}, column {2}.
DSE7084=ALTER TABLE ADD CONSTRAINT statement conflicted with UNIQUE constraint {0}.
The conflict occurred in table {1}.
DSE7086=ALTER TABLE ADD CONSTRAINT statement conflicted with CHECK constraint {0}.
The conflict occurred in table {1}.
DSE7087=ALTER TABLE ADD COLUMN statement conflicted with PRIMARY KEY constraint
{0}.ALTER TABLE only allows columns to be added that can contain nulls or have a DEFAULT
definition specified. Column {1} cannot be added to table {2} because it does not allow nulls and does
not specify a DEFAULT definition.
DSE7088=ALTER TABLE ADD COLUMN statement conflicted with UNIQUE KEY constraint {0}.
The conflict occurred in table {1}.
DSE8009=Invalid number
DSE8010=DROP TABLE statement conflicted with VIEW {0}. The conflict occurred in table {1}.
DSE8011=DROP TABLE statement conflicted with TRIGGER {0}. The conflict occurred in table
{1}.
DSE8012=DROP TABLE statement conflicted with CHECK constraint {0}. The conflict occurred in
table {1}.
DSE8013=DROP TABLE statement conflicted with FOREIGN KEY constraint {0}. The conflict
occurred in table {1}.
DSE8014=DROP VIEW statement conflicted with VIEW {0}. The conflict occurred in view {1}.
DSE8015=DROP VIEW statement conflicted with TRIGGER {0}. The conflict occurred in view {1}.
DSE8022=Invalid timestamp data type value. Timestamp format must be yyyy-mm-dd hh:mm:ss.fff.
DSE8025=Acess Denied Do not have Select privileges on column {0} of table {1}
DSE8032=Old or new values alias list can not be specified for Statement trigger
DSE8037=Beginning label and ending label used should match for a statement
DSE8042=Only prepared statement like functionality supported in case of statements other than CALL
statement
DSE8049=The maximum size for all index columns can not exceed {0} bytes. The index {1} with size
{2} bytes can not be created.
DSE8052=Either EXECUTE not called or command does not produce result set
DSE8060=Parameter Index can not be less than 1,passed parameter index is {0}
DSE8062=In case of type Forward only ,only valid direction is fetch forward
DSE8093=The role can not be granted to itself or any of its applicable roles
DSE8096=Role to be granted does not lie in applicable role of grantor {0} or doesn't have WITH
ADMIN OPTION.
DSE8103=object can not be created with name greater than 128 characters
DSE8111=Invalid start index passed to the {0} function. Start index can not be less than one.
DSE8112=Invalid length parameter passed to the {0} function. Length can not be negative.
DSE8114=Invalid counter passed to the {0} function. Counter can not be negative.
DSE8116=Cannot alter domain {0} because this domain does not exist in database.
DSE8118=Problem in creating file {0} either it contains illegal characters or blank spaces
DSE6003=For Update Option cannot be used if query contains multiple tables, view, group by or
having clause.
DSE8123=Number of parameters in procedure declaration does not match with number of parameters
in java method
DSE8137=Do not have sufficient privileges for create schema with {0} catalog.
DSE8139={0}
DSE8148=Value larger than specified precision not allowed for column {0}
DSE8149=Data type value is invalid for column {0} / Date format must be yyyy-mm-dd.
DSE8154=More than one primary key constraint can not be applied on column {0}
DSE8155=More than one unique key constraint can not be applied on column {0}
DSE8156=More than one not null constraint can not be applied on column {0}
DSE8157=Both primary key and unique key constraint''s can not be applied on column {0}
DSE8162=Query expression''s length {0} can not exceed ''4192'' characters for view {1}.
DSE8167=Grantor {0} does not have any privilege with grant option on object {1}.
DSE8170=Result of repeat function exceeds the maximum length of char data type.
DSE8176=Current user {0} must have references rights on column {1} of table {2}.
DSE8177=The value you entered is not consistent with the data type or length of the parameter.
DSE8186=Trigger table alias does not match with alias {0} used in when condition.
DSE8187=Can not add multiple unique OR primary key constraint on same column in table {0}