DB2 – Schemas

DB2 – Schemas ”; Previous Next This chapter introduces and describes the concept of Schema. Introduction A schema is a collection of named objects classified logically in the database. In a database, you cannot create multiple database objects with same name. To do so, the schema provides a group environment. You can create multiple schemas in a database and you can create multiple database objects with same name, with different schema groups. A schema can contain tables, functions, indices, tablespaces, procedures, triggers etc. For example, you create two different schemas named as “Professional” and “Personal” for an “employee” database. It is possible to make two different tables with the same name “Employee”. In this environment, one table has professional information and the other has personal information of employee. In spite of having two tables with the same name, they have two different schemas “Personal” and “Professional”. Hence, the user can work with both without encountering any problem. This feature is useful when there are constraints on the naming of tables. Let us see few commands related to Schema: Getting currently active schema Syntax: db2 get schema Example: [To get current database schema] db2 get schema Setting another schema to current environment Syntax: db2 set schema=<schema_name> Example: [To arrange ‘schema1’ to current instance environment] db2 set schema=schema1 Creating a new Schema Syntax: [To create a new schema with authorized user id] db2 create schema <schema_name> authroization <inst_user> Example: [To create “schema1” schema authorized with ‘db2inst2”] db2 create schema schema1 authorization db2inst2 Exercise Let us create two different tables with same name but two different schemas. Here, you create employee table with two different schemas, one for personal and the other for professional information. Step 1: Create two schemas. Schema 1: [To create schema named professional] db2 create schema professional authorization db2inst2 Schema 2: [To create schema named personal] db2 create schema personal authorization db2inst2 Step 2: Create two tables with the same name for Employee details Table1: professional.employee [To create a new table ‘employee’ in the database using schema name ‘professional’] db2 create table professional.employee(id number, name varchar(20), profession varchar(20), join_date date, salary number); Table2: personal.employee [To create a new table ‘employee’ in the same database, with schema name ‘personal’] db2 create table personal.employee(id number, name varchar(20), d_birth date, phone bigint, address varchar(200)); After executing these steps, you get two tables with same name ’employee’, with two different schemas. Print Page Previous Next Advertisements ”;

DB2 – Backup and Recovery

DB2 – Backup and Recovery ”; Previous Next This chapter describes backup and restore methods of database. Introduction Backup and recovery methods are designed to keep our information safe. In Command Line Interface (CLI) or Graphical User Interface (GUI) using backup and recovery utilities you can take backup or restore the data of databases in DB2 UDB. Logging Log files consist of error logs, which are used to recover from application errors. The logs keep the record of changes in the database. There are two types of logging as described below: Circular logging It is a method where the old transaction logs are overwritten when there is a need to allocate a new transaction log file, thus erasing the sequences of log files and reusing them. You are permitted to take only full back-up in offline mode. i.e., the database must be offline to take the full backup. Archive logging This mode supports for Online Backup and database recovery using log files called roll forward recovery. The mode of backup can be changed from circular to archive by setting logretain or userexit to ON. For archive logging, backup setting database require a directory that is writable for DB2 process. Backup Using Backup command you can take copy of entire database. This backup copy includes database system files, data files, log files, control information and so on. You can take backup while working offline as well as online. Offline backup Syntax: [To list the active applications/databases] db2 list application Output: Auth Id Application Appl. Application Id DB # of Name Handle Name Agents ——– ————– ———- ——————— —————————————– ——– —– DB2INST1 db2bp 39 *LOCAL.db2inst1.140722043938 ONE 1 Syntax: [To force application using app. Handled id] db2 “force application (39)” Output: DB20000I The FORCE APPLICATION command completed successfully. DB21024I This command is asynchronous and may not be effective immediately. Syntax: [To terminate Database Connection] db2 terminate Syntax: [To deactivate Database] db2 deactivate database one Syntax: [To take the backup file] db2 backup database <db_name> to <location> Example: db2 backup database one to /home/db2inst1/ Output: Backup successful. The timestamp for this backup image is : 20140722105345 Online backup To start, you need to change the mode from Circular logging to Archive Logging. Syntax: [To check if the database is using circular or archive logging] db2 get db cfg for one | grep LOGARCH Output: First log archive method (LOGARCHMETH1) = OFF Archive compression for logarchmeth1 (LOGARCHCOMPR1) = OFF Options for logarchmeth1 (LOGARCHOPT1) = Second log archive method (LOGARCHMETH2) = OFF Archive compression for logarchmeth2 (LOGARCHCOMPR2) = OFF Options for logarchmeth2 (LOGARCHOPT2) = In the above output, the highlighted values are [logarchmeth1 and logarchmeth2] in off mode, which implies that the current database in “CIRCULLAR LOGGING” mode. If you need to work with ‘ARCHIVE LOGGING’ mode, you need to change or add path in the variables logarchmeth1 and logarchmeth2 present in the configuration file. Updating logarchmeth1 with required archive directory Syntax: [To make directories] mkdir backup mkdir backup/ArchiveDest Syntax: [To provide user permissions for folder] chown db2inst1:db2iadm1 backup/ArchiveDest Syntax: [To update configuration LOGARCHMETH1] db2 update database configuration for one using LOGARCHMETH1 ”DISK:/home/db2inst1/backup/ArchiveDest” You can take offline backup for safety, activate the database and connect to it. Syntax: [To take online backup] db2 backup database one online to /home/db2inst1/onlinebackup/ compress include logs Output: db2 backup database one online to /home/db2inst1/onlinebackup/ compress include logs Verify Backup file using following command: Syntax: db2ckbkp <location/backup file> Example: db2ckbkp /home/db2inst1/ONE.0.db2inst1.DBPART000.20140722112743.001 Listing the history of backup files Syntax: db2 list history backup all for one Output: List History File for one Number of matching file entries = 4 Op Obj Timestamp+Sequence Type Dev Earliest Log Current Log Backup ID — — —————— —- — ———— ———— ————– B D 20140722105345001 F D S0000000.LOG S0000000.LOG ———————————————————— —————- Contains 4 tablespace(s): 00001 SYSCATSPACE 00002 USERSPACE1 00003 SYSTOOLSPACE 00004 TS1 ———————————————————— —————- Comment: DB2 BACKUP ONE OFFLINE Start Time: 20140722105345 End Time: 20140722105347 Status: A ———————————————————— —————- EID: 3 Location: /home/db2inst1 Op Obj Timestamp+Sequence Type Dev Earliest Log Current Log Backup ID — — —————— —- — ———— ———— ————– B D 20140722112239000 N S0000000.LOG S0000000.LOG ———————————————————— ————————————————————- ——————————- Comment: DB2 BACKUP ONE ONLINE Start Time: 20140722112239 End Time: 20140722112240 Status: A ———————————————————— —————- EID: 4 Location: SQLCA Information sqlcaid : SQLCA sqlcabc: 136 sqlcode: -2413 sqlerrml: 0 sqlerrmc: sqlerrp : sqlubIni sqlerrd : (1) 0 (2) 0 (3) 0 (4) 0 (5) 0 (6) 0 sqlwarn : (1) (2) (3) (4) (5) (6) (7) (8) (9) (10) (11) sqlstate: Op Obj Timestamp+Sequence Type Dev Earliest Log Current Log Backup ID — — —————— —- — ———— ———— ————– B D 20140722112743001 F D S0000000.LOG S0000000.LOG ———————————————————— —————- Contains 4 tablespace(s): 00001 SYSCATSPACE 00002 USERSPACE1 00003 SYSTOOLSPACE 00004 TS1 ————————————————————- —————- Comment: DB2 BACKUP ONE OFFLINE Start Time: 20140722112743 End Time: 20140722112743 Status: A ————————————————————- —————- EID: 5 Location: /home/db2inst1 Op Obj Timestamp+Sequence Type Dev Earliest Log Current Log Backup ID ————————————————————- —————- R D 20140722114519001 F 20140722112743 ———————————————————— —————- Contains 4 tablespace(s): 00001 SYSCATSPACE 00002 USERSPACE1 00003 SYSTOOLSPACE 00004 TS1 ———————————————————— —————- Comment: RESTORE ONE WITH RF Start Time: 20140722114519 End Time: 20140722115015 Status: A ———————————————————— —————- EID: 6 Location: Restoring the database from backup To restore the database from backup file, you need to follow the given syntax: Syntax: db2 restore database <db_name> from <location> taken at <timestamp> Example: db2 restore database one from /home/db2inst1/ taken at 20140722112743 Output: SQL2523W Warning! Restoring to an existing database that is different from the database on the backup image, but have matching names. The target database will be overwritten by the backup version. The Roll-forward recovery logs associated with the target database will be deleted. Do you want to continue ? (y/n) y DB20000I The RESTORE DATABASE command completed successfully. Roll forward all the logs located in the log directory, including latest changes just before the disk drive failure. Syntax: db2 rollforward db <db_name> to end of logs and stop Example: db2 rollforward db one to end of logs and stop

DB2 – Constraints

DB2 – Constraints ”; Previous Next This chapter describes various constraints in the database. Introduction To enforce database integrity, a set of rules is defined, called constraints. The constraints either permit or prohibit the values in the columns. In a Real time database activities, the data should be added with certain restrictions. For example, in a sales database, sales-id or transaction-id should be unique. The constraints types are: NOT NULL Unique Primary key Foreign Key Check Informational Constraints are only associated with tables. They are applied to only particular tables. They are defined and applied to the table at the time of table creation. Explanation of each constraint: NOT NULL It is a rule to prohibit null values from one or more columns within the table. Syntax: db2 create table <table_name>(col_name col_type not null,..) Example: [To create a sales table, with four columns (id, itemname, qty, price) in this adding “not null” constraints to all columns to avoid forming any null cell in the table.] db2 create table shopper.sales(id bigint not null, itemname varchar(40) not null, qty int not null,price double not null) Inserting NOT NULL values into table You can insert values in the table as shown below: Example: [ERRORoneous Query] db2 insert into shopper.sales(id,itemname,qty) values(1,”raagi”,12) Output: [Correct query] DB21034E The command was processed as an SQL statement because it was not a valid Command Line Processor command. During SQL processing it returned: SQL0407N Assignment of a NULL value to a NOT NULL column “TBSPACEID=5, TABLEID=4, COLNO=3″ is not allowed. SQLSTATE=23502 Example: [Correct query] db2 insert into shopper.sales(id,itemname,qty,price) values(1,”raagi”,12, 120.00) db2 insert into shopper.sales(id,itemname,qty,price) values(1,”raagi”,12, 120.00) Output: DB20000I The SQL command completed successfully. Unique constraints Using these constraints, you can set values of columns uniquely. For this, the unique constraints are declared with “not null” constraint at the time of creating table. Syntax: db2 create table <tab_name>(<col> <col_type> not null unique, …) Example: db2 create table shopper.sales1(id bigint not null unique, itemname varchar(40) not null, qty int not null,price double not null) Inserting the values into table Example: To insert four different rows with unique ids as 1, 2, 3 and 4. db2 insert into shopper.sales1(id, itemname, qty, price) values(1, ”sweet”, 100, 89) db2 insert into shopper.sales1(id, itemname, qty, price) values(2, ”choco”, 50, 60) db2 insert into shopper.sales1(id, itemname, qty, price) values(3, ”butter”, 30, 40) db2 insert into shopper.sales1(id, itemname, qty, price) values(4, ”milk”, 1000, 12) Example: To insert a new row with “id” value 3 db2 insert into shopper.sales1(id, itemname, qty, price) values(3, ”cheese”, 60, 80) Output: when you try to insert a new row with existed id value it will show this result: DB21034E The command was processed as an SQL statement because it was not a valid Command Line Processor command. During SQL processing it returned: SQL0803N One or more values in the INSERT statement, UPDATE statement, or foreign key update caused by a DELETE statement are not valid because the primary key, unique constraint or unique index identified by “1” constrains table “SHOPPER.SALES1″ from having duplicate values for the index key. SQLSTATE=23505 Primary key Similar to the unique constraints, you can use a “primary key” and a “foreign key” constraint to declare relationships between multiple tables. Syntax: db2 create table <tab_name>( ,.., primary key ()) Example: To create ‘salesboys’ table with “sid” as a primary key db2 create table shopper.salesboys(sid int not null, name varchar(40) not null, salary double not null, constraint pk_boy_id primary key (sid)) Foreign key A foreign key is a set of columns in a table which are required to match at least one primary key of a row in another table. It is a referential constraint or referential integrity constraint. It is a logical rule about values in multiple columns in one or more tables. It enables required relationship between the tables. Earlier, you created a table named “shopper.salesboys” . For this table, the primary key is “sid”. Now you are creating a new table that has sales boy’s personal details with different schema named “employee” and table named “salesboys”. In this case, “sid” is the foreign key. Syntax: db2 create table <tab_name>(<col> <col_type>,constraint <const_name> foreign key (<col_name>) reference <ref_table> (<ref_col>) Example: [To create a table named ‘salesboys’ with foreign key column ‘sid’] db2 create table employee.salesboys( sid int, name varchar(30) not null, phone int not null, constraint fk_boy_id foreign key (sid) references shopper.salesboys (sid) on delete restrict ) Example: [Inserting values into primary key table “shopper.salesboys”] db2 insert into shopper.salesboys values(100,”raju”,20000.00), (101,”kiran”,15000.00), (102,”radha”,10000.00), (103,”wali”,20000.00), (104,”rayan”,15000.00) Example: [Inserting values into foreign key table “employee.salesboys” [without error]] db2 insert into employee.salesboys values(100,”raju”,98998976), (101,”kiran”,98911176), (102,”radha”,943245176), (103,”wali”,89857330), (104,”rayan”,89851130) If you entered an unknown number, which is not stored in “shopper.salesboys” table, it will show you SQL error. Example: [error execution] db2 insert into employee.salesboys values(105,”rayan”,89851130) Output: DB21034E The command was processed as an SQL statement because it was not a valid Command Line Processor command. During SQL processing it returned: SQL0530N The insert or update value of the FOREIGN KEY “EMPLOYEE.SALESBOYS.FK_BOY_ID” is not equal to any value of the parent key of the parent table. SQLSTATE=23503 Checking constraint You need to use this constraint to add conditional restrictions for a specific column in a table. Syntax: db2 create table ( primary key (), constraint check (condition or condition) ) Example: [To create emp1 table with constraints values] db2 create table empl (id smallint not null, name varchar(9), dept smallint check (dept between 10 and 100), job char(5) check (job in (”sales”, ”mgr”, ”clerk”)), hiredate date, salary decimal(7,2), comm decimal(7,2), primary key (id), constraint yearsal check (year(hiredate) > 1986 or salary > 40500) ) Inserting values You can insert values into a table as shown below: db2 insert into empl values (1,”lee”, 15, ”mgr”, ”1985-01-01” , 40000.00, 1000.00) Dropping the constraint Let us see the syntaxes for dropping various constraints. Dropping UNIQUE constraint Syntax: db2 alter table <tab_name> drop unique <const_name> Dropping primary key Syntax: db2 alter table <tab_name> drop primary key Dropping check constraint Syntax: db2 alter table <tab_name> drop

DB2 – Server Installation

DB2 – Server Installation ”; Previous Next This chapter describes installation steps of DB2 server. Introduction You can download the DB2 Server trial version or purchase the product license from www.ibm.com. There are two separate DB2 servers available for downloading, depending upon the size of operating system, on which it is intended to execute. For example, if you want to download a DB2 server for 32bit Linux or UNIX operating system, then you need to download a 32 bit DB2 server. The same applies for 64bit DB2 server. Hardware requirements Processor : Minimum Core 2Duo Ram : 1GB minimum Hard disk : 30GB minimum Software requirements Before installing the DB2 server, your system needs to get ready with the required software on it. For Linux, you need to install “libstdc++6.0”. Checking system compatibility Before installing DB2 Server, you need to verify if your system is compatible with the DB2 server. For confirming the compatibility, you need to call ”db2prereqcheck” command on command console. Installing DB2 on Linux operating system Open the Terminal and set the db2 installation image folder path on console using “CD <DB2 installation folder>” command. Then type “./db2prereqcheck” command, which confirms the compatibility of your system with DB2 server. ./db2prereqcheck Figure-1 shows the compatibility requirements of Linux operating system and hardware system. Follow the given steps for installing DB2 on your Linux system: Open the terminal. Login as root user. Open DB2 Installation folder. Type “./db2setup” and press Enter. This process will start execution of DB2 server setup. Type “./db2setup” and press Enter on root terminal to start setup process of DB2 Server. On doing so, the “Set up Launch Pad” screen appears. [Figure-2] On Setup Launch pad page, select “Install a Product” option from left side menu. Select option “DB2 Advanced Enterprise Server Edition”. Select “Install New” Button. A new frame appears with name “DB2 setup wizard”. Click “Next”. [Figure-3] The next screen appears with DB2 license agreement. Select “I accept the terms…” Click “Next”. [Figure-4] Next screen comes up with offer of Installation type, which is set to “Typical” by default. Keep the same selection. Click “Next”. [Figure-5] The next screen appears with installation action. Select “Install DB2 Advanced Enterprise Server Edition…” Click “Next”. [Figure-6] On the next screen, the setup program asks for selection of installation directory. Keep the default and click “Next”. The next screen comes up with the user authentication. Enter your password for “dasusr1” user. (Your password can be identical to username so that it is convenient to remember.) On the following screen, the setup asks you for creation of DB2 Server Instance. Here, it is creating a DB2 instance with name “db2inst1”. The next screen asks you the number of partitions you require for your default instance. You have a choice of “single or Multiple” partitions. Select “single partition instance”. Click “next”. On the next screen, the setup asks you for authentication for DB2 instance being created. Here, by default username is created as “db2inst1”. You can enter password same as username. Click “Next”. On the next screen, the setup asks to enter authentication information for “db2fenc” user. Here, you can enter password same as username. Click “Next”. On the next screen, you can select “Do not setup your db2 server to send notifications at this time” option. Click ”Next”. The next screen shows you the information about db2 setup. Click “Finish”. The DB2 Installation procedure is complete at this stage. Verifying DB2 installation You need to verify the installation of DB2 server for its usefulness. On completing the DB2 Server installation, logout from current user mode and login to “db2inst1” user. In “db2inst1” user environment, you can open terminal and execute the following commands to verify if your db2 product is installed properly or not. db2level This command shows the current version and service level of the installed DB2 product for current instance. Syntax: db2level Example: db2level Output: DB21085I Instance “db2inst2” uses “64” bits And DB2 code release “SQL10010” with level identifier “0201010E”. Informational tokens are “DB2 v10.1.0.0”, “s120403”, “LINUXAMD64101”, and Fix Pack “0”. Product is installed at “/home/db2inst2/sqllib”. db2licm This command shows all the license related information of our DB2 Product. Syntax: db2licm <parameter> Example: db2licm -l Output: Product name: “DB2 Advanced Enterprise Server Edition” License type: “Trial” Expiry date: “10/02/2014” Product identifier: “db2aese” Version information: “10.1” Product name: “DB2 Connect Server” License type: “Trial” Expiry date: “10/02/2014” Product identifier: “db2consv” Version information: “10.1” Command Line Processor (CLP) The CLP can be started in one of the three modes: Command mode: In this mode, each command and SQL statement must be prefixed by “db2”. For example, query “db2 activate database sample”. Interactive input mode: you can launch this mode by using the “db2” command. Here, you can pass SQL statements without prefix. For example, “activate database sample”. Batch mode: Here, you need to create a script file, which contains all SQL queries of requirements and save the file with “.db2” extension. You can call this in command line using syntax “db2 –tf <filename.db2>”. Print Page Previous Next Advertisements ”;

DB2 – Database Security

DB2 – Database Security ”; Previous Next This chapter describes database security. Introduction DB2 database and functions can be managed by two different modes of security controls: Authentication Authorization Authentication Authentication is the process of confirming that a user logs in only in accordance with the rights to perform the activities he is authorized to perform. User authentication can be performed at operating system level or database level itself. By using authentication tools for biometrics such as retina and figure prints are in use to keep the database from hackers or malicious users. The database security can be managed from outside the db2 database system. Here are some type of security authentication process: Based on Operating System authentications. Lightweight Directory Access Protocol (LDAP) For DB2, the security service is a part of operating system as a separate product. For Authentication, it requires two different credentials, those are userid or username, and password. Authorization You can access the DB2 Database and its functionality within the DB2 database system, which is managed by the DB2 Database manager. Authorization is a process managed by the DB2 Database manager. The manager obtains information about the current authenticated user, that indicates which database operation the user can perform or access. Here are different ways of permissions available for authorization: Primary permission: Grants the authorization ID directly. Secondary permission: Grants to the groups and roles if the user is a member Public permission: Grants to all users publicly. Context-sensitive permission: Grants to the trusted context role. Authorization can be given to users based on the categories below: System-level authorization System administrator [SYSADM] System Control [SYSCTRL] System maintenance [SYSMAINT] System monitor [SYSMON] Authorities provide of control over instance-level functionality. Authority provide to group privileges, to control maintenance and authority operations. For instance, database and database objects. Database-level authorization Security Administrator [SECADM] Database Administrator [DBADM] Access Control [ACCESSCTRL] Data access [DATAACCESS] SQL administrator. [SQLADM] Workload management administrator [WLMADM] Explain [EXPLAIN] Authorities provide controls within the database. Other authorities for database include with LDAD and CONNECT. Object-Level Authorization: Object-Level authorization involves verifying privileges when an operation is performed on an object. Content-based Authorization: User can have read and write access to individual rows and columns on a particular table using Label-based access Control [LBAC]. DB2 tables and configuration files are used to record the permissions associated with authorization names. When a user tries to access the data, the recorded permissions verify the following permissions: Authorization name of the user Which group belongs to the user Which roles are granted directly to the user or indirectly to a group Permissions acquired through a trusted context. While working with the SQL statements, the DB2 authorization model considers the combination of the following permissions: Permissions granted to the primary authorization ID associated with the SQL statements. Secondary authorization IDs associated with the SQL statements. Granted to PUBLIC Granted to the trusted context role. Instance level authorities Let us discuss some instance related authorities. System administration authority (SYSADM) It is highest level administrative authority at the instance-level. Users with SYSADM authority can execute some databases and database manager commands within the instance. Users with SYSADM authority can perform the following operations: Upgrade a Database Restore a Database Update Database manager configuration file. System control authority (SYSCTRL) It is the highest level in System control authority. It provides to perform maintenance and utility operations against the database manager instance and its databases. These operations can affect system resources, but they do not allow direct access to data in the database. Users with SYSCTRL authority can perform the following actions: Updating the database, Node, or Distributed Connect Service (DCS) directory Forcing users off the system-level Creating or Dropping a database-level Creating, altering, or dropping a table space Using any table space Restoring Database System maintenance authority (SYSMAINT) It is a second level of system control authority. It provides to perform maintenance and utility operations against the database manager instance and its databases. These operations affect the system resources without allowing direct access to data in the database. This authority is designed for users to maintain databases within a database manager instance that contains sensitive data. Only Users with SYSMAINT or higher level system authorities can perform the following tasks: Taking backup Restoring the backup Roll forward recovery Starting or stopping instance Restoring tablespaces Executing db2trc command Taking system monitor snapshots in case of an Instance level user or a database level user. A user with SYSMAINT can perform the following tasks: Query the state of a tablespace Updating log history files Reorganizing of tables Using RUNSTATS (Collection catalog statistics) System monitor authority (SYSMON) With this authority, the user can monitor or take snapshots of database manager instance or its database. SYSMON authority enables the user to run the following tasks: GET DATABASE MANAGER MONITOR SWITCHES GET MONITOR SWITCHES GET SNAPSHOT LIST LIST ACTIVE DATABASES LIST APPLICATIONS LIST DATABASE PARTITION GROUPS LIST DCS APPLICATIONS LIST PACKAGES LIST TABLES LIST TABLESPACE CONTAINERS LIST TABLESPACES LIST UTITLITIES RESET MONITOR UPDATE MONITOR SWITCHES Database authorities Each database authority holds the authorization ID to perform some action on the database. These database authorities are different from privileges. Here is the list of some database authorities: ACCESSCTRL: allows to grant and revoke all object privileges and database authorities. BINDADD: Allows to create a new package in the database. CONNECT: Allows to connect to the database. CREATETAB: Allows to create new tables in the database. CREATE_EXTERNAL_ROUTINE: Allows to create a procedure to be used by applications and the users of the databases. DATAACCESS: Allows to access data stored in the database tables. DBADM: Act as a database administrator. It gives all other database authorities except ACCESSCTRL, DATAACCESS, and SECADM. EXPLAIN: Allows to explain query plans without requiring them to hold the privileges to access the data in the tables. IMPLICIT_SCHEMA: Allows a user to create a schema implicitly by creating an object using a CREATE statement. LOAD: Allows to load data into table. QUIESCE_CONNECT: Allows to access the

DB2 – Tables

DB2 – Tables ”; Previous Next Tables are logical structure maintained by Database manager. In a table each vertical block called as column (Tuple) and each horizontal block called as row (Entity). The collection of data stored in the form of columns and rows is known as a table. In tables, each column has different data type. Tables are used to store persistent data. Type of tables Base Tables: They hold persistent data. There are different kinds of base tables, including: Regular Tables: General purpose tables, Common tables with indexes are general purpose tables. Multidimensional Clustering Table (MDC): This type of table physically clustered on more than one key, and it used to maintain large database environments. These type of tables are not supported in DB2 pureScale. Insert time clustering Table (ITC): Similar to MDC tables, rows are clustered by the time they are inserted into the tables. They can be partitioned tables. They too, do not support pureScale environment. Range-Clustered tables Table (RCT): These type of tables provide fast and direct access of data. These are implemented as sequential clusters. Each record in the table has a record ID. These type of tables are used where the data is clustered tightly with one or more columns in the table. This type of tables also do not support in DB2 pureScale. Partitioned Tables: These type of tables are used in data organization schema, in which table data is divided into multiple storage objects. Data partitions can be added to, attached to and detached from a partitioned table. You can store multiple data partition from a table in one tablespace. Temporal Tables: History of a table in a database is stored in temporal tables such as details of the modifications done previously. Temporary Tables: For temporary work of different database operations, you need to use temporary tables. The temporary tables (DGTTs) do not appear in system catalog, XML columns cannot be used in created temporary tables. Materialized Query Tables: MQT can be used to improve the performance of queries. These types of tables are defined by a query, which is used to determine the data in the tables. Creating Tables The following syntax creates table: Syntax: [To create a new table] db2 create table <schema_name>.<table_name> (column_name column_type….) in <tablespace_name> Example: We create a table to store “employee” details in the schema of “professional”. This table has “id, name, jobrole, joindate, salary” fields and this table data would be stored in tablespace “ts1”. db2 create table professional.employee(id int, name varchar(50),jobrole varchar(30),joindate date, salary double) in ts1 Output: DB20000I The SQL command completed successfully. Listing table details The following syntax is used to list table details: Syntax: [To see the list of tables created with schemas] db2 select tabname, tabschema, tbspace from syscat.tables Example: [To see the list of tables in the current database] db2 select tabname, tabschema, tbspace from syscat.tables Output: TABNAME TABSCHEMA TBSPACE ———— ————- ——– EMPLOYEE PROFESSIONAL TS1 1 record(s) selected. Listing columns in a table The following syntax lists columns in a table: Syntax: [To see columns and data types of a table] db2 describe table <table_name> Example: [To see the columns and data types of table ‘employee’] db2 describe table professional.employee Output: Data type Column Column name schema Data type name Length Scale Nulls —— —– ——— —————– ——— —– —— ID SYSIBM INTEGER 4 0 Yes NAME SYSIBM VARCHAR 50 0 Yes JOBROLE SYSIBM VARCHAR 30 0 Yes JOINDATE SYSIBM DATE 4 0 Yes SALARY SYSIBM DOUBLE 8 0 Yes 5 record(s) selected. Hidden Columns You can hide an entire column of a table. If you call “select * from” query, the hidden columns are not returned in the resulting table. When you insert data into a table, an “INSERT” statement without a column list does not expect values for any implicitly hidden columns. These type of columns are highly referenced in materialized query tables. These type of columns do not support to create temporary tables. Creating table with hidden column The following syntax creates table with hidden columns: Syntax: [To create a table with hidden columns] db2 create table <tab_name> (col1 datatype,col2 datatype implicitly hidden) Example: [To create a ‘customer’ table with hidden columns ‘phone’] db2 create table professional.customer(custid integer not null, fullname varchar(100), phone char(10) implicitly hidden) Inserting data values in table The following syntax inserts values in the table: Syntax: [To insert values into a table] db2 insert into <tab_name>(col1,col2,…) values(val1,val2,..) Example: [To insert values in ‘customer’ table] db2 insert into professional.customer(custid, fullname, phone) values(100,”ravi”,”9898989”) db2 insert into professional.customer(custid, fullname, phone) values(101,”krathi”,”87996659”) db2 insert into professional.customer(custid, fullname, phone) values(102,”gopal”,”768678687”) Output: DB20000I The SQL command completed successfully. Retrieving values from table The following syntax retrieves values from the table: Syntax: [To retrieve values form a table] db2 select * from &lttab_name> Example: [To retrieve values from ‘customer’ table] db2 select * from professional.customer Output: CUSTID FULLNAME ———– ———————— 100 ravi 101 krathi 102 gopal 3 record(s) selected. Retrieving values from a table including hidden columns The following syntax retrieves values from selected columns: Syntax: [To retrieve selected hidden columns values from a table] db2 select col1,col2,col3 from <tab_name> Example: [To retrieve selected columns values result from a table] db2 select custid,fullname,phone from professional.customer Output: CUSTID FULLNAME PHONE ——- ——— ———— 100 ravi 9898989 101 krathi 87996659 102 gopal 768678687 3 record(s) selected. If you want to see the data in the hidden columns, you need to execute “DESCRIBE” command. Syntax: db2 describe table <table_name> show detail Example: db2 describe table professional.customer show detail Output: Column name Data type schema Data type name Column column Partitionkey code Length Scale Nulls number sequence page Hidden Default ————— ——————– ————— ——– —- —- ——– ———- ————- ——– ———– —— — CUSTID SYSIBM INTEGER 4 0 No 0 0 0 No FULLNAME SYSIBM VARCHAR 100 0 Yes 1 0 1208 No PHONE SYSIBM CHARACTER 10 0 Yes 2 0 1208 Implicitly 3 record(s) selected. Altering the type of table columns You can modify our table

DB2 – Bufferpools

DB2 – Bufferpools ”; Previous Next This chapter introduces you to Bufferpools in the database. Introduction The bufferpool is portion of a main memory space which is allocated by the database manager. The purpose of bufferpools is to cache table and index data from disk. All databases have their own bufferpools. A default bufferpool is created at the time of creation of new database. It called as “IBMDEFAULTBP”. Depending on the user requirements, it is possible to create a number of bufferpools. In the bufferpool, the database manager places the table row data as a page. This page stays in the bufferpool until the database is shutdown or until the space is written with new data. The pages in the bufferpool, which are updated with data but are not written onto the disk, are called “Dirty” pages. After the updated data pages in the bufferpool are written on the disk, the bufferpool is ready to take another data. Relationship between tablespaces and bufferpools Each table space is associated with a specific buffer pool in a database. One tablespace is associated with one bufferpool. The size of bufferpool and tablespace must be same. Multiple bufferpools allow you to configure the memory used by the database to increase its overall performance. Bufferpool sizes The size of the bufferpool page is set when you use the “CREATE DATABASE” command. If you do not specify the page size, it will take default page size, which is 4KB. Once the bufferpool is created, it is not possible to modify the page size later Listing the available bufferpools in the current database directory Syntax: [The syntax below shows all available bufferpools in database] db2 select * from syscat.bufferpools Example: [To see available bufferpools in current database] db2 select * from syscat.bufferpools Output: BPNAME BUFFERPOOLID DBPGNAME NPAGES PAGESIZE ESTORE NUMBLOCKPAGES BLOCKSIZE NGNAME ———————————————————— IBMDEFAULTBP 1 – -2 4096 N 0 0 – 1 record(s) selected. Creating the bufferpool To create a new bufferpool for database server, you need two parameters namely, “bufferpool name” and “size of page”. The following query is executed to create a new bufferpool. Syntax: [In the syntax below,‘bp_name’ indicates bufferpool name and ‘size’ indicates size for page you need to declare for bufferpools (4K,8K,16K,32K)] db2 create bufferpool <bp_name> pagesize <size> Example: [To create a new bufferpool with name “bpnew” and size “8192”(8Kb).] db2 create bufferpool bpnew pagesize 8192 Output DB20000I The SQL command completed successfully. Dropping the bufferpool Before dropping the bufferpool, it is required to check if any tablespace is assigned to it. Syntax: [To drop the bufferpool] drop bufferpool <bp_name> Example: [To drop ‘bpnew’ named bufferpool] db2 drop bufferpool bpnew Output DB20000I The SQL command completed successfully. Print Page Previous Next Advertisements ”;

DB2 – Alias

DB2 – Alias ”; Previous Next This chapter describes the creation of alias and retrieving data using alias of database objects. Introduction Alias is an alternative name for database objects. It can be used to reference the database object. You can say, it is a nick name for database objects. Alias are defined for the objects to make their name short, thereby reducing the query size and increasing readability of the query. Creating database object aliases You can create database object alias as shown below: Syntax: db2 create alias <alias_name> for <table_name> Example: Creating alias name for table “professional.customer” table db2 create alias pro_cust for professional.customer If you pass “SELECT * FROM PRO_CUST” or “SELECT * FROM PROFESSIONAL.CUSTOMER” the database server will show the same result. Syntax: [To retrieve values from a table directly with schema name] db2 select * from <schema_name>.<table_name> Example: [To retrieve values from table customer] db2 select * from professional.customer Output: CUSTID FULLNAME PHONE ——- ——— ———— 100 ravi 9898989 101 krathi 87996659 102 gopal 768678687 3 record(s) selected. Retrieving values using alias name of the table You can retrieve values from database using alias name as shown below: Syntax: [To retrieve values from table by calling alias name of the table] db2 select * from <alias_name> Example: [To retrieve values from table customer using alias name] db2 select * from pro_cust Output: CUSTID FULLNAME PHONE ——- ——— ———— 100 ravi 9898989 101 krathi 87996659 102 gopal 768678687 3 record(s) selected. Print Page Previous Next Advertisements ”;

DB2 – Storagegroups

DB2 – Storagegroups ”; Previous Next This chapter describes the Database Storagegroups. Introduction A set of Storage paths to store database table or objects, is a storage group. You can assign the tablespaces to the storage group. When you create a database, all the tablespaces take default storagegorup. The default storage group for a database is ‘IBMSTOGROUP’. When you create a new database, the default storage group is active, if you pass the “AUTOMATIC STOGROUP NO” parameter at the end of “CREATE DATABASE” command. The database does not have any default storage groups. Listing storagegroups You can list all the storagegroups in the database. Syntax: [To see the list of available storagegroups in current database] db2 select * from syscat.stogroups Example: [To see the list of available storagegorups in current database] db2 select * from syscat.stogroups Creating a storagegroup Here is a syntax to create a storagegroup in the database: Syntax: [To create a new stogroup. The ‘stogropu_name’ indicates name of new storage group and ‘path’ indicates the location where data (tables) are stored] db2 create stogroup on ‘path’ Example: [To create a new stogroup ‘stg1’ on the path ‘data1’ folder] db2 create stogroup stg1 on ‘/data1’ Output: DB20000I The SQL command completed succesfully Creating tablespace with stogroup Here is how you can create a tablespace with storegroup: Syntax: [To create a new tablespace using existed storage group] db2 create tablespace <tablespace_name> using stogroup <stogroup_name> Example: [To create a new tablespace named ‘ts1’ using existed storage group ‘stg1’] db2 create tablespace ts1 using stogroup stg1 Output: DB20000I The SQL command completed succesfully Altering a storagegroup You can alter the location of a storegroup by using following syntax: Syntax: [To shift a storage group from old location to new location] db2 alter stogroup add ‘location’, ‘location’ Example: [To modify location path from old location to new location for storage group named ‘sg1’] db2 alter stogroup sg1 add ‘/path/data3’, ‘/path/data4’ Dropping folder path of storagegroup Before dropping folder path of storagegroup, you can add new location for the storagegroup by using alter command. Syntax: [To drop old path from storage group location] db2 alter stogroup drop ‘/path’ Example: [To drop storage group location from ‘stg1’] db2 alter stogroup stg1 drop ‘/path/data1’ Rebalancing a tablespace Rebalancing the tablespace is required when we create a new folder for storagegroup or tablespaces while the transactions are conducted on the database and the tablespace becomes full. Rebalancing updates database configuration files with new storagegroup. Syntax: [To rebalance the tablespace from old storage group path to new storage group] db2 alter tablspace <ts_name> rebalance Example: [To rebalance] db2 alter tablespace ts1 rebalance Renaming a storagegroup Syntax: [To modify the name of existing storage name] db2 rename stogroup <old_stg_name> to <new_stg_name> Example: [To modify the name of storage group from ‘sg1’ to new name ‘sgroup1’] db2 rename stogroup sg1 to sgroup1 Dropping a storage group Step 1: Before dropping any storagegroup, you can assign some different storagegroup for tablespaces. Syntax: [To assign another storagegroup for table space.] db2 alter tablspace <ts_name> using stogroup <another sto_group_name> Example: [To change from one old stogroup to new stogroup named ‘sg2’ for tablespace ‘ts1’] db2 alter tablespace ts1 using stogroup sg2 Step 2: Syntax: [To drop the existing stogroup] db2 drop stogorup <stogroup_name> Example: [To drop stogroup ‘stg1’ from database] db2 drop stogroup stg1 Print Page Previous Next Advertisements ”;

Home

DB2 Tutorial PDF Version Quick Guide Resources Job Search Discussion This tutorial provides you the basic understanding of concepts of database, database installation and management. At the end of the tutorial you should be equipped with well understanding of database management concepts. Audience This tutorial is designed for the readers pursuing education in database management domain and all enthusiastic readers. Prerequisites This tutorial is designed and developed for absolute beginners. Though, awareness about software systems, operating systems and computer fundamentals would be beneficial. Print Page Previous Next Advertisements ”;