Professional Documents
Culture Documents
SQL
SQL What is it ?
A powerful,
set oriented,
non-procedural
Non-proprietary
Language created to perform tasks such as update or
retrieve data from relational databases
First introduced by IBM in mid 70s
First commercial version by Oracle corporation in 79,
followed by IBM in 80
Available on ALL platforms from PC to mainframes
CS 53 Ramasesha Mudigere . Contd. 2
SQL is ..
1. An interactive query language for ad-hoc queries
2. A database programming language
3. A combo of data definition, manipulation &
administration commands
4. Provides features, for data validation and transaction
support in a multi-user environment
5. Most appropriate language for networked database
servers
6. The flexible language that can be used for any data
storage and access
CS 53 Ramasesha Mudigere 3
SQL is ..
1. An interactive query language for ad-hoc queries
2. A database programming language e TA
th DA
3. A combo of data definition, manipulation or &l of
f ro
administration commands nca n t
ra c o
4. Provides features, for a f
data n d and transaction
validation
gu n a
support in a multi n itio
li -usernenvironment
h e efi
T
5. Most appropriate , d
language for networked database
servers io n
l at
pu
i language that can be used for any data
6. The flexible
an
m and access
storage
CS 53 Ramasesha Mudigere 4
History Of SQL
In 1974, D. Chamberlin (IBM San Jose Laboratory)
defined language called Structured English Query
Language (SEQUEL)
A revised version, SEQUEL/2, was defined in 1976 but
name was subsequently changed to SQL for legal
reasons
IBM subsequently produced a prototype DBMS called
System R, based on SEQUEL/2
In late 70s, ORACLE appeared and was probably first
commercial RDBMS based on SQL
CS 53 Ramasesha Mudigere 5
SQL Standards
SQL-86 (A.k.a. SQL1)
issued by ANSI and ISO in 1986
SQL-89 - Minor revision like
intersection of SQL implementations of that time; (SQL
compliance was very easy for most)
Referential integrity
Bindings to standard programming languages
SQL-92 ( A.k.a. SQL2) -- Ratified in late 1992
Full-function RDBMS
Defines three levels of compliance - Entry, Intermediate, &
Full
The most widely used version in vogue even today
CS 53 Ramasesha Mudigere . Contd.6
SQL Standards
SQL 1999 ( A.k.a. SQL3)
The current version of SQL standards
Over 5 times the size of SQL-92
Included OO features and stored procedures
Most DBMSs conform .. but some features are still not
implemented by some vendors.
SQL 2003 ( A.k.a. SQL4)
Proposed new Standard
XML Extensions and
SQL-1999 bug fixes
CS 53 Ramasesha Mudigere 7
SQL Standards u s s.
p l r e
SQL 1999 ( A.k.a. SQL3) e ,
s at u
t r
u y fe
The current version of SQL standards f a
e tar
- 9 2 ri e
Over 5 times the size of SQL-92 L
Q lp r o p
S
ll , ci a
Included OO features and stored a procedures
t spe
no
Most DBMSs conform .. but t, i f some &features are still not
o s ard s
implemented by some r mvendors.n d
ff e sta
SQL 2003 ( A.k.a. s oSQL4) e r
e m l a t
ys t m
Proposed l s new f ro
Standard
r c i a e t s
XML e e s
Extensions and
m m tur
Co SQL g f e a -1999 bug fixes
ry i n
a
CS v53 Ramasesha Mudigere 8
SQL
Today,
300+ vendors of SQL products on various platforms
like
DB2, Oracle, Sybase, Informix, Microsoft SQL Server,
MSAccess, Ingress, MYSQL etc..
Most of them also have their own additional proprietary
extensions that are usually only used on their system
Has gone ( rather going ) through several revisions and
standardizations by ANSI
CS 53 Ramasesha Mudigere 9
SQL Commands
Can be Grouped as:
1. DML Component ) To manipulate data in the Tables
2. DDL Component ) To Add / Change / Delete Tables
3. Admin. Component ) To Control & manage access
permissions
4. Programming Component ) To access Database
in procedural way
5. Transaction Support ) To run transactions in a
multi-user environment
CS 53 Ramasesha Mudigere 10
1. SQL DML Component
Comprises FOUR (4 ) basic statements:
1. SELECT
To retrieve rows from tables
2. UPDATE
To modify the rows of tables
3. INSERT
To add new rows to tables
4. DELETE
To remove rows from tables.
CS 53 Ramasesha Mudigere 11
2. SQL DDL Component
Comprises THREE (3) basic statements:
1. CREATE
To create new table specification
2. DROP
To delete the tables
3. ALTER
To add or delete columns from a table, and
To change the specification on an existing
column
CS 53 Ramasesha Mudigere 12
3. SQL Admin Component
Comprises FOUR (4) basic statements:
1. CREATE
To create new users to access database
2. DROP
To delete the users
3. GRANT
To provide specific access permissions to users
4. REVOKE
To withdraw access permissions from users
CS 53 Ramasesha Mudigere 13
4. SQL Programming Component
Comprises FOUR (4) basic statements:
1. DECLARE
To define CURSORS to access database
2. OPEN
To enable / activate CURSORS
3. FETCH
To get data rows based on CURSOR
4. CLOSE
To disable /deactivate the cursor
CS 53 Ramasesha Mudigere 14
5. SQL Transaction Component
Comprises FOUR (4) basic statements:
1. BEGIN
To start a new transaction
2. COMMIT
To make the changes done by a a transaction
permanent
3. ROLLBACK
To undo the changes done by a transaction
4. SAVEPOINT
To create an intermediary commit point
CS 53 Ramasesha Mudigere 15
SQL Statements A Summary
ADMIN PGM TXN
DML DDL
Support Support Support
OPEN
UPDATE DROP DROP COMMIT
CS 53 Ramasesha Mudigere 16
SQL Statements Coding Format
SQL is not Case Sensitive.
Exception:
Character values within quotation marks (Use the correct
case for these values.)
Example:
adams will not match with the stored value is Adams
Tabs and Indentations will promote readability.
Keywords cannot be split or abbreviated.
SQL Statements can be split across lines.
Clauses are placed in different lines, to promote
readability.
CS 53 Ramasesha Mudigere 17
1. SQL DML Component
Comprises FOUR (4 ) basic statements:
1. SELECT
To retrieve rows from tables
2. UPDATE
To modify the rows of tables
3. INSERT
To add new rows to tables
4. DELETE
To remove rows from tables.
CS 53 Ramasesha Mudigere 18
SELECT
The most common and most used verb in SQL
The one ( and only one) basic command used to
retrieve data from column (s) of Table (s)
NOT to be confused with the SELECT operation of
Relational Algebra
So many options and flavor are available making it one
of the most versatile and powerful commands
Can vary from very simple to most Complex command
depending on options and parameters used
CS 53 Ramasesha Mudigere 19
An SQL SELECT Query
Has up to six clauses specified in the following order :
SELECT [ DISTINCT | ALL ] < attribute list >
FROM < table list [alias] [, ...] >
[ WHERE < condition > ]
[ GROUP BY < grouping attribute(s) > ]
[ HAVING < group condition > ]
[ ORDER BY < attribute list> ]
Only the first two, SELECT and FROM, are mandatory
CS 53 Ramasesha Mudigere 20
Clauses of SELECT Statement
SELECT ) To List the columns (and expressions) that
should be returned from the query
FROM ) To Indicate the table(s) or view(s) from
which data will be obtained
WHERE ) To Indicate the conditions under which a
row will be included in the result
GROUP BY ) To Indicate categorization of results
HAVING ) To Indicate the conditions under which a
category (group) will be included
ORDER BY ) To Sort the result according to specified
CS 53 criteria
Ramasesha Mudigere 21
SQL statement
processing order
CS 53 Ramasesha Mudigere 22
SQL statement
processing order
CS 53 Ramasesha Mudigere 23
Simple SELECT command
1. SELECT * FROM EMPLOYEE
Lists all columns from table Employee with column name
( underlined ) as heading ;The output format looks something
like this *
2. SELECT BDATE, ADDRESS FROM EMPLOYEE
Lists columns BDATE & ADDRESS for all Employees
3. SELECT DNO FROM EMPLOYEE
Lists dept number column from EMPLOYEE Table
4. SELECT DISTINCT DNO FROM EMPLOYEE
Lists only unique DNO ( 5, 4 and 1)
5. SELECT ALL DNO FROM EMPLOYEE O/P Same As Q3
CS 53 N Ramasesha Mudigere 24
Simple SELECT with computed fields
Computed columns
Data that do not exist in the database Can be computed
using data in existing columns & arithmetic operators
SELECT SSN, LNAME, SALARY *12 FROM EMPLOYEE
Lists SSN, LNAME and SALARY *12 ( A computed figure ) for
all rows under the heading :
SSN NAME _SALARY * 12
CS 53 Ramasesha Mudigere 25
Simple SELECT with AS Clause
AS clause is used to name the column differently in the
output ( Not in the database )
AS clause is optional
SELECT SSN, LNAME AS NAME, SALARY *12 AS
ANNUAL_SALARY FROM EMPLOYEE OR
SELECT SSN, LNAME NAME, SALARY *12
ANNUAL_SALARY FROM EMPLOYEE
Lists SSN, LNAME and SALARY *12 ( A computed figure ) for
all rows under the heading :
SSN NAME ANNUAL_SALARY
CS 53 Ramasesha Mudigere 26
CS 53 Ramasesha Mudigere 27
CS 53 Ramasesha Mudigere B
28
SELECT Statement with WHERE Clause
SELECT FNAME , LNAME, SALARY FROM
EMPLOYEE WHERE DNO = 4
Lists the FNAME LNAME and SALARY from rows where
DNO = 4 ( 3 rows )
Comparison operators allowed are:
CS 53 Ramasesha Mudigere 29
SELECT Statement with compound Condition
Compound conditions
Formed by connecting two or more simple conditions
Uses AND, OR, and NOT operators
1. AND: all conditions must be true
2. OR: any one of conditions is true
3. NOT: reverses the truth of the original condition
The WHERE clause in SQL can include
compound Conditions to fine tune the selection
CS 53 Ramasesha Mudigere 30
SELECT Statement with compound
Condition
CS 53 Ramasesha Mudigere 31
SELECT Statement with compound
Condition
CS 53 Ramasesha Mudigere 32
Range Search Condition
1. BETWEEN operator
Used to search for a range of values
Inclusive values defining range are included
( BETWEEN 10 AND 20 will return 10 and 20 if available. )
Not an essential feature
Can arrive at same answer without it using AND
Does make certain SELECT commands simpler
Can be negated using NOT BETWEEN
CS 53 Ramasesha Mudigere 33
Range Search Condition - Example
CS 53 Ramasesha Mudigere 34
Pattern Matching Condition
LIKE operator
used when exact matches will not work
Can be used with a wildcard symbol
Can be negated using NOT LIKE
CS 53 Ramasesha Mudigere 35
Pattern Matching Condition
SQL> SELECT ename ENAME
-------
2 FROM emp JAMES
3 WHERE ename LIKE _A%; WARD
CS 53 Ramasesha Mudigere 36
Set Membership Condition
Use of IN
Provides concise way of phrasing certain conditions
Used to search for groups of values ( Replaces = )
List of values are in ( ) and comma separated
Advanced Advantage Can contain list of values from
another query
Can be negated by using NOT IN
List the customer number, last name, and first name
for every customer with a credit limit of $1,000, $1,500,
or $2,000
CS 53 Ramasesha Mudigere 37
Set Membership Condition
Use of IN
CS 53 Ramasesha Mudigere 38
ORDER BY Clause
Generally, the order of rows is immaterial to the DBMS
Results when displayed are in no defined order
Rows can displayed in the order in which they were
entered
However:
ORDER BY clause lists data in a specific order
Last part of SQL statement that controls order of records
returned
ASC Ascending Order (Default order )
DESC Descending Order
CS 53 Ramasesha Mudigere 39
ORDER BY Example
CS 53 Ramasesha Mudigere 40
ORDER BY Example
SQL> SELECT ename, job, deptno, hiredate
2 FROM emp
3 ORDER BY hiredate DESC;
ENAME JOB DEPTNO HIREDATE
---------- --------- --------- ---------
ADAMS CLERK 20 12-JAN-83
SCOTT ANALYST 20 09-DEC-82
MILLER CLERK 10 23-JAN-82
JAMES CLERK 30 03-DEC-81
FORD ANALYST 20 03-DEC-81
KING PRESIDENT 10 17-NOV-81
MARTIN SALESMAN 30 28-SEP-81
...
1453 rows selected.
CS Ramasesha Mudigere 41
ORDER BY using multiple keys
When sorting more than one column
the more important column is called the major key
(or primary sort key)
CS 53 Ramasesha Mudigere 43
Handling NULL Values
signifies an unknown value or a value that does not exist.
Any arithmetic operation with NULL results in NULL
NULL values sometimes produce unexpected results
NULLS require special handling when coding
Use the SQL Operator IS NULL to test for NULL values
SQL> SELECT ename, mgr
2 FROM emp
3 WHERE mgr IS NULL;
ENAME MGR
-------- ---------
CS 53 KING Ramasesha Mudigere 44
Aggregate operators in SQL
Also referred to as Group Functions
ISO standard defines five aggregate functions:
1. COUNT returns number of values in specified column
2. SUM returns sum of values in specified column.
3. AVG returns average of values in specified column.
4. MIN returns smallest value in specified column.
5. MAX returns largest value in specified column
All operators (Except count) used only on numeric data
ignoring NULL values, if any, are encountered
CS 53 Ramasesha Mudigere 45
COUNT
Returns the number of non-null occurrences of a column
Use of asterisk * Counts the rows
Use DISTICNCT to count duplicate values only once
SELECT COUNT(PART_NUMBER) FROM PART
WHERE ITEM_CLASS = HW;
CS 53 Ramasesha Mudigere 46
SUM, AVG, MAX and MIN
Work only on numeric fields
DISTICT can be used with SUM and AVG
Ignore null values ( But sometimes strange results are obtained)
CS 53 Ramasesha Mudigere 47
Summary of Group Functions
All of them Except count, operate on numeric fields only
COUNT alone
Can work on non-numeric as well as numeric fields
Can also use * as parameter to count number of rows
Null values are ignored during computation;
However strange results may occur sometimes with COUNT
Can be used in any combination
BUT
Can not be used together with direct column references
in the SELECT list (unless the SELECT statement
includes a GROUP BY clause)
CS 53 Ramasesha Mudigere 48
GROUP BY Clause
Intimately connected with Aggregates
Allows data to be:
grouped in a particular order and
compute statistics (aggregate functions) on these groups
that share some common characteristics
When used, the SELECT list must can contain
1. List of column names ( these names must appear in
GROUP BY Clause too) and
2. List of terms with aggregate operation
CS 53 Ramasesha Mudigere 49
GROUP BY Example
Consider the Table
Find highest salary
Find highest salary in DepartmentNo = 5
Find DNO, and highest salary in each DNO
CS 53 Ramasesha Mudigere 50
GROUP BY Example
SELECT DNO, MAX (SALARY) FROM EMPLYEE
GROUP BY DNO ORDER BY DNO
CS 53 Ramasesha Mudigere 52
HAVING Clause
Designed for use with GROUP BY
Restricts groups that appear in final result table
Similar to WHERE, but WHERE filters individual rows whereas
HAVING filters groups
Column names in HAVING clause must also appear in the
GROUP BY list or be contained within an aggregate function
CS 53 Ramasesha Mudigere 53
HAVING Clause Another Example
CS 53 Ramasesha Mudigere 54
Clauses of SELECT Statement (Revisited)
SELECT ) To List the columns (and expressions) that
should be returned from the query
FROM ) To Indicate the table(s) or view(s) from
which data will be obtained
WHERE ) To Indicate the conditions under which a
row will be included in the result
GROUP BY ) To Indicate categorization of results
HAVING ) To Indicate the conditions under which a
category (group) will be included
ORDER BY ) To Sort the result according to specified
CS 53 criteria
Ramasesha Mudigere 55
Sub Query ( A. k. a. Nested Query)
Query within a Query
( SELECT embedded within another SELECT )
Can be used in WHERE and HAVING clauses of an
outer SELECT, where it is called a subquery or nested
query.
May also appear in INSERT, UPDATE, and DELETE
statements OUTER Query
SELECT . FROM .
WHERE . ( SELECT .. FROM . WHERE ..)
CS 53 INNER
Ramasesha Mudigere Query 56
Sub Query Example
Consider the Employee Table
List LNAME with salary higher than salary of Narayan
We need two Queries
SELECT SALARY FROM EMPLOYEE WHERE LNAME = Narayan
SALARY
3800
SELECT LNAME FROM EMPLOYEE WHERE SALARY > 3800
Instead we can Write a single nested query :
SELECT LNAME FROM EMPLOYEE WHERE SALARY > ( SELECT
SALARY FROM EMPLOYEE WHERE LANME = Narayan )
CS 53 Ramasesha Mudigere 57
EMPLOYEE TABLE
CS 53 Ramasesha Mudigere 58
Nested Query Further Example
Suppose we want to check Narayans salary is above
average in his company by finding names with salary
higher than the average salary of the company ?
SELECT LNAME FROM EMPLOYEE WHERE SALARY > ( SELECT
AVG (SALARY) FROM EMPLOYEE)
Suppose we want to check Narayans salary is above
average in his Department alone
SELECT LNAME FROM EMPLOYEE WHERE SALARY > ( SELECT
AVG (SALARY) FROM EMPLOYEE WHERE DNO = ( SELECT
DNO FROM EMPLOYEE WHERE LANME = Narayan )
CS 53 Ramasesha Mudigere 59
Nested Query More Examples
List the amount by which colleagues salaries higher
than that of Narayan
CS 53 Ramasesha Mudigere 60
Nested Query More Examples
List the Average of Excess salary of all those employees
who draw salary higher than the average salary of
Narayans department
SELECT AVG ( SALARY ( SELECT SALARY FROM EMPLOYEE
WHERE LANME = Narayan )) AS AVGEXCESS
FROM EMPLOYEE
WHERE SALARY > ( SELECT AVG (SALARY) FROM
EMPLOYEE WHERE DNO = ( SELECT DNO FROM
EMPLOYEE WHERE LANME = Narayan )
Sub-query returned single value output so far; How about
CS muti
53 -value return ?Ramasesha Mudigere 61
USE of IN in Nested Queries
Used to check the existence of a variable in outer query,
when inner query returns a set not a single value
Consider the Table Employee
List Name and salaries of all who work in Departments
with least one female employee
SELECT LNAME, SALARY FROM EMPLOYEE
WHERE DNO IN ( SELECT DISTINCT DNO FROM EMPLOYEE
WHERE SEX = F )
Inner Query Returns a set of DNO {4,5}
Outer query checks + condition for each member of set
CS 53 Ramasesha Mudigere 62
EMPLOYEE TABLE
CS 53 Ramasesha Mudigere 63
USE OF ANY & ALL
May be used with sub-queries that produce a single
column of numbers
With ALL, condition will only be true if it is satisfied by
all values produced by sub-query.
With ANY, condition will be true if it is satisfied by any
values produced by sub-query.
If subquery is empty, ALL returns true, ANY returns
false.
SOME may be used in place of ANY.
CS 53 Ramasesha Mudigere 64
ANY & ALL Example
Consider the Employee Table
List names of all employees whose salary is equal to
salary of any one who woks in dept 4
SELECT LNAME FROM EMPLOYEE WHERE SALARY = ANY
( SELECT DISTINCT SALARY FROM EMPLOYEE
WHERE DNO = 4 )
List names of all employees in other departments
whose salary is equal to salary of any one who woks
in dept 4
SELECT LNAME FROM EMPLOYEE WHERE Dno NOT = 4
AND SALARY = ANY ( SELECT DISTINCT SALARY FROM
EMPLOYEE WHERE DNO = 4 )
CS 53 Ramasesha Mudigere 65
EMPLOYEE TABLE
CS 53 Ramasesha Mudigere 66
Use OF EXISTS & NOT EXISTS
EXISTS and NOT EXISTS are for use only with
subqueries.
Produce a simple true/false result.
True if and only if there exists at least one row in result
table returned by subquery.
False if subquery returns an empty result table.
NOT EXISTS is the opposite of EXISTS.
CS 53 Ramasesha Mudigere 67
EXISTS Example
Consider Employee table
List all Names & department where at least one female
employee is working
1
2
CS 53 6 Ramasesha Mudigere 74
1
Populated Database
3
2
5
4
6
CS 53 Ramasesha Mudigere 75
Multi Table SELECT Examples
Retrieve the name and address of all employees who
work for the 'Research' department.
CS 53 Ramasesha Mudigere 80
Outer JOIN Example - RIGHT
List branches and properties that are in same city along
with any unmatched Properties
SELECT b.*, p.* FROM Branch1 b RIGHT JOIN PropertyForRent1
p ON b.bCity = p.pCity;
Includes those rows of second (right) table unmatched
with rows from first (left) table.
Columns from First table are filled with NULLs
CS 53 Ramasesha Mudigere 81
Outer JOIN Example - FULL
List branches and properties in same city and any
unmatched branches or properties
SELECT b.*, p.* FROM Branch1 b FULL JOIN PropertyForRent1 p
ON b.bCity = p.pCity;
Includes rows that are unmatched in both tables.
Unmatched columns are filled with NULLs.
CS 53 Ramasesha Mudigere 82
Set Operations with SELECT
Supports UNION, INTERSECTION and DIFFERENCE
to combine results of two or more queries whose
results are union compatible into a single result table
Format of set operator clause in each case is:
op [ALL] [CORRESPONDING [BY {column1 [, ...]}]]
If CORRESPONDING BY specified, set operation
performed on the named column(s).
If CORRESPONDING specified but not BY clause,
operation performed on common columns.
If ALL specified, result can include duplicate rows
CS 53 Ramasesha Mudigere 83
Set Operation Examples - UNION
Consider the following tables:
Branch ( Branchno, street, city, pin)
Property (Propid, street, city, type, rent, ownerid, branchandling)
1. List all cities with either a branch office or a property
SELECT city FROM Branch WHERE city IS NOT NULL)
UNION
SELECT city FROM Property WHERE city IS NOT NULL
OR
SELECT * FROM Branch WHERE city IS NOT NULL
UNION CORRESPONDING BY city
SELECT * FROM Property WHERE city IS NOT NULL
CS 53 Ramasesha Mudigere 84
Set Operation Examples - INTERSECT
2. List all cities with both branch office AND a property
CS 53 Ramasesha Mudigere 98
SQL Data Types
1. Boolean ) Consists of variables which can take truth values
of TRUE, FALSE & UNKNOWN (NULL)
2. Character ) Consists of sequence of characters ( a string)
from vendor defined set ( ASCII or EBCDIC)
3. Numeric ) To define numbers ( both integer and real ) based
on pattern or storage allocation
4. BIT ) Consists of sequence of bits ( 0 / 1) ( bit string)
5. Datetime ) To define points in time to a certain degree of
accuracy
6. Interval ) Used to represent periods of time
7. Large Objects ( LOBs) ) Used to store huge amounts of
binary/character data
CS 53 Ramasesha Mudigere 99
2. SQL Data Types Character types
Two sub types are supported namely
1. Fixed length CHAR (n) where n is number of Characters
2. Variable length VARCHAR (n) or CHAR VARYING (n)
where n is the max size of the data item
When specifying a literal string value, the string is
placed between single Quotes ( E.g. Example)
When the character string stored in a field is less than
the size defined, Fixed length CHAR fields are blank
filled to the right & these blanks are ignored in
comparison
CS 53 Ramasesha Mudigere 100
3. SQL Data Types Numeric types
Two sub-categories namely
1. Approximate Numeric which describes the type &
2. Exact Numeric which describes format of the numbers
2.1 Approximate Numeric has following types
INTEGER or INT
SMALLINT
FLOAT ( Precision)
or REAL
DOUBLE PREISION
Precision on FLOAT defines the precision of mantissa
Precision & size of REAL & DOUBLE PRECISION is
implementation dependent
CS 53 Ramasesha Mudigere . Contd.
101
3. SQL Data Types Numeric types
Two sub-categories namely
1. Approximate Numeric which describes the type &
2. Exact Numeric which describes format of the numbers
2.2 Exact Numeric
Used for declaring formatted numbers
NUMERIC ( p, s ) or DECIMAL ( p, s) where
p represents the TOTAL number of digits ( precision) and
S represents the number of digits to the right of decimal
point ( scale) ( 0 < or = s < or = p & default is 0)
Example : SALARY TYPE NUMERIC (5,2) can hold a
maximum value of 999.99 & min value of 999.99
CS 53 Ramasesha Mudigere 102
4. SQL Data types Bit String Type
Used to store strings of bits that can take value 0 or 1
Two types are supported
1.BIT (n) where n specifies the length of the bit string
2.BIT VARYING (n) specifies a variable length string of
maximum size n
Literal bit strings are specified by placing the string
between single quotes but preceded by B ( like fo
example B101101
If the string size is a multiple of even hexa-decimal
notation can be used with preceding character X
Data is right justified and zero filled to the left
CS 53 Ramasesha Mudigere 103
5. SQL Data types Datetime Type
Used to define points in time to a certain degree of
accuracy
E.g. dates, times, and times of a day
ISO standard subdivides this data type to YEAR, MONTH,
DAY, HOUR, MINUTE, SECOND, TIMEZONE_ HOUR &
TIMEZONE_MINUTE
Three types of Datetime data type is supported
1. DATE
2. TIME [ timePrecision] WITH TIME ZONE]
3. TIMESTAMP [ timePrecision] WITH TIME ZONE]
CS 53 Ramasesha Mudigere . Contd.
104
5. SQL Data types Datetime Type
5.1 DATE
Used to store calendar dates
Has TEN positions with components as YEAR MONTH and DAY
in the form YYYYMMDD
Literal values can be mentioned as DATE2006-09-27 and
comparison performed directly
5.2 TIME [ timePrecision] WITH TIME ZONE]
Used to store time with at least 8 positions with components
HOUR, MINUTE and SECOND in the form HH:MM:SS
timeprecision is the number of the decimal places of accuracy
to which the second field is kept ( Max vendor dependent) and
it defaults to 0
CS 53
CS 53 Ramasesha Mudigere
Ramasesha Mudigere . Contd.
105
5. SQL Data types Datetime Type
5.2 TIME [ timePrecision] WITH TIME ZONE]
WITH TIME ZONE keyword includes additional six positions
for specifying the displacement from the standard universal
time zone
Literal values can be mentioned as TIME09:22:15 and
comparison performed directly
5.3 TIMESTAMP
Includes both the DATE and TIME fields plus a minimum of
six positions for decimal fractions of seconds and optional with
TIME ZONE Qualifier
Literal values are placed by single-quoted-strings preceded by
TIMESTAMP ( E.g. TIMESTAMP 2006-09-1115:35:648302)
CS 53 Ramasesha Mudigere 106
6. SQL Data types Interval Type
Used to represent periods of time ( Durations)
Consists of contiguous subset of fields YEAR, MONTH,
DAY, HOUR, MINUTE, SECOND
Two types of INTERVAL fields
1. Year-Month intervals &
2. Day-time Intervals
Generally used in Temporal databases
Format
INTERVAL [{startfield] TO [Endfield}] or [singletimefield]
CS 53 Ramasesha Mudigere 107
7. SQL Data types LOBs
Used to store large size objects which are generally
not kept as a part of data base (E.g. (photos, videos,
CAD files, etc.)
1. blob: binary large object
A large collection of un-interpreted binary data (whose
interpretation is left to an application outside of the
database system)
2. clob: character large object
a large collection of character data
When a query returns a large object, a pointer is
returned rather than the large object itself.
CS 53 Ramasesha Mudigere 108
8. User Defined data Types
SQL 3 supports user Defined data types (UDT)
Users
Manager
Privileges
SQL>
SQL> GRANT
GRANT create
create table,
table, create
create view
view
22 to
to manager;
manager;
Grant
Grant succeeded.
succeeded.
SQL>
SQL> GRANT
GRANT manager
manager to
to BLAKE,
BLAKE, CLARK;
CLARK;
Grant
Grant succeeded.
succeeded.
ORACLE
Link
Run Time Linker Application
Library Program
CS 53 Ramasesha Mudigere 167
CS 53 Ramasesha Mudigere 168
Host language Variables
Used in embedded SQL to transfer data from database
into program and vice versa
Cannot be used to represent database objects, such
as table names or column names
Declared in a special Section of the program initially
Prefixed by colon : , when used in the program
Additional variables called indicators can be
associated with these variables to indicate the status of
data transfer like:
Indicating NULL values in Db
Truncation of data etc..
CS 53 Ramasesha Mudigere 169
Host Variables DECLARE Section
addressInd = -1;
EXEC SQL UPDATE PrivateOwner
SET address = :address :addressInd
WHERE ownerNo = CO21;
CS 53 Ramasesha Mudigere 172
SQLCA Area
A data structure to be included in the program by the
programmer
Used ( initialized) by DBMS to indicate the status of
every SQL execution in the program
Set by DBMS after execution of each DBMS command
Contains several fields of which SQLCODE is of
special interest
0 - statement executed successfully;
< 0 - an error occurred;
> 0 - statement executed successfully, but an exception
occurred, such as no more rows returned by SELECT.
CS 53 Ramasesha Mudigere 173
CS 53 Ramasesha Mudigere 174
Embedding SQL Commands
Starts with identifier, usually EXEC SQL
Data Types
UDT
Binary Character Double-Byte DateTime Numeric
String String Char String
decimal
DATE time timestamp
DECIMAL
integer floating
CHAR CLOB point
GRAPHIC DBCLOB SMALLINT
BLOB INTEGER REAL
VARCHAR
VARGRAPHIC
DOUBLE
1
2
Populated Database
3
2
5
4
6
CS 53 Ramasesha Mudigere 199