Useful Pointers


Getting started on DB2 at UCLA


The DB2 Bulk Loader: Using the DB2 Bulk Loader


 Two examples are to be added soon!


Non-SQL2 Features of DB2


Basic SQL Features (nothing yet)

Indexes

Data Types

Constraints

Embedded SQL


DB2 Dates and Times


Dates datatype




Overview

All CS240A students should log in at least once and change their password for safety.

Logging into DB2

Right now the DB2 UDB server is running on koi.cs.ucla.edu. A sample session could be

Enjoy the powerful DB2 SQL.

Changing Your Password

DB2 UDB server relies on UNIX operating system for user authentication. Be sure to keep your UNIX password in secret.

Creating a Table

Since tables are the basic objects that are used to store the information in V2, the most fundumental data
definition statement is the CREATE TABLE statement. The basic job of a CREATE TABLE statement is to
specify the name of the table to be created and the names and datatypes of all its columns. In addition, the statement
can optionally specify that certain columns of the table do not accept null values and that one or more columns
constitute the primary key of the table. Primary key columns never accept null values, and the values of the
primary key columns uniquely identify a row of the table. CREATE TABLE statement also has more advanced
features that are not discussed here.

Examples:

CREATE TABLE parts
    (partno Char(4) NOT NULL PRIMARY KEY,
     description Varchar(20),
     qonhand  Integer,
     qonorder Integer);
CREATE TABLE quoations
     (suppno Char(3) NOT NULL,
      partno  Char(4) NOT NULL,
      price Integer,
      responsetime Integer,
      PRIMARY KEY (suppno, partno) );
As you can see from the examples, a CREATE TABLE statement contains a parenthesized list of column names with a datatype specified for each column. If a column does not accept null values, the phrase NOT NULL is specified after its datatype. An optional PRIMARY KEY clause identifies the columns that constitute the primary key of the table. Every column that is identified as part of the primary key must also have a NOT NULL designation. When you create a table, a description of the table is stored in the system catalog table named TABLES and descriptions of its columns are stored in the catalog table named COLUMNS.

Inserting Tuples

The purpose of the INSERT statement is to insert one or more rows into a table or view. The rows to be inseted can be specified as a literal table or can be derived from the database by means of a query. Users of SQL are familiar with the use of a VALUES clause to insert a single row into a table, as in the following example:

 INSERT INTO quotations(suppno, partno, price, responsetime)
    VALUES ('S59', 'P227' , 175, 8);
Since V2 allows an INSERT statement to contain a literal table, the VALUES clause in an INSERT statement is nonlonger limited to a single row, and it may contain expressions as well as constants. Furthermore, when a literal table is used in an INSERT statement, a value inside the literal table may consist simply of the word DEFAULT, indicating "the default value for the target column" (the default value of a column, if any, being determined when a table is created). Some of these features are illustrated by the example below, which insets two rows into the ORDERS table, using a default value (the current date) for the ORDERDATE column.
INSERT INTO orders(suppno, partno, quantity, orderdate)
  VALUES ('S59', 'P227', 100, DEFAULT),
                  ('S59', 'P231', 250, DEFAULT);
Columns for which no values are provided by an INSERT statement receive default values. For this reason, the INSERT statement in the following example is equivalent to the one in the previous example:
INSERT INTO orders(suppno, partno, quantity)
  VALUES ('S59', 'P227', 100),
                  ('S59', 'P231', 250);
If an INSERT statement contains a query, that query is evaluated and the resulting rows are inserted into the target table. For example, if we create a table named INACTIVE with a column named SUPPNO, we might use the following statement to populate this table with all the suppliers who currently have no quotations on file:
  INSERT INTO INACTIVE (suppno)
      SELECT suppno
      FROM suppliers
 EXCEPT
      SELECT suppno
      FROM quotations;
If a query inside an INSERT statement contains a reference to the table into which the data is being inserted, the INSERT statement is said to be self-referencing. The query in a self-referencing INSERT statement is completely evaluated before any rows are inserted. The target of an INSERT statement may be either a table or a view. Inserting rows into a view has the effect of inserting rows into the table on which the view is based. Of course, the view must be updatable, and the rows being inserted must satisfy any constraints that are in effect for the table and/or the view. If any error is encountered during execution of an INSERT statement (for example, some constraint is violated by the 100th row to be inseted), the statement is rolled back and no rows are inserted.

Getting the Value of a Relation

When a query is used asa top-level SQL statement, we call it a SELSECT statement. A select statement can be submitted to an interactive interface such as the CLP (Command Line Processor), which will execute it and display the result. In addition to the normal query clauses, a SELECT statement may have an additional clause that is meaningful only for top-level queries. That caluse is called an ORDER BY clause and is used to impose an ordering on the result set, controlling the order in which the result rows are displayed. The result set of a query can be ordered by the values of one or more of its columns, in either ascending or desending order. Each of the columns in the ORDER BY clause must correspond to one of the expressions in the SELECT clause. These expressions can be identified in several ways, as shown in the following examples. If a simple column name is selected, that column name can be used in the ORDER BY clause. The following query lists all the quotations for part number P231 that have a response time of less than ten days, in order by price from the least expensive to the most expensive.

    SELECT  suppno, price
    FROM  quotations
    WHERE partno = "p231"
    AND responsetime < 10
    ORDER BY price;
A column name in the SELECT clause that is qualified by a table name or correlation name can also appear in the ORDER BY clause, just as it appears in the SELECT clause. The following example joins three tables to make a master list of the parts that are supplied by the various suppliers. The rows of the result set are ordered alphabetically by the name of the supplier, and secondarily ordered by part number.
    SELECT s.name, q.partno, q.price, i.description
    FROM suppliers s, quotations q, parts i
    WHERE s.suppno = q.suppno
    AND q.partno = i.partno
    ORDER BY s.name, q.partno;
An expression in the SELECT clause that is not a simple column name can be given a name by using the keyword AS, and this name can be used in the ORDER BY clause. The following query lists parts in descending order by the total number of each part that is on hand or on order.
   SELECT partno, qonorder+qonhand AS totalq
   FROM parts
   ORDER BY totalq DESC;
If an expression in the SELECT clause is not given a name, it can be referred to in the ORDER BY clause by an integer that represents its ordinal position in the SELSECT clause. The following query lists the parts that are currently out of stock, in descending order by their average prices.
  SELECT partno, avg(price)
  FROM quotations
  WHERE partno IN
       (SELECT partno
        FROM parts
        WHERE qonhand = 0)
 GROUP BY partno
 ORDER BY 2 DESC;
When a SELECT statement includes multiple query blocks, remember that the ORDER BY clause is a property of the statement as a whole, not of any individual query block. The following query produces an ordered list of supplier numbers for suppliers who either have an order pending for part number P221 or who can supply this part in ten days or less:
    SELECT suppno
    FROM orders
    WHERE partno = 'P221'
UNION ALL
    SELECT suppno
    FROM  quaotations
    WHERE partno = 'P221'
    AND responsetime <= 10
ORDER BY suppno;

Getting Rid of Your Tables

Tables, views, and other object can be removed from the database by means of a DROP statement. Examples:

     DROP TABLE accounts.receivable;
     DROP VIEW overdue;
     DROP PACKAGE  payroll;
When you drop an object such as a table, view, or index, you may affect other objects that depend on the object you have dropped. For example, if you drop a table that is used in a view definition, that view definition will no longer be valid, and if you drop an index that is being used by a package, that package must be rebound before it can be executed. In some cases, the system will automatically repair the dependent objects (for example, a package that depends on a dropped index wil automatically be rebound to use some other access plan). In other cases dropping an object causes dependent objects to be dropped also (for example, dropping a table automatically drops all indexes difined on that table). In still other cases, you are not allowed to drop an object if other objects are depending on it. In general, dependency is a complex subject.

Getting Information About Your Database

Quitting DB2

Just issue "quit;" (or "terminate;") command.

Executing DB2 from a File: Using the Command Line Processor

CLP is the basic tool provided by V2 for interactively executing SQL statements and system commands. The CLP can take its input either from the keyboard of from a file, and can direct its output either to your display or to a file. The CLP is invoked by typing the command db2 at your operating system prompt or, if your operator has a GUI, by double-clicking on the "Command Line Processor" icon in the "DB2" group. The three forms of the db2 command are as follows:

  1. If you follow the word db2 with an SQL statement or system command, the CPL will execute that statement or command and display the result.
  2. If you follow the word db2 with the option -f filename, the CLP will take its input from the named file, processing all the commands in the file one after another. For example, the following command directs the CLP to process all the statements in the file named monday.clp:
       db2 -f monday.clp
    
  3. If you simply type db2 followed by neither the -f option nor a command, the CLP will go into interactive mode and will prompt you to enter SQL statements or commnads, one at a time, at the keyboard. The simplest form of the db2 command is as follows:
  db2
While the CLP is executing in the interactive mode, it prompts you for input by means of a prompt that looks like this:
  db2 =>
When you are using the CLP to execute a series of SQL statements in a file, the !echo command can be used to generate text into the output stream, perhaps to serve as labels on the results of your queries. The CLP will not be able to access any data until the database server has been started. The server can be started bya a db2start command, which can be executed by a suitably authorized user either at the CLP prompt or at the operating system prompt, or by double-clicking on the "Start DB2" icon in your operating systems GUI. A CLP session can be ended by a TERMINATE command.

Editing Commands in the Buffer

Recording Your Session

Help Facilities

At any time during a CLP session, you can use the "?" command to browse the online documentation that is provided with your V2 system. To obtain help about a given subject, simply type HELP followed by a word or phrase, such as the following:

  ? CREATE TRIGGER;
The system will open a window to display the relevant page from one of the online manuals. If you do not specify any word or phrase, or if no specific help is found for the word or phrase you specified, the system will open a window on the table of contents of the DB2 SQL Reference. You can you use the online help facility to browse through manuals, perform content searches, and follow hypertext links.


Basic SQL Features

Indexes

An index is an access aid that can be created on a table, using one or more columns of the table as the key columns of the index. You can create as many indexes on the table as you like, using the various combinations of columns as keys. Finding an optimum set of indexes to mainatain in your database is an art that you will learn by experience. Indexes are created by the CREATE INDEX statement, as the following examples illustrate:

     CREATE INDEX  i1 ON suppliers(name);
     CREATE UNIQUE INDEX i2 ON quotations(partno, suppno);
     CREATE INDEX i3 ON quotations(partno ASC, price DESC);
The keywords ASC and DESC denote ascending and descending order, respectively. There are certain limitations on the creation of indexes. An index may not have more than 16 key columns, and the sum of the lengths of the key columns (including a small allowance for system overhead) may not exceed 255 bytes. If you attempt to create a unique index on a set of columns that already contains nonunique values, the index creation will fail.

Data Types

Basic Single-byte SQL Datatypes: Smallint, Integer, Decimal(p,s), Double, 
                  Char(n), Varchar(n), Date, Time, Timestamp.

Basic Double-byte SQL Datatypes:  Graphic(n), Vargraphic(n).

Large Objects: Blob(Binary Large Object), Clob(Character Large Object), 
               Dbclob(Double-Byte Character Large Object).
Users can also create a new datatype of their own, called a distinct type, to suppliment the system's built-in datatypes.

Constraints

In V2, each constraint is associated with a specific table in the database and protects the validity of data values in that table. Name of the constraint is used by the system in error messages whenever the constraint is violated. If you create a constraint and do not give it a name, the system will generate a name for the constraint automatically.

Embedded SQL

The host programming languages supported by V2 are C, C++, COBOL, FORTRAN, REXX.




Dates datatype

DB2 DATE datatypes are very similar to the SQL-92 standard:

Date             Consists of a year, month, and day.
Time             Consists of an hour, minute, and second.
Timestamp        Consists of a year, month,day, hour,minute,second, and microsecond.