Beruflich Dokumente
Kultur Dokumente
Miracle – Database
Author Details:
Prepared by: Database Team
Email: ljampana@miraclesoft.com
Phone no: 12482331818
Document Details:
Version: 5.0
Date: Thursday, December 08, 2005
V.4.1
V.4.2
V.4.3
V.4.4
V.4.5
V.4.6
V.4.7
V.4.8
V.4.9
V.4.10
V.4.11
V.4.12
V.4.13
V.4.14
V.4.15
V.4.16
V.4.17
V.4.18
V.4.19
Miracle Software Systems, Inc Database
V.4.20
Table of Contents
1.Introduction........................................................................................................................................................4
1.1.Data 4
1.2.Database.................................................................................................................................................4
1.3.RDBMS....................................................................................................................................................4
1.4.Exercises.................................................................................................................................................4
2.SQL (Structured Query Language)..................................................................................................................5
2.1.DATA DEFINITION LANGUAGE.............................................................................................................5
2.1.1.DATA TYPES.............................................................................................................................5
2.1.2.Constraints..................................................................................................................................6
2.2.DATA MANIPULATION LANGUAGE......................................................................................................8
2.2.1.INSERT.......................................................................................................................................8
2.2.2.UPDATE.....................................................................................................................................8
2.2.3.DELETE......................................................................................................................................8
2.3.TRANSACTION CONTROL LANGUAGE................................................................................................9
2.4.Exercise...................................................................................................................................................9
3.OPERATORS....................................................................................................................................................10
3.1.MATHEMATICAL OPERATORS...........................................................................................................10
3.2.COMPARISION OPERATORS..............................................................................................................10
3.3. LOGICAL OPERATORS.......................................................................................................................10
3.4. SPECIAL OPERATORS.......................................................................................................................10
3.5. SET OPERATORS...............................................................................................................................10
3.6.Exercise.................................................................................................................................................13
4.BUILTIN FUNCTIONS.....................................................................................................................................14
4.1.CHARACTER FUNCTIONS...................................................................................................................14
4.2.NUMERIC FUNCTIONS........................................................................................................................17
4.3.DATE FUNCTIONS...............................................................................................................................18
4.4.CONVERSION FUNCTIONS.................................................................................................................20
4.5.GROUP FUNCTIONS............................................................................................................................21
4.6.NULL FUNCTIONS................................................................................................................................22
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 2 of 36
Last printed
Miracle Software Systems, Inc Database
4.7.CASE Expression..................................................................................................................................23
5.JOINS 24
6.SUB QUERIES and CORELATED SUB QUERIES........................................................................................26
6.1.SUB QUERIES......................................................................................................................................26
6.1.1.SINGLE ROW SUB QUERY.....................................................................................................26
6.1.2.MULTIPLE ROW SUB QUERY................................................................................................26
6.2.CORELATED SUB QUERIES..............................................................................................................26
7.VIEWS...............................................................................................................................................................28
7.1.1.STORED PROCEDURE...........................................................................................................29
7.1.2.STORED FUNCTION...............................................................................................................30
7.1.3.TRIGGER..................................................................................................................................32
8.CURSORS.........................................................................................................................................................33
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 3 of 36
Last printed
Miracle Software Systems, Inc Database
1. Introduction
1.1.
Data
Related information is called as DATA.
1.2.
Database
Data stored as a collection in an organized manner can be called as database.
1.3.
RDBMS
A Relational Database Management System is a program that lets you create, update and
administrator a relational database. The primary rule for RDBMS is that the Data should
be stored in the form of tables.
Most of the RDBMS’s use the Structured Query Language to access the database.
When a database undergoes NORMALISATION it is called as a RDBMS.
Different products of RDBMS are
ORACLE Oracle Corporation.
SQL Server2000 Microsoft Corporation.
DB2 UDB IBM
MySQL MySQL
Sybase Sybase
Teradata NCR
1.4.
Exercises
a) Oracle is a ______________.
b) DB2 is a product of ___________.
c) ___________ is a language with which we can access the database.
d) In RDBMS the data is stored in the form of _____________.
e) _____________is a product of Microsoft Corporation.
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 4 of 36
Last printed
Miracle Software Systems, Inc Database
2. SQL (Structured Query Language)
This is a common language with which we can interact with the database.
SQL is classified mainly into three categories.
SQL
2.1.
DATA DEFINITION LANGUAGE
These commands are used to create, modify and delete database objects.
DDL Commands are Autocommit.
Create
This command is used to create database objects such as Tables, Views, Indexes,
Synonyms, Sequences, Stored Procedures, Triggers, Functions, Packages and userdefined
datatypes.
Alter
This command is used to modify the structure of the database objects.
Drop
This command is used to remove the objects from the database.
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 5 of 36
Last printed
Miracle Software Systems, Inc Database
2.1.1.
DATA TYPES
DB2
int
char
time
varchar
numeric
float
decimal
date
time stamp
2.1.2.
Constraints
Constraint restricts the values that the table can store.
We can declare integrity constraints at the table level or column level.
In columnlevel constraints the constraint type is specified after specifying the column
datatype i.e., before the delimiting comma.
Where as in the tablelevel constraints the constraint type is going to be specified as
separate commadelimited clauses after defining the columns.
There are five constraints
1. Not Null
2. Unique Key
3. Check
4. Primary Key
5. Foreign Key
Not Null
If a column in a table is specified as Not Null, then it’s not possible to insert a null into
that column. It can be implemented with create and alter commands. When we
implement the Not Null constraint with alter command there should not be any null
values in the existing table.
Unique Key
The unique constraint doesn't allow duplicate values in a column. If the unique
constraint encompasses two or more columns, no two equal combinations are
allowed. To enforce unique constraint, the column must be a Not Null column. That
means, we can not insert a single row with a Null value against the Unique Key
constraint column.
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 6 of 36
Last printed
Miracle Software Systems, Inc Database
Check
Check constraint is used to restrict the values before inserting into a table.
Primary Key
The key column with which we can identify the entire Table is called as a primary key
column. A primary key is a combination of a Unique and a Not Null constraint, it will
not allow null and duplicate values. A table can have only one primary key.
A primary key can be declared on two or more columns as a Composite Primary Key.
Foreign Key
Columns defined as foreign keys refer the Primary Key of other tables. The Foreign
Key "points" to a primary key of another table, guaranteeing that you can't enter data
into a table unless the referenced table has the data already which enforces the
REFERENTIAL INTEGRITY. This column will take Null values.
Except Not Null constraint all other constraints can be given at both the column level
and table level.
TABLE CREATION
Syntax
CREATE TABLE <table name> (
<column_name1> <data type>[(<width>)]
[constraint <constraint name> <constraint type>],
<column_name2> <data type>[(<width>)],
<column_name3> <data type>[(<width>)],
<column_name4> <data type>[(<width>)],
.
.
.
<column_nameN> <data type>[(<width>)]
);
Example
CREATE TABLE Employee(
empno int not null constraint pk_empno primary key,
ename varchar(50) constraint nn_ename not null,
salary decimal(10,2),
hire_date date,
gender char(1) constraint chk_gen check(gender in (‘M’, ‘F’, ‘m’, ‘f’)),
email varchar(50) unique
);
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 7 of 36
Last printed
Miracle Software Systems, Inc Database
ALTER TABLE
Syntax
ALTER TABLE <table name> ADD CONSTRAINT <constraint name> <constraint
type> <column name>;
Syntax to add referential integrity
ALTER TABLE <table name> ADD CONSTRAINT <constraint name>
FOREIGN KEY(<foreign key column>)
REFERNCES <parent table name>(<primary key column>);
Example
ALTER TABLE Employee ADD CONSTRAINT un_ename UNIQUE(ename);
ALTER TABLE Employee ADD CONSTRAINT Ref_dept
FOREIGN KEY (deptno)
REFERENCES Department(deptno);
DROP
Syntax
DROP <OBJECT> <object name>;
Example
DROP PROCEDURE ins_emp;
DROP TABLE Employee;
2.2. DATA MANIPULATION LANGUAGE
These commands are used to append, change or remove the data in a Table.
COMMIT/ROLLBACK statement should be given to make the changes permanent or to revert
back.
2.2.1.
INSERT
Using this command we can append data into tables.
Syntax
INSERT INTO <table name>(<column_name1>, <column_name2>, ...)
VALUES (column1_value, column2_value, ...);
INSERT INTO <tablename>(<column_name2>, <column_name1>, ...)
VALUES (column2value, column1value, ...);
INSERT INTO <tablename> VALUES (value1, value2, ...);
Example
INSERT INTO Employee(empno, ename, salary, hire_date, gender, email)
VALUES(1234, ‘JOHN’, 8000, ’18AUG80, ‘M’, ‘john@miraclesoft.com’);
INSERT INTO Employee(email , ename, empno, hire_date, gender, salary)
VALUES(‘rhonda@miraclesoft.com’, ‘RHONDA’, 1235, ’24JUL81’, ‘F’, 7500);
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 8 of 36
Last printed
Miracle Software Systems, Inc Database
INSERT INTO Employee
VALUES(1236, ‘JACK’, 15000, ’23SEP79’, ‘m’, ‘jack@miraclesoft.com’);
2.2.2.
UPDATE
This command is used to modify the data existing in the tables.
Syntax
UPDATE <tablename> SET <columnname> = <value>;
UPDATE <tablename> SET <columnname> = <value> WHERE <condition>;
Example
UPDATE Employee SET salary = 15000;
UPDATE employee SET salary = 15000 WHERE empno = 1235;
2.2.3.
DELETE
Syntax
DELETE FROM <tablename>;
DELETE FROM <tablename>WHERE <condition>;
Example
DELETE FROM Employee;
DELETE FROM Employee WHERE empno = 1236;
2.3. TRANSACTION CONTROL LANGUAGE
These command are used to maintain the consistency of the database.
Commit
This command is used to make the transaction permanent.
Rollback
This command is used to undo the recent transaction.
2.4. Exercise
a) TCL stands for _____________________________________.
b) Define UNIQUE key constraint.
c) Give a statement to add a primary key to an existing table.
d) Give the sql statement to drop an procedure
e) Delete is a Auto Commit statement. YES/NO.
f) Rollback make the current transaction permenant. YES/NO.
g) After deleting records we get back the values using COMMIT statement. YES/NO.
h) Using UPDATE statement we can update multiple tables.YES/NO.
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 9 of 36
Last printed
Miracle Software Systems, Inc Database
3.
OPERATORS
3.1. MATHEMATICAL OPERATORS
V.6 Symboli
V.5 Operator
c V.8 Description
Name
V.7 Notation
Addition + To add two integer values.
Subtraction To subtract two integer values.
Division / To divide two integer values.
Multiplication * To get the product of two integer values.
3.2. COMPARISION OPERATORS
V.10 Symbolic
V.9 Operator Name
V.11 Notation
EQUAL TO =
GREATER THAN >
LESS THAN <
GREATER THAN OR EQUAL TO >=
LESS THAN OR EQUAL TO <=
NOT EQUAL TO <> or !=
3.3. LOGICAL OPERATORS
V.1 OPERATOR
V.2 AND
V.3 OR
V.4 NOT
3.4. SPECIAL OPERATORS
OPERATOR
IN
LIKE
NULL
BETWEEN
HAVING
EXISTS
DISTINCT
ORDER BY
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 10 of 36
Last printed
Miracle Software Systems, Inc Database
3.5. SET OPERATORS
OPERATOR DESCRIPTION
UNION Returns all rows retrieved by both the queries excluding common rows.
UNION ALL Returns all rows retrieved by both the queries including duplicate rows.
INTERSECT Returns all common rows in both the queries.
EXCEPT Returns all rows from the first query which are not existing in second
query.
Examples on SET operators
SELECT JOB FROM EMP WHERE DEPTNO=10
UNION
SELECT JOB FROM EMP WHERE DEPTNO=20;
SELECT JOB FROM EMP WHERE DEPTNO=10
UNION ALL
SELECT JOB FROM EMP WHERE DEPTNO=20;
SELECT JOB FROM EMP WHERE DEPTNO=10
INTERSECT
SELECT JOB FROM EMP WHERE DEPTNO=20;
SELECT JOB FROM EMP WHERE DEPTNO=10
EXCEPT
SELECT JOB FROM EMP WHERE DEPTNO=20;
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 11 of 36
Last printed
Miracle Software Systems, Inc Database
Examples on SPECIAL operators
SELECT * FROM DEPT WHERE DEPTNO IN (SELECT DISTINCT DEPTNO FROM EMP);
DEPTNO DNAME LOC
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
DEPTNO EMPNO ENAME
20 7369 SMITH
20 7876 ADAMS
20 7902 FORD
20 7788 SCOTT
20 7566 JONES
SELECT EMPNO,SAL,COMM FROM EMP WHERE COMM IS NOT NULL;
EMPNO SAL COMM
7499 1600 300
7521 1250 500
7654 1250 1400
7844 1500 0
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 12 of 36
Last printed
Miracle Software Systems, Inc Database
SELECT EMPNO,SAL FROM EMP WHERE SAL BETWEEN 2000 AND 3000;
EMPNO SAL
7566 2975
7698 2850
7782 2450
7788 3000
7902 3000
1111 3000
SELECT DEPTNO,AVG(SAL) FROM EMP GROUP BY DEPTNO HAVING AVG(SAL)>1000;
DEPTNO AVG(SAL)
10 2937.5
20 2175
30 1566.66667
DEPTNO DNAME LOC
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
SELECT DISTINCT SAL FROM EMP;
SAL
2500
3250
3600
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 13 of 36
Last printed
Miracle Software Systems, Inc Database
SELECT DEPTNO,EMPNO,SAL FROM EMP ORDER BY SAL;
DEPTNO EMPNO SAL
20 7369 800
30 7900 950
30 7521 1250
30 7654 1250
3.6. Exercise
a) Give the SET operators.
b) Describe Union All.
c) What is the order in which we can use orderby, where, having and groupby clauses.
d) What are the mathematical operators we have.
e) Define Distinct clause.
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 14 of 36
Last printed
Miracle Software Systems, Inc Database
4.
BUILTIN FUNCTIONS
SYSIBM.SYSDUMMY1
A table in DB2 of SYSIBM’s schema against which we can test any functions.
Ex: Select 12345 * 33 from SYSIBM.SYSDUMMY1;
4.1. CHARACTER FUNCTIONS
DB2
CHR
ASCII
LOWER/LCASE
UPPER/UCASE
SUBSTR
REPLACE
TRANSLATE
LENGTH
LTRIM
RTRIM
LEFT
RIGHT
LOCATE
CONCAT
ASCII
ASCII returns the decimal representation in the database character set of the first
character of char.
SELECT ASCII('A') FROM sysibm.sysdummy1;
ASCII('A')
65
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 15 of 36
Last printed
Miracle Software Systems, Inc Database
CHR
CHR returns the character having the binary equivalent to n in either
the database character set or the national character set.
SELECT CHR(65) FROM sysibm.sysdummy1;
A
CONCAT
CONCAT returns char1 concatenated with char2. Both char1 and char2
can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2,
CLOB, or NCLOB. The string returned is of VARCHAR2 datatype
and is in the same character set as char1. This function is equivalent to the
concatenation operator (||).
SELECT CONCAT('MIRACLE ','SOFTWARE') FROM sysibm.sysdummy1;
CONCAT('MIRACLE'
MIRACLE SOFTWARE
SELECT 'MIRACLE ' || 'SOFTWARE' FROM sysibm.sysdummy1;
'MIRACLE'||'SOFT
MIRACLE SOFTWARE
LOCATE
This function search string for substring and returns an integer
indicating the position of the character instring that is the first
character of this occurrence.
SELECT LOCATE('Miracle Software Systems','S',1,2) from sysibm.sysdummy1;
LOCATE('MIRACLESOFTWARESYSTEMS','S',1)
8
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 16 of 36
Last printed
Miracle Software Systems, Inc Database
LENGTH
This function returns the length of the given string.
SELECT LENGTH('MIRACLE') FROM sysibm.sysdummy1;
LENGTH('MIRACLE')
7
LOWER
Convert the whole string into lower case.
SELECT LOWER('MIRACLE') FROM sysibm.sysdummy1;
LOWER('
miracle
LTRIM :
It trims the given string on LEFT side by removing the spaces on the left.
SELECT LTRIM(' MIRACLE') FROM sysibm.sysdummy1;
LTRIM('T
MIRACLE
RTRIM
It trims the given string on RIGHT side by removing the spaces on the right..
SELECT RTRIM('MIRACLE ') FROM sysibm.sysdummy1;
RTRIM('
MIRACLE
REPLACE
It returns a string with every occurrence of search string replaced with the replacement
string.
SELECT REPLACE('THAT MIRACLE','THAT','TEAM') FROM sysibm.sysdummy1;
REPLACE('MI
TEAM MIRACLE
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 17 of 36
Last printed
Miracle Software Systems, Inc Database
SUBSTR
This function returns a portion of string beginning at the character portion and character
length specified.
TRANSLATE
TRANSLATE returns char with all occurrences of each character in ‘from string’
replaced by its corresponding character in ‘to string’.
SELECT TRANSLATE('KIRACLE MOFTWARE','MS','KM') FROM sysibm.sysdummy1;
TRANSLATE('KIRAC
MIRACLE SOFTWARE
UPPER
Converts the given string into uppercase.
SELECT UPPER('miracle') FROM sysibm.sysdummy1;
UPPER('
MIRACLE
4.2. NUMERIC FUNCTIONS
V.12 DB2
V.13 ABS
CEIL
FLOOR
MOD
POWER
ROUND
SQRT
TRUNC
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 18 of 36
Last printed
Miracle Software Systems, Inc Database
ABS
It returns the absolute value of the given integer.
SELECT ABS (52),ABS(52) FROM sysibm.sysdummy1;
ABS(52) ABS(52)
52 52
53
CEIL,FLOOR
It returns the smallest integer greater than or equal to the given integer.
SELECT CEIL(9.2),CEIL(9.2),FLOOR(9.2),FLOOR(9.2) FROM sysibm.sysdummy1;
CEIL(9.2) CEIL(9.2) FLOOR(9.2) FLOOR(9.2)
10 9 9 10
MOD
SELECT MOD(m, n) FROM sysibm.sysdummy1;
It returns the remainder of the m divided by n, returns 0 if n is 0.
SELECT MOD(14,5) FROM sysibm.sysdummy1;
MOD(14,5)
4
POWER
SELECT POWER(m, n) FROM sysibm.sysdummy1;
Returns the first value raised the second value.
SELECT POWER(5,3) FROM sysibm.sysdummy1;
POWER(5,3)
125
ROUND
SELECT ROUND(123.50,1),ROUND(123.49,1),ROUND(1234.5666,3),
ROUND(1234.5666,2) FROM sysibm.sysdummy1;
ROUND(123.50) ROUND(123.49) ROUND(1234.5666,3) ROUND(1234.5666,2)
123.50 123.50 1234.5670 1234.5700
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 19 of 36
Last printed
Miracle Software Systems, Inc Database
SQRT
SQRT returns square root of n. The value cannot be negative. SQRT returns a "real" result.
SELECT SQRT(26) "Square root" FROM sysibm.sysdummy1;
Square root
5.09901951
TRUNC
SELECT TRUNC(123.50,1),TRUNC(123.49,1) FROM sysibm.sysdummy1;
1 2
123.50 123.40
4.3. DATE FUNCTIONS
V.14 DB2
CURRENT_DATE
CURRENT_TIMESTAMP
DAY,MONTH,YEAR
HOUR,MINUTE,SECOND
MICROSECOND
DAYS
DAYNAME,MONTHNAME
CURRENT_DATE
CURRENT_DATE
Returns the current date in mm/dd/yyyy format.
SELECT CURRENT_DATE FROM sysibm.sysdummy1;
CURRENT_DATE
12/12/2006
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 20 of 36
Last printed
Miracle Software Systems, Inc Database
CURRENT_DATE
Returns the current date in mm/dd/yyyy format.
SELECT CURRENT_TIME FROM sysibm.sysdummy1;
CURRENT_TIME
00:19:05
CURRENT_TIMESTAMP
Returns current time and date in the session time zone.
SELECT CURRENT_TIMESTAMP FROM sysibm.sysdummy1;
CURRENT_TIMESTAMP
2006121210.25.44.875000
DAY(date), MONTH(date), YEAR(date)
Returns the day, month, year of particular date.
SELECT DAY(CURRENT DATE), MONTH(CURRENTDATE),
YEAR(CURRENT DATE) FROM sysibm.sysdummy1;
1 2 3
12 12 2006
HOUR(time), MINUTE(time), SECOND(time)
Returns the hour, minute, second of particular time
MICRO SECOND(timestamp)
Returns the number of months between the two specified dates.
SELECT HOUR(current_time), MINUTE(current_time),SECOND(current_time)
FROM sysibm.sysdummy1;
1 2 3
14 59 7
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 21 of 36
Last printed
Miracle Software Systems, Inc Database
Here are a couple of examples
4.4. CONVERSION FUNCTIONS
V.15 DB2
INT
CHAR
DATE
DECIMAL
NUMERIC
CHAR
To convert a date or timestamp value to a varchar value.
SELECT CHAR(current date) from sysibm.sysdummy1;
1
01/03/200
DATE
To convert a character date to a date value.
SELECT DATE('04042004') FROM sysibm.sysdummy1;
1
04042004
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 22 of 36
Last printed
Miracle Software Systems, Inc Database
INT
To convert a character number into a number value.
SELECT INT('100.50') FROM sysibm.sysdummy1;
1
100 100
DECIMAL
4.5. GROUP FUNCTIONS
Group function work on a group of data to obtain aggregated values
V.15.1.1.1 B2UDB
AVG
COUNT
MIN
MAX
SUM
SELECT COUNT(SAL), AVG(SAL), MIN(SAL), MAX(SAL), SUM(SAL) FROM EMP;
1 2 3 4 5
14 2073.21428571428571428571428571 800.00 5000.00 29025.00
SELECT DEPTNO,AVG(SAL) FROM EMP WHERE DEPTNO<>10 GROUP BY DEPTNO
HAVING AVG(SAL)>1600;
DEPTNO AVG(SAL)
20 2175
NOTE
WHERE filters before GROUPING and HAVING clause filters after grouping
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 23 of 36
Last printed
Miracle Software Systems, Inc Database
4.6. NULL FUNCTIONS
COALESCE
The COALESCE function returns the first nonnull expr in the expression list. At least one
expr must not be the literal NULL. If all occurrences of expr evaluate to null, the function
returns null. This function is a generalization of the NVL function. You can also use
COALESCE as a variety of the CASE expression.
COALESCE (expr1, expr2)
is equivalent to:
CASE WHEN expr1 IS NOT NULL THEN expr1 ELSE expr2 END
NULLIF
If expr1 is null, NULLIF returns expr2. If expr1 is not null, NULLIF returns expr1. The
arguments expr1 and expr2 can have any datatype. If their datatypes are different, Oracle
converts expr2 to the datatype of expr1 before comparing them. The datatype of the return
value is always the same as the datatype of expr1, unless expr1 is character data, in which
case the return value’s datatype is VARCHAR and is in the character set of expr1.
The following example returns a list of employee names and commissions, substituting
"Not Applicable" if the employee receives no commission:
SELECT last_name, N\ULLIF(TO_CHAR(commission_pct), ’Not Applicable’)
"COMMISSION" FROM employees WHERE last_name LIKE ’B%’;
LAST_NAME COMMISSION
Baer Not Applicable
Baida Not Applicable
Banda .11
Bates .16
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 24 of 36
Last printed
Miracle Software Systems, Inc Database
4.7. CASE Expression
This expression lets us use IF…THEN…ELSE logic in SQL Statements.
SELECT ename,
CASE WHEN sal< 3000 THEN 'Low'
WHEN sal>10000 THEN 'High'
ELSE 'Medium' END
FROM Emp
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 25 of 36
Last printed
Miracle Software Systems, Inc Database
5. JOINS
When the database is being normalized, data is distributed across multiple tables.
To retrieve the data from one or more tables using select statements is called as a Join.
The table given left to the comparison operator is called the left table and right to that is called the
right table
Joins are classified as
CROSS JOIN
SELF JOIN
EQUI JOIN OR INNER JOIN
NONEQUI JOIN
OUTER JOIN
SELF JOIN
Joining of a table to itself is called as a self join.
Example
SELECT e1.last_name ||' works for '||e2.last_name "Employees and Their Managers"
FROM employees e1, employees e2
WHERE e1.manager_id = e2.employee_id AND e1.last_name LIKE 'R%';
EQUI JOIN
In this type of join data is retrieved from tables comparing a common column.
Example
SELECT ENAME,DNAME,SAL FROM EMP E,DEPT D WHERE D.DEPTNO=E.DEPTNO;
NONEQUI JOIN
Using this type of join data can be retrieved from tables, which are not having any common
columns.
Example
OUTER JOIN
These joins are still classified into three types.
LEFT OUTER JOIN
RIGHT OUTER JOIN
FULL OUTER JOIN
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 26 of 36
Last printed
Miracle Software Systems, Inc Database
LEFT OUTER JOIN
In this type of join the data from the left table is retrieved regardless of the condition
specified.
Example
SELECT ENAME,DNAME,SAL FROM EMP E,DEPT D
WHERE D.DEPTNO=E.DEPTNO;
RIGHT OUTER JOIN
In this type of join the data from the right table is retrieved regardless of the condition
specified.
Example
SELECT ENAME,DNAME,SAL FROM EMP E,DEPT D
WHERE D.DEPTNO=E.DEPTNO;
FULL OUTER JOIN
In this type of join data from both left and right tables is retrieved.
Example
SELECT E.DEPTNO, DNAME, EMPNO FROM EMP E
FULL OUTER JOIN DEPT D
ON E.DEPTNO = D.DEPTNO;
How does one escape special characters when building SQL queries?
The LIKE keyword allows for string searches. The '_' wild card character is used to match exactly
one character, '%' is used to match zero or more occurrences of any characters. These characters can
be escaped in SQL.
Example
SELECT ename FROM emp WHERE ename LIKE '_LA%' ;
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 27 of 36
Last printed
Miracle Software Systems, Inc Database
6. SUB QUERIES and CORELATED SUB QUERIES
6.1.
SUB QUERIES
A query embedded within another query is called as a subquery.
Using subqueries we can use the results of one query as the input for another query.
There are two types of sub queries
1. Single row sub query 2. Multiple row sub query
6.1.1. SINGLE ROW SUB QUERY
If the sub query returns only one single row then it is called as a single row sub query.
6.1.2. MULTIPLE ROW SUB QUERY
If the sub query returns more than one row then it is called as a multiple row sub query.
Example 1
Query to list the employee who is getting the maximum salary
SELECT ename FROM Employee WHERE salary = (SELECT max(salary) FROM Employee);
Example 2
Query to list the employees who are earning more than Blake
SELECT ename FROM Employee
WHERE salary in (SELECT avg(salary) FROM Employee group by job);
6.2. CORELATED SUB QUERIES
Example 1
Write a query to list the employees who are earning more than their manager
SELECT ename FROM emp x
WHERE sal > (SELECT sal FROM emp WHERE empno = x.mgr);
Example 2
How does one eliminate duplicates rows from a table?
Choose one of the following queries to identify or remove duplicate rows from a table leaving
only unique records in the table:
Method 1:
SQL> DELETE FROM EMP A WHERE ROWID > (
2 SELECT min(rowid) FROM EMP B
3 WHERE A.EMPNO = B.EMPNO);
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 28 of 36
Last printed
Miracle Software Systems, Inc Database
Method 2:
SQL> delete from EMP E1
SQL> where exists (select 'x' from EMP E2
SQL> where E2.EMPNO = E1.EMPNO
SQL> and E2.ROWID > E1.ROWID);
How does one generate primary key values for a table?
SEQUENCE
It is a autogenerated number which will be unique.
CREATE SEQUENCE EMPNO_SEQ int START WITH 1111 INCREMENT BY 1;
INSERT INTO EMPLOYEE VALUES(NEXTVAL FOR EMPNO_SEQ,'PRAMOD');
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 29 of 36
Last printed
Miracle Software Systems, Inc Database
7. VIEWS
A view is a logical or virtual table, which does not, exists physically in the database.
Views are also called as Dictionary Objects.
Advantages
Security – The confidential columns can be suppressed from viewing and manipulation.
Complexity can be avoided.
Logical columns can be created.
Application design becomes easier.
Views can be classified into two categories on the way they are created.
1. Simple View 2. Complex View
Simple View
If the view is created from a single table, it is called as a simple view. We can do DML
Operation, if it is Simple View.
Complex View
If the view is created on multiple tables, it is called as a complex view.
Syntax
CREATE VIEW <view name>
AS <query>
Example 1
CREATE VIEW data_emp
AS
SELECT ename, salary FROM Employee;
Example 2
CREATE VIEW dup_emp
AS
SELECT ename, salary, salary*0.2 comm FROM Employee;
DROPPING A VIEW
Only the owner of the view can drop it.
Syntax
DROP VIEW <view name>;
Example
DROP VIEW data_emp;
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 30 of 36
Last printed
Miracle Software Systems, Inc Database
SQL PL
What to do is can determined in SQL but when to do is not possible.
There is interactive programming only in SQL.
To obtain the control DB2 introduced SQL PL programming.
SQL PL stands for Procedural Language/Structured Query Language.
It is a III Generation Language.
There is a Batch programming in SQL PL.
ROUTINES
These are also meant for batch processing but posses a name and are stored as an object in
the database.
Generally these are
Stored Procedures.
Stored Functions.
Triggers.
Cursors.
7.1.1.
STORED PROCEDURE
Definition
It is subprogram, which is stored in the database and whenever it is called, it does
something but doesn’t return any value.
But they could return indirectly through OUT parameters.
Using the stored procedures you can reduce the number of calls to the database and
decrease network traffic.
Syntax of a Stored Procedure (DB2 UDB)
CREATE PROCEDURE <procedure name>(
[<parameter mode>]<parameter1> <data type> [<width>],
[<parameter mode>]<parameter2> <data type> [<width>],
[<parameter mode>]<parameter3> <data type> [<width>],
[<parameter mode>]<parameter4> <data type> [<width>],
[<parameter mode>]<parameterN> <data type> [<width>]
[DYNAMIC RESULT SETS
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 31 of 36
Last printed
Miracle Software Systems, Inc Database
LANGUAGE <language specifier>]
BEGIN
<sql statements>;
END
<special symbol other than ‘;’> block terminator
Example (DB2)
Procedure to insert a new row into the Employee table.
DROP PROCEDURE INS_EMP to drop the procedure if already exist.
CREATE PROCEDURE INS_EMP(
p_ename varchar(50),
p_salary numeric(10,2),
p_hire_date datetime,
p_gender char(1),
p_email varchar(50),
)
AS
LANGUAGE SQL
BEGIN
INSERT INTO Employee(empno, ename, salary, hire_date, gender, email)
VALUES(p_empno, p_ename, p_salary, p_hire_date, p_gender, p_email);
SET p_out_param=p_empno; Assigning the employee number to out parameter.
END
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 32 of 36
Last printed
Miracle Software Systems, Inc Database
7.1.2.
STORED FUNCTION
Definition
It is subprogram, which is stored in the database and whenever it is called, it does
something and return some value.
Syntax of a function (DB2 UDB).
CREATE FUNCTION <function name>>[(
<parameter1> <data type> [<width>],
<parameter2> <data type> [<width>],
<parameter3> <data type> [<width>],
<parameter4> <data type> [<width>],
<parameterN> <data type> [<width>]
)]
RETURNS <data type>
LANGUAGE <language specifier>
BEGIN ATOMIC
[DECLARE
<declarations>;]
<function body>;
END
<special symbol other than ‘;’> block terminator
Example (DB2)
Function to multiply two numbers.
create function product (a integer, b integer)
returns integer
language sql
no external action
not deterministic
begin atomic
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 33 of 36
Last printed
Miracle Software Systems, Inc Database
declare v_pro integer;
set v_pro = a*b;
return v_pro ;
end
7.1.3.
TRIGGER
A trigger is a block of statements, which are fired automatically when a DML operation
takes place.
These are always associated with the database tables.
Triggers are classified as two types:
1. Row Level Triggers. 2. Statement Level Triggers.
1.Row Level Triggers
These triggers will be fired for each row with proportionate to the number of rows
those are begin effected the DML statement.
2. Statement Level Triggers
These triggers are fired once for each statement regardless with the number of
rows
those are being affected by the DML statement.
In DB2 triggers can be classified into two more categories such as
a) Before Triggers. b) After Triggers.
a) Before Triggers
These triggers are fired before the execution of the DML statements.
b) After Triggers
These triggers are fired after the execution of the DML statements.
Syntax of a Trigger(DB2UDB)
CREATE TRIGGER <trigger name>
before/after <event1 or event2 event3>
ON <table>
[for each row]
BEGIN ATOMIC
<action block>;
Example (DB2UDB)
DROP TRIGGER Trig_Insert
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 34 of 36
Last printed
Miracle Software Systems, Inc Database
go
CREATE TRIGGER Trig_Insert after insert
ON Employee
REFERENCING new AS nnn
BEGIN ATOMIC
begin
insert into empid(nnn.empno);
end;
nnn– These are the alias names given to the inserted values.
8.
CURSORS
A cursor is a memory context area.
For every SQL Statement execution certain area in memory is allocated.
SQL PL allows us to name that private area which is called as context area or cursor.
A cursor acts as a handle or pointer into the context area.
A SQL PL program controls the context area using the cursor.
A cursor has 4 stages.
8.1.
Declaring Cursor
DECLARE <cursorname> CURSOR FOR <select statement>
DECLARE emp_cur CURSOR FOR SELECT ename FROM EMP;
Opening Cursor
Syntax
OPEN <cursorname>;
Example
OPEN emp_cur;
Fetching data from Cursor
Syntax
FETCH <cursorname> INTO <variables>;
Example
FETCH emp_cur INTO ena;
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 35 of 36
Last printed
Miracle Software Systems, Inc Database
Closing a Cursor
Syntax
CLOSE <cursorname>;
Example
CLOSE emp_cur;
Important Contacts:
Training Issues:
Ravi Kumar Ijju
Email: rijju@miraclesoft.com
Office: 12482333651
Raju Cherukuri
Email: scherukuri@miraclesoft.com
Office: 12482333654
Immigration / HR Related Issues:
K. Sita Rama Raju
Email: skothapalli@miraclesoft.com
Office: 12482333686
Delivery / Project / Technical Reports:
Ramani Lokam
Email: rlokam@miraclesoft.com
Office: 12482331131
Mobile: 124823213213
System Administration / Others:
Joe Peddiboyina
Email: joe@miraclesoft.com
Office: 12482331199
/home/miracle/Tutors/Db2/DB2_trmaterail.sxw Page 36 of 36
Last printed