db2 part 1

Upload: malleswara-rao-yalamarthi

Post on 07-Apr-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/6/2019 DB2 Part 1

    1/45

    1Confidential Copyright 2008 Wipro Ltd

    Introduction to DB2

    What is DB2? A subsystem of the MVS operating system

    An abbreviation for IBM Database 2 Was announced in June 1983

    Supports SQL (Structured Query Language

  • 8/6/2019 DB2 Part 1

    2/45

    2Confidential Copyright 2008 Wipro Ltd

    SQL

    The bulk of SQL execution takes place in the DB2 Database Servicesaddress space , which

    contains three sub-components: the Relational Data System (RDS), theData Manager, and

    the Buffer Manager.

    The SQL travels through these three components before the results are

    returned to the application. The RDS passes requests to the Data Manager, which

    passes requests to the

    Buffer Manager. The results trace back from the Buffer Manager to theData Manager to the

    RDS. Let's look more closely at the tasks each component handles.

  • 8/6/2019 DB2 Part 1

    3/45

    3

    TYPES OF SQL

    Based on Functionality SQL is 3 types.

    The Data Control Language (DCL) provides the control stmtsthat govern data security withthe GRANT and REVOKE verbs.

    The Data Definition language (DDL) creates and maintains thephysical data structure withthe CREATE, DROP and ALTER sqlverbs

    The Data Manipulation Language (DML) accesses and modifiesdata with the SELECT,INSERT, DELETE and UPDATE verbs.

  • 8/6/2019 DB2 Part 1

    4/45

    4

    SQL CREATE TABLE Syntax

    CREATE TABLE -

    An employee table with fields employee id, name, managername, salary, location can be created by using the followingcommand.

    CREATE TABLE employee

    (empid SMALLINT NOT NULL,empname CHAR(14),

    managerCHAR(14),

    salary DECIMAL(9,2)NOT NULL,

    location VARCHAR(100) )

  • 8/6/2019 DB2 Part 1

    5/45

    5

    SQL ALTER & DROP TABLE Syntax

    ALTER TABLE - A new column can be added to the table by using the ALTER

    command.

    ALTER TABLE employee

    ADD accountnumber DECIMAL(10,0) NOT NULL

    Note: you can not use ALTER TABLE command for dropping acolumn.

    DROP TABLE-

    A TABLE,VIEW can be dropped using DROP statement.

    DROP TABLE employee

  • 8/6/2019 DB2 Part 1

    6/45

    6

    The SQL SELECT Statement

    The SELECT statement is used to select data from a database.

    The result is stored in a result table, called the result-set.

    SQL SELECT Syntax

    SELECT column_name(s) FROM tablename

    SELECT * FROM table_name

  • 8/6/2019 DB2 Part 1

    7/45

    7

    The SQL SELECT DISTINCT Statement

    The SELECT statement is used to select data from a database.

    The result is stored in a result table, called the result-set.

    Unique retrieval

    SQL SELECT DISTINCT Syntax

    SELECT DISTINCT column_name(s) FROM table_name

  • 8/6/2019 DB2 Part 1

    8/45

    8

    The WHERE Clause

    The WHERE Clause

    The WHERE clause is used to filter records.

    WHERE clause is used to retrieve data based on certainconditions.

    SQL WHERE Syntax

    SELECT column_name(s) FROM table_name WHEREcolumn_name operator value

  • 8/6/2019 DB2 Part 1

    9/45

    9

    The AND & OR Operators

    The AND & OR Operators

    The AND operator displays a record if both the first conditionand the second condition is true.

    The OR operator displays a record if either the first conditionor the second condition is true.

    SELECT * FROM Persons WHERE FirstName='Tove' ANDLastName='Svendson'

  • 8/6/2019 DB2 Part 1

    10/45

    10

    The ORDER BY Keyword

    The ORDER BY Keyword

    The ORDER BY keyword is used to sort the result-set by aspecified ORDER.

    The ORDER BY keyword sort the records in ascending order bydefault.

    If you want to sort the records in a descending order, you canuse the DESC keyword.

    SQL ORDER BY Syntax

    SELECT column_name(s) FROM table_name ORDER BYcolumn_name(s) ASC|DESC

  • 8/6/2019 DB2 Part 1

    11/45

    11

    The GROUP BY Keyword

    The GROUP BY Keyword

    The GROUP BY clause is used for grouping the rows by certaincriteria to retrieve the collective information from the table.

    SYNTAX-

    SELECT manager, SUM (salary) as Salary

    FROM Employee

    GROUP BY manager

    The above query sums up the salary circulated by eachmanager and displays the total against the manager name.

  • 8/6/2019 DB2 Part 1

    12/45

    12

    INSERT STATEMENT

    SQL INSERT Syntax-

    The INSERT statement is used for inserting rows into the table.

    INSERT INTO table_name VALUES (value1, value2, value3,...)

    INSERT INTO table_name (column1, column2, column3,...)VALUES (value1, value2, value3,...)

  • 8/6/2019 DB2 Part 1

    13/45

    13

    The UPDATE Statement

    The UPDATE statement is used to update existing records in atable.

    SQL UPDATE Syntax-

    UPDATE table_name SET column1=value, column2=value2,...WHERE some_column=some_value

    Note: The WHERE clause specifies which record or records thatshould be updated. If you omit the WHERE clause, all recordswill be updated!

  • 8/6/2019 DB2 Part 1

    14/45

    14

    The DELETE Statement

    The DELETE statement is used to delete rows in a table.

    SQL DELETE Syntax

    DELETE FROM table_name WHERE some_column=some_value

    Note: The WHERE clause specifies which record or records thatshould be deleted. If you omit the WHERE clause, all records

    will be deleted!

  • 8/6/2019 DB2 Part 1

    15/45

    15

    SQL Wildcards

    SQL wildcards can substitute for one or more characters whensearching for data in a database.

    SQL wildcards must be used with the SQL LIKE operator.

    With SQL, the following wildcards can be used:

    Wild card Description

    % A substitute for zero or more characters

    _ A substitute for exactly one character

  • 8/6/2019 DB2 Part 1

    16/45

    16

    The IN Operator

    The IN operator allows you to specify multiple values in aWHERE clause.

    SQL IN Syntax

    SELECT column_name(s) FROM table_name WHEREcolumn_name IN (value1,value2,...)

    SELECT * FROM Persons WHERE LastName IN('Hansen','Pettersen')

  • 8/6/2019 DB2 Part 1

    17/45

    17

    The BETWEEN Operator

    The BETWEEN operator selects a range of data between twovalues. The values can be numbers, text, or dates.

    SQL BETWEEN Syntax

    SELECT column_name(s) FROM table_name WHEREcolumn_name BETWEEN value1 AND value2

    SELECT * FROM Persons WHERE LastName BETWEEN 'Hansen'AND 'Pettersen'

  • 8/6/2019 DB2 Part 1

    18/45

    18

    The UNION AND UNION ALL Keyword

    UNION is used to combine two or more select stmt to form a singleresulttable.

    UNION is used for represent row

    Output should be in sorted order

    UNION is used to avoid duplicate.

    SELECT empid FROM employee

    UNION

    SELECT empid FROM department

    But if we want to display the result along with the duplicates (as many

    times it appears in the tables), we can use UNION ALL. The output is not in sorted order.

  • 8/6/2019 DB2 Part 1

    19/45

    19

    SQL AlIAS AND SYNONYMS

    AliaS AND SYNONYMS are alternate name of table Alias is an alternate name that can be used by everyone

    synonyms can only be used by creator

    SQL AlIAS Syntax for Tables

    CREATE ALIAS ALIAS_name for Table_name

    SQL SYNONYMS Syntax for Tables

    CREATE SYNONYMS SYN_name for Tbl_name

  • 8/6/2019 DB2 Part 1

    20/45

    20

    SQL COLUMN Functions

    SQL Column functions return a single value, compute from agroup of rows.

    Column functions :

    AVG() - Returns the average value

    COUNT() - Returns the number of rows

    MAX() - Returns the largest value MIN() - Returns the smallest value

    SUM() - Returns the sum

  • 8/6/2019 DB2 Part 1

    21/45

    21

    SQL SCALAR Functions

    Scalar functions operate on a field to get the required operation done. Scalar functions are applied to acolumn or expressoin & operate on

    asingle value.

    Scalar functions are :

    LENGTH ( ) function is used for finding the length of a field

    MONTH ( ) function can be used to retrieve the month part of thedate.

    YEAR ( ) function can be used to retrieve the year part of the date.

    DATE ( ) function can be used to retrieve the date part of the date.

    CONCAT( ) function is used for concatenating strings.

    UCASE ( ) function is used for making all characters of a string to

    upper case. LCASE ( ) function is used for making all characters of a string to

    lowercase.

  • 8/6/2019 DB2 Part 1

    22/45

    22

    SQL JOIN

    The art of combining data from multiple table is called joining. Join is mainly representation of column.

    TYPES OF JOIN-

    2 types of join

    1)INNER JOIN.

    2)OUTER JOIN.

    >LEFT OUTER JOIN

    >RIGHT OUTER JOIN

    >FULL OUTER JOIN

  • 8/6/2019 DB2 Part 1

    23/45

    23

    SQL INNER JOIN Keyword

    The INNER JOIN keyword return rows which are common toboth tables.

    SQL INNER JOIN Syntax

    SELECT column_name(s) FROM table_name1 INNER JOINtable_name2 ON

    table_name1.column_name=table_name2.column_name

  • 8/6/2019 DB2 Part 1

    24/45

    24

    SQL LEFTOUTER JOIN Keyword

    The LEFT JOIN keyword returns all rows from the left table(table_name1), even if there are no matches in the right table(table_name2).

    SQL LEFT JOIN Syntax

    SELECT column_name(s) FROM table_name1 LEFT JOIN

    table_name2 ONtable_name1.column_name=table_name2.column_namePS: Insome databases LEFT JOIN is called LEFT OUTER JOIN.

  • 8/6/2019 DB2 Part 1

    25/45

    25

    SQL RIGHTOUTER JOIN Keyword

    The RIGHT JOIN keyword Return all rows from the right table(table_name2), even if there are no matches in the left table(table_name1).

    SQL RIGHT JOIN Syntax

    SELECT column_name(s) FROM table_name1 RIGHT JOIN

    table_name2 ONtable_name1.column_name=table_name2.column_name

  • 8/6/2019 DB2 Part 1

    26/45

    26

    SQL FULLOUTER JOIN Keyword

    The FULL JOIN keyword return rows when there is a match inone of the tables.

    SQL FULL JOIN Syntax

    SELECT column_name(s) FROM table_name1 FULL JOINtable_name2 ON

    table_name1.column_name=table_name2.column_name

  • 8/6/2019 DB2 Part 1

    27/45

    27

    SQL Constraints

    Constraints are used to limit the type of data that can go into atable.

    Constraints can be specified when a table is created (with theCREATE TABLE statement) or after the table is created (with theALTER TABLE statement).

    We will focus on the following constraints:

    NOT NULL

    UNIQUE

    PRIMARY KEY

    FOREIGN KEY

  • 8/6/2019 DB2 Part 1

    28/45

    28

    SQL NOT NULL Constraint

    The NOT NULL constraint enforces a column to NOT acceptNULL values.

    The NOT NULL constraint enforces a field to always contain avalue. This means that you cannot insert a new record, orupdate a record without adding a value to this field.

    The following SQL enforces the "P_Id" column and the"LastName" column to not accept NULL values:

    CREATE TABLE Persons ( P_Id int NOT NULL, LastNamevarchar(255) NOT NULL, FirstName varchar(255), Addressvarchar(255), City varchar(255) )

  • 8/6/2019 DB2 Part 1

    29/45

    29

    SQL UNIQUE Constraint

    The UNIQUE constraint uniquely identifies each record in a databasetable.

    The UNIQUE and PRIMARY KEY constraints both provide a guaranteefor uniqueness for a column or set of columns.

    A PRIMARY KEY constraint automatically has a UNIQUE constraintdefined on it.

    Note that you can have have many UNIQUE constraints per table, butonly one PRIMARY KEY constraint per table.

    SQL UNIQUE Constraint on CREATE TABLE

    The following SQL creates a UNIQUE constraint on the "P_Id" columnwhen the "Persons" table is created:

    MySQL:

    CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255)NOT NULL, FirstName varchar(255), Address varchar(255), Cityvarchar(255), UNIQUE (P_Id) )

  • 8/6/2019 DB2 Part 1

    30/45

    30

    SQL PRIMARY KEY Constraint

    The PRIMARY KEY constraint uniquely identifies each record ina database table.

    Primary keys must contain unique values.

    A primary key column cannot contain NULL values.

    Each table should have a primary key, and each table can have

    only one primary key. SQL PRIMARY KEY Constraint on CREATE TABLE

    The following SQL creates a PRIMARY KEY on the "P_Id" columnwhen the "Persons" table is created:

    MySQL:

    CREATE TABLE Persons ( P_Id int NOT NULL, LastNamevarchar(255) NOT NULL, FirstName varchar(255), Addressvarchar(255), City varchar(255), PRIMARY KEY (P_Id) )

  • 8/6/2019 DB2 Part 1

    31/45

    31

    SQL FOREIGN KEY Constraint

    SQL FOREIGN KEY Constraint A FOREIGN KEY in one table points to a PRIMARY KEY in

    another table.

    CREATE TABLE Orders ( O_Id int NOT NULL, OrderNo int NOTNULL, P_Id int, PRIMARY KEY (O_Id), FOREIGN KEY (P_Id)

    REFERENCES Persons(P_Id) )SQL Server / Oracle / MS Access: CREATE TABLE Orders ( O_Id int NOT NULL PRIMARY KEY,

    OrderNo int NOT NULL, P_Id int FOREIGN KEY REFERENCESPersons(P_Id) )

  • 8/6/2019 DB2 Part 1

    32/45

    32

    Indexes

    An index can be created in a table to find data more quickly andefficiently.

    The users cannot see the indexes, they are just used to speed upsearches/queries.

    Note: Updating a table with indexes takes more time than updating atable without (because the indexes also need an update). So youshould only create indexes on columns (and tables) that will befrequently searched against. SQL CREATE INDEX Syntax

    Creates an index on a table. Duplicate values are allowed:

    CREATE INDEX index_name ON table_name (column_name)SQLCREATE UNIQUE INDEX Syntax

    Creates a unique index on a table. Duplicate values are not allowed:

    CREATE UNIQUE INDEX index_name ON table_name

    (column_name)Note: The syntax for creating indexes varies amongstdifferent databases. Therefore: Check the syntax for creating indexesin your database.

  • 8/6/2019 DB2 Part 1

    33/45

    33

    SQL NULL Values

    If a column in a table is optional, we can insert a new record orupdate an existing record without adding a value to thiscolumn. This means that the field will be saved with a NULLvalue.

    NULL values are treated differently from other values.

    NULL is used as a placeholder for unknown or inapplicablevalues.

    Note: It is not possible to compare NULL and 0; they are notequivalent.

  • 8/6/2019 DB2 Part 1

    34/45

    34

    The HAVING Clause

    The HAVING clause cheks the properties of each groupin table. Having is used in select stmt with GROUP BY clause.

    SQL HAVING Syntax

    SELECT column_name, column_function(column_name) FROMtable_name GROUP BY column_name HAVING

    column_function(column_name) operator value

  • 8/6/2019 DB2 Part 1

    35/45

    35

    Cursors

    Cursor is useful when more than one row of a table to beprocessed

    Cursor is nothing but a pointer

    Conceptually they are results table used by DB2 to

    contain the multiple results of a query.

    They are data structures which hold some/all the resultsof a query.

    Are defined in the WORKING- STORAGE SECTION/

    PROCEDURE DIVISION.

  • 8/6/2019 DB2 Part 1

    36/45

    36

    Cursors

    Cursors Notes SELECTs in the general interactive SQL may return any number of rows while

    SELECTs in embedded SQL can deal with only one row at a time. A programming device

    called a cursor allows the SELECT to find a set of rows but return them one at a time. A cursor

    could point to the row to be processed, then move to the next row for processing, and so

    on. A cursor needs to be declared using a SELECT statement. It can be declared

    both in the WORKING-STORAGE SECTION as well as in the PROCEDURE DIVISION. But, by practice it is done in WORKING-STORAGE SECTION. Cursor definition is done

    once. If it is a part of the PROCEDURE DIVISION, then the programmer should have to

    separate the

    declaration step from the other operations and should make sure that it isdone only once. So by practice it is done in WORKING-STORAGE SECTION.

  • 8/6/2019 DB2 Part 1

    37/45

    37

    Cursors

    Operations associated with a Cursor: DECLARE

    OPEN

    FETCH

    CLOSE

  • 8/6/2019 DB2 Part 1

    38/45

    38

    CURSORS

    Cursors Notes (continued) The above slide shows the operations associated with a cursor.

    The first operation is DECLARE which is used to define the cursor on aspecific set of rows

    from a table. Without doing this we cannot form a cursor. But thisdoesnt execute any SQL

    statement defined within it. For doing that, we must first open thecursor using the OPEN

    command. Then in order to fetch the rows form the result set, theFETCH statement is used

    which fetches a single row from the cursor. Finally after performingall the operations, we

    need to close the cursor by using the CLOSE statement. All these

    operations will be discussed in detail in the coming slides.

  • 8/6/2019 DB2 Part 1

    39/45

    39

    Declaring a Cursor

    EXEC SQLDECLARE EMPCUR CURSOR FOR

    SELECT EMPNO, NAME, SALARY FROM EMPLOYEE

    WHERE EMPNO >:WS-EMPNO

    END-EXEC.

    Cursors

    The first statement is the DECLARE statement. Its a non-executable statement. This is just

    the definition, DB2 executes this statement when we open it.Here we specify what should

    the cursor contain, or rather the set of rows that are being

    retrieved from the table as a result of the SQL query executed. The cursor name follows the

    DECLARE word.

  • 8/6/2019 DB2 Part 1

    40/45

    40

    Opening a Cursor

    EXEC SQLOPEN EMPCUR

    END-EXEC.

  • 8/6/2019 DB2 Part 1

    41/45

    41

    Closing a Cursor

    EXEC SQLCLOSE EMPCUR

    END-EXEC.

    Before using the cursor one must open it. The OPEN statementprepares the SELECT for

    execution. It uses the keyword OPEN followed by the cursors name.

    When OPEN cursor is done the query is executed and the result set isformed.

    The CLOSE statement releases all memory occupied by the cursor. Itis mandatory to close

    a cursor before ending a program. After a cursor has been closed, itcan be reopened

    without declaring again.

  • 8/6/2019 DB2 Part 1

    42/45

    42

    Fetching results from a cursor

    EXEC SQL FETCH EMPCUR

    INTO :WS-EMPNO,:WS-NAME,:WS-SALARY

    END-EXEC.

    Fetching results from a cursor

    Cursors (5 of 7)

    Remarks:

    We get one row at a time.

    Only forward READ till SQLCODE = 100.

  • 8/6/2019 DB2 Part 1

    43/45

    43

    Cursors-FETCH

    The FETCH statement identifies the cursor to be used andemploys an INTO clause to

    indicate the host variables that are to receive the values fromeach row.

    A FETCH statement is coded within a loop as we get one row at

    a time. DB2 communicates with the programs about processing status

    through SQLCODE as

    discussed earlier. Like, the program can test for SQLCODE =100 and move out of the loop

    when it is encountered.

  • 8/6/2019 DB2 Part 1

    44/45

    44

    Exercise

    Which SQL statement is used to extract data from a database?OPEN SELECT GET EXTRACT Which SQL statement is used to update data in a database?

    SAVE AS MODIFY

    SAVE UPDATE Which SQL statement is used to delete data from a database?

    COLLAPSE REMOVE DELETE Which SQL statement is used to insert new data in a database?

    ADD RECORD ADD NEW INSERT NEW INSERT INTO

  • 8/6/2019 DB2 Part 1

    45/45

    45

    Exercise

    With SQL, how do you select a column named "FirstName" from a table named "Persons"?SELECT Persons.FirstName

    EXTRACT FirstName FROM Persons SELECT FirstName FROM Persons . With SQL, how do you select all the columns from a table named "Persons"?

    SELECT [all] FROM Persons SELECT * FROM Persons SELECT Persons SELECT *.Persons

    With SQL, how do you select all the records from a table named "Persons" where the valueof the column "FirstName" is "Peter"?SELECT [all] FROM Persons WHERE FirstName LIKE 'Peter

    SELECT * FROM Persons WHERE FirstName='Peter SELECT * FROM Persons WHERE FirstName'Peter SELECT [all] FROM Persons WHERE FirstName='Peter With SQL, how do you select all the records from a table named "Persons" where the value

    of the column "FirstName" starts with an "a"?SELECT * FROM Persons WHERE FirstName LIKE '%a

    SELECT * FROM Persons WHERE FirstName LIKE 'a% SELECT * FROM Persons WHERE FirstName='%a% SELECT * FROM Persons WHERE FirstName='a'