Presentation is loading. Please wait.

Presentation is loading. Please wait.

SQL – DDL Data Definition Language

Similar presentations


Presentation on theme: "SQL – DDL Data Definition Language"— Presentation transcript:

1 SQL – DDL Data Definition Language
Copyright  1992, 1993 BY DMC CONSULTING, INC. ALL RIGHTS RESERVED 5650 West Central Avenue, Suite B, Toledo, OH 43615 AS/400 is a trademark of International Business Machines Corporation

2 SQL – DDL – Creating Schemas

3 Objectives Upon completion of this segment, you will
have a thorough understanding of: Collections and Schemas Creating Schemas Schema Contents Schema Commands You will also perform the following task: Create a schema

4 What is a Schema Simply put, a schema (also called collection) is a group of tables. These tables are logically linked together for easier management. On the System i, schemas are implemented as Libraries within the DB2 database. Not just a library though, but also all of the management objects within the schema that are used by the SQL engine to manage the schema. Knowing what these objects are and how to use them is very practical knowledge. Schemas contain the following objects by default:

5 What is a Schema Catalog Journals SYSTABLES QSQJRN
SYSCOLUMNS QSQJRN0001 SYSINDEXES SYSKEYS SYSVIEWS SYSVIEWDEP SYSPACKAGE SYSCHKCST SYSCST SYSCSTCOL SYSCSTDEP SYSKEYCST SYSREFCST SYSTRIGCOL SYSTRIGDEP SYSTRIGGER SYSTRIGUPD Syntax: CREATE SCHEMA schema-name

6 What is a Schema SET CURRENT SCHEMA schema-name
This statement sets the default schema for created objects as well as the default schema for objects referenced in other SQL statements, but not procedures and functions. Correctly specifying the current schema can greatly simplify SQL syntax by removing the location to find

7 What is a Schema SET OPTION DFTRDBCOL = schema-name
When creating procedures and functions, its possible to define the default database schema (collection) using the SET OPTION statement as shown below: CREATE PROCEDURE procedure-name LANGUAGE SQL SET OPTION DFTRDBCOL = schema-name BEGIN procedure-code; END

8 What is a Schema SET PATH = “schema-name”, schema-name, schema-name,…
The SQL path is used to resolve unqualified references to User Defined Functions , User Defined Data Types, and Stored Procedures. The default behavior of SQLPATH changes based upon the naming convention in use: *SYS Naming, SQLPATH = “*LIBL” *SQL Naming, SQLPATH = “QSYS,QSYS2,user-id” To best use this feature, create a procedure in each environment (test,production, etc) Define that procedure shown below, replacing the schema name with the data schema for that environment.

9 What is a Schema CREATE PROCEDURE Set_Schema LANGUAGE SQL BEGIN
SET CURRENT SCHEMA schema-name END In any other stored procedure, call the Set_Schema procedure at the beginning of the code to correctly set the data schema being used in this environment. It should avoid the need for hard coded schema names. CREATE PROCEDURE Other_Proc LANGUAGE SQL BEGIN CALL Set_Schema;

10 SQL Create Statement Tables
The CREATE statement allows the user to build a new table. All of the fields (columns) must also be defined. Their data type, length, and null attributes must be described. And optional constraints may be defined as well. There are three different version of the CREATE TABLE statement: CREATE TABLE table-name (definition) CREATE TABLE LIKE other-table CREATE TABLE AS (select-statement)

11 SQL Create Statement CREATE TABLE table-name (definition)
CREATE TABLE lib/table (field1 datatype(length) null, field2 datatype(length) null, field3 datatype(length) null, etc......, constraint1, constraint2, etc ) The library/schema name is optional. For compatibility with RPG IV, the file and field names should not exceed 10 characters. For RPG/400, field names cannot exceed 6 characters.

12 SQL Create Statement Data Types
CHAR – Up to 32,767 bytes of alphanumeric data ( if Null capable) DECIMAL – Up to 63 digits of packed numeric data NUMERIC – Up to 63 digits of zoned numeric data. DATE – Date Data type using a 4 digit year TIME – Time data type in 24 hr format TIMESTAMP - Timestamp data type include date, time, and microseconds (6 digits) INTEGER (INT) – Large Integer (4 Bytes) SMALLINT – A small integer (2 Bytes) BIGINT – A big integer (8 Bytes) FLOAT – Floating Point data type (8 Bytes) VARCHAR - Up to 32,740 bytes of character data ( if Null capable) LONG VARCHAR – Variable Length Character Data up to the length of the row BINARY – Up to 32,767 bytes of binary data (32,765 if Null Capable)

13 SQL Create Statement Data Types
VARBINARY - Up to 32,740 bytes of binary data ( if Null capable) GRAPHIC – Up to 16,383 double byte characters (16,382 if Null capable) VARGRAPHIC – Up tp double byte characters (16,369 if Null capable) LONG VARGRAPHIC – A string of double byte characters up to the length of the row DOUBLE – Double precision floating point (8 Bytes) REAL – Single Precision Floating point (4 Bytes) BLOB – Variable length binary string up to 2 gigabytes in length CLOB – Variable length string of characters up to 1 gigabyte in length DATALINK – A string up to 32,718 bytes containing a URL (32,717 if Null capable) DBCLOB – Variable length double byte character string up to 1 gigabyte in length User-Defined (UDT) – Custom functions built with the CREATE FUNCTION statement ROWID - System generated key that uniquely defines a row (40 Bytes)

14 SQL Create Statement When defining fields their null attribute can be:
Omitted: To allow null values NOT NULL: To prevent null values from being loaded into a field NOT NULL WITH DEFAULT: To use default values in place of null values CREATE TABLE MYTEST (PART CHAR(10) NOT NULL WITH DEFAULT, OQTY NUMERIC(5, 0) NOT NULL, COST NUMERIC(7, 2) NOT NULL WITH DEFAULT 19.99, DESC CHAR(20))

15 SQL Create Statement Constraints
Primary key: A set of fields which must contain unique, non-null values. Unique key: A set of fields which must contain unique values. Foreign key: A set of fields which must match the key to the parent file. Check: A set of fields whose values must meet a defined criteria.

16 SQL Create Statement Constraints CONSTRAINT name type (values)
CONSTRAINT CUST_KEY PRIMARY KEY (FIELDA) CONSTRAINT VALID_CUST FOREIGN KEY (CUSTNO) REFERENCES CUST (CNUMBER) ON DELETE CASCADE ON UPDATE NO ACTION CONSTRAINT FIELDC_VALIDITY CHECK (FIELDC <> 0 ) CONSTRAINT VALID_ORDER UNIQUE (ORDER#)

17 SQL Create Statement CREATE TABLE LIKE other-table
CREATE TABLE MYTABLE LIKE YOURTABLE INCLUDING IDENTITY or EXCLUDING IDENTITY

18 SQL Create Statement CREATE TABLE AS (Select-Statement)
CREATE TABLE MYTABLE AS (SELECT * FROM YOURTABLE) WITH DATA WITH NO DATA (SELECT KEYFLD, SUM(QTYFLD) AS TOTAL FROM YOURTABLE GROUP GROUP BY KEYFLD)

19 SQL Create Statement Identity Columns What is an Identity Column?
An identity column is a column in an SQL table which is partially under system control, and is used to create a unique key to a database. These must defined at the time of the table creation, though they can altered after the fact, but not added. An Identity column must be defined as Decimal, Numeric, Integer, Smallint, or Bigint. It has a starting and ending value as well as an increment. If the CYCLE option is used, then when the ending value is reached, the next new record uses the starting value. Essentially “wrapping” the identity value.

20 PartID Part# Description Price
SQL Create Statement Identity Columns These columns are ideal as keys to a database table. Using an identity column in place of a meaningful data item such as Part Number, Employee Number, or Order Number enables us to freely change those values and treat them as easily maintained data columns. PartID Part# Description Price A Widget A Sprocket C Cog

21 SQL Create Statement Identity Columns CREATE TABLE PARTMAST
(PARTKEY DECIMAL (6,0) NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH INCREMENT BY 1 CYCLE CACHE 100 NO ORDER), PARTDESC AS CHAR(30))

22 SQL Create Statement Identity Columns CREATE TABLE PARTMAST
(PARTKEY DECIMAL (6,0) NOT NULL GENERATED BY DEFAULT AS IDENTITY (START with INCREMENT BY 1 MINVALUE MAXVALUE NO CYCLE NO CACHE ORDER), PARTDESC AS CHAR(30))

23 SQL Create Statement Identity Columns
GENERATED ALWAYS – System assigns value, no value can be specified for this field on INSERT statements GENERATED BY DEFAULT – System assigns value if no value was specified for this field on INSERT statements START WITH x – Beginning value for inserted rows INCREMENT BY x – Amount added to value for each row CYCLE – After reaching the MAXVALUE restart at MINVALUE NO CYCLE – No restart after reaching MAXVALUE (until alter table xxxxx alter column yyyyy restart is run)

24 SQL Create Statement CACHE x – Allocate x identity values in memory for faster INSERTS (must be 2 or more) NO CACHE – Do not preallocate identity values ORDER – Identity values must be issued in order NO ORDER – Identity values may be issued in any order IDENTITY_VAL_LOCAL() – Function returns the last Identity value issued at “same level”. This means within the same function or procedure. Do not use in a before trigger. INSERT INTO PARTMAST (PARTDESC) VALUES(‘NEW PART’) INSERT INTO PARTHIST SELECT * FROM PARTMAST WHERE PARTID = IDENTITY_VAL_LOCAL() *See ROWID for information OVERRIDING options on Insert

25 SQL Create Statement Row ID Columns What is a ROWID Column?
ROWIDs are similar to identity columns in that they uniquely identify rows within the database. Unlike an identity column, ROWID is a datatype with a 40 byte length. Either the system will assign the ROWID, or one can be assigned by the user. But in the later case it must be a valid row-id generated by the database. CREATE TABLE PARTMAST (PARTKEY ROWID GENERATED ALWAYS, PARTDESC AS CHAR(30))

26 SQL Create Statement Row ID Columns
The ROWID() Function can be used to translate a character string back into a row id data type. This presumes the character string was created by casting a valid row id value into a character string with the CAST function. When inserting data into a table with either a ROW ID or an Identity Column the following clauses may precede the values clause.

27 SQL Create Statement Row ID Columns INSERT INTO PARTMAST
OVERRIDING USER VALUE – This tells the SQL Engine to ignore row id or identity column values given on an insert, and that the system should generate appropriate values instead. OVERRIDING SYSTEM VALUE – This tells the SQL Engine to recognize row id or identity column values given on an insert, and that the system should not generate these values. INSERT INTO PARTMAST OVERRIDING USER VALUE VALUES(0,’New Part’)

28 Table Creation Scripts
SQL Create Statement Table Creation Scripts It is useful to have an easy executed and modified script/program available to delete and recreate tables, indexes and views. Because the SQL Engine has certain predictable patterns when searching for an optimal index, controlling the sequence they are created in, can improve performance. Text members executed with RUNSQLSTM can be used for this purpose. CREATE TABLE PARTMAST (PARTID DECIMAL (6,0) GENERATED BY DEFAULT AS IDENTITY (START WITH MINVALUE MAXVALUE INCREMENT BY 1 NO CYCLE NO CACHE NO ORDER), PARTDESC CHAR(30)); RUNSQLSTM SRCFILE(lib/file) SRCMBR(mbr)

29 Table Creation Scripts
SQL Create Statement Table Creation Scripts Besides using RUNSQLSTM, other options such as these may be used: This task can be performed by QMQRY script files. An SQL script file executed via iSeries Navigator A High Level Language program with embedded SQL A stored procedure.

30 SQL Create Statement CREATE PROCEDURE PARTMAST_BUILD LANGUAGE SQL
MODIFIES SQL DATA BEGIN CREATE TABLE PARTMAST (PARTID DECIMAL (6,0) GENERATED BY DEFAULT AS IDENTITY (START WITH MINVALUE MAXVALUE INCREMENT BY 1 NO CYCLE NO CACHE NO ORDER), PARTDESC CHAR(30)); CALL PARTMAST_ADD_INDEX; END

31 SQL Create Statement A complete set of procedures may be used to manage a table and all its related objects. CREATE PROCEDURE PARTMAST_ADD_INDEX LANGUAGE SQL MODIFIES SQL DATA BEGIN ALTER TABLE PARTMAST ADD CONSTRAINT PARTMAST_PRI_KEY PRIMARY KEY (PARTID); CREATE UNIQUE INDEX PARTMAST_UNIQUE_DESC ON PARTMAST(PARTDESC); END

32 SQL Create Statement CREATE PROCEDURE PARTMAST_DROP LANGUAGE SQL
MODIFIES SQL DATA BEGIN CALL PARTMAST_DROP_INDEX; DROP TABLE PARTMAST; END CREATE PROCEDURE PARTMAST_DROP_INDEX ALTER TABLE PARTMAST DROP CONSTRAINT PARTMAST_PRI_KEY; DROP INDEX PARTMAST_UNIQUE_DESC;

33 SQL Create Statement CREATE PROCEDURE PARTMAST_REINDEX LANGUAGE SQL
MODIFIES SQL DATA BEGIN CALL PARTMAST_DROP_INDEX; CALL PARTMAST_ADD_INDEX; END

34 SQL Create Statement Materialized Query CREATE TABLE INVTOTALS AS
(WITH TEMP AS (SELECT DEC(SUM(IQTY),7,0) as TOTAL, IITEM FROM INVDET GROUP BY IITEM) SELECT MITEM,MDESC, MITMPRC, MITMCST, TOTAL FROM ITMMST LEFT JOIN TEMP ON MITEM = IITEM) DATA INITIALLY DEFERRED REFRESH DEFERRED ENABLE QUERY OPTIMIZATION MAINTAINED BY USER See IBM’s White paper for more details at

35 SQL Create Statement DATA INITIALLY DEFERRED indicates that the MQT is not loaded with data at the time of creation. Use DATA INITIALLY IMMEDIATE to load it with data right away if necessary REFRESH DEFERRED indicates that the user may choose to refresh the table at any time by issuing the REFRESH TABLE mqt-name statement. This clause is not optional. ENABLE QUERY OPTIMIZATION indicates that the SQL engine may choose to use this MQT to satisfy other SQL statements issued against the underlying table(s). To deactivate this feature, use DISBALE QUERY OPTIMIZATION instead. MAINTAINED BY USER indicates that the user is responsible for loading the correct data into the MQT using INSERT, UPDATE, DELETE, and REFRESH TABLE statements. This is not optional.

36 SQL Create Statement Managing Materialized Queries
The data within an MQT is static, meaning that once data is loaded into it, it will not change regardless of what happens to the underlying tables. Programmers may choose to manually update the MQT with INSERT, UPDATE, and DELETE statements, or more likely, they can repopulate the table with current data using the REFRESH TABLE statement such as the one shown below. REFRESH TABLE INVTOTALS QAQQINI File To enable the use of MQTs within the SQL optimizer, the QAQQINI file must be updated, as the default settings do not allow the use of Materialized Queries during the optimization process. These settings are needed: MATERIALIZED_QUERY_TABLE_USAGE = *ALL MATERIALIZED_QUERY_TABLE_REFRESH_AGE = *ANY

37 Global Temporary Table
SQL Create Statement Global Temporary Table DECLARE GLOBAL TEMPORARY TABLE ORDER_BATCH (ORDER DECIMAL(5,0), CUSTOMER DECIMAL (7,0), DUEDATE DATE, STATUS CHAR(1)) AS (SELECT ORDER, CUSTOMER, DUEDATE DATE, STATUS FROM ORDMAST WHERE BATCHNO = 12345) WITH DATA

38 Global Temporary Table
SQL Create Statement Global Temporary Table DECLARE GLOBAL TEMPORARY TABLE ORDER_BATCH LIKE ORDMAST SELECT * FROM SESSION/ORDER_BATCH

39 Triggers and Constraints

40 Check Constraints RPG Program Check Constraint Database File
The Check constraint enforces basic edit rules such as: PLTNO <> 0 STATUS <> “ “ YNFLD = “Y” OR YNFLD = “N” SHIFT > 0 AND SHIFT < 4 DAYOFWEEK(WEDT) = 1

41 Check Constraints ALTER TABLE PARTMAST ADD CONSTRAINT
PARTMAST_PRICE_NOT_ZERO CHECK (PRICE > 0) ALTER TABLE ORDMAST ORDMAST_VALID_STATUS CHECK (STATUS = ‘A’ OR STATUS = ‘P’ OR STATUS = ‘C’) PARTMAST_VALID_DATA CHECK (TYPE = ‘L’ AND PRICE = 0 OR TYPE <> ‘L’)

42 Primary/Unique Key Constraints
Child File - Primary Key Pugsley Adams Wed. Adams Bobby Brady Cindy Brady Greg Brady Jan Brady Marsha Brady ALTER TABLE PARTMAST ADD CONSTRAINT PARTMAST_PRI_KEY PRIMARY KEY (PARTID)

43 Primary/Unique Key Constraints
Child File -Unique Key Pugsley Adams Wed. Adams null Brady Greg Brady Jan Brady Marsha Brady ALTER TABLE PARTMAST ADD CONSTRAINT PARTMAST_UNIQUE_DESC UNIQUE KEY (PARTDESC)

44 Referential Constraints
RPG Program Child File Pugsley Adams Wed. Adams Bobby Brady Cindy Brady Greg Brady Jan Brady Marsha Brady Parent File Adams Brady Cleaver Munster Referential Constraint

45 Referential Constraints
ALTER TABLE INVDETAIL ADD CONSTRAINT “VALID PART” FOREIGN KEY (PARTID) REFERENCES PASRTMAST (PARTID) ON DELETE CASCADE ON UPDATE NO ACTION ON UPDATE… No Action – Do not allow parents records with dependents to have their parent key column(s) changed.. (Journalling required) Restrict - Do not allow parents records with dependents to have their parent key column(s) changed. (Journalling not required) ON DELETE… No Action – Do not allow parents records with dependents to be deleted. (Journalling required) Restrict - Do not allow parents records with dependents to be deleted. (Journalling not required) Cascade - If a parent record is deleted, cascade the delete to the dependent file, and delete all records associated with that parent record. Set Default - If a parent record is deleted, Set the key fields in the dependent file to their default values for all records associated with that parent record. Set Null- If a parent record is deleted, Set the key fields in the dependent file to null for all records associated with that parent record.

46 Indexes and Views kldjfhglkdjhfgpow this is jkhgoiwouiopuwe
kldjfhglkdjhfgp really important fgowouiopuwe kldjfhglkdjhfg information for me oiwiouiopuwe kldjfhglkdjhfg selected out from ubilgloiopuwe kldjfhglkdjhfg the jumble of data igowoiopuwe kldjfhglkdjhfg that fills up all my llswiwuiopuwe kldjfhglkdjhfgp data tables hdfigiwuopuwe kldjfhglkdjhfgpowehtljxncbvljkhdfgoiwluiopuwe

47 SQL Create Statement Index CREATE {UNIQUE} INDEX lib/index-name
ON lib/table-name (field1 {ASC/DESC}, field2 {ASC/DESC}, field3 {ASC/DESC}...) CREATE UNIQUE INDEX CUSTNAME ON CUST (CNAME) CREATE INDEX CUSTCITY ON CUST (CSTATE, CCITY) CREATE INDEX INVAVAIL ON INVDET (IITEM, IQTY DESC)

48 SQL Create Statement Encoded Vector Index
CREATE ENCODED VECTOR INDEX lib/index ON lib/table (field1 {ASC/DESC}, field2 {ASC/DESC}, field3 {ASC/DESC}...) WITH n DISTINCT VALUES; CREATE ENCODED VECTOR INDEX USER001/CUSTST ON CUST USER001/CUST (CSTATE) WITH 60 DISTINCT VALUES;

49 SQL Create Statement Views CREATE VIEW view-name AS
SELECT field1, field2, field3, etc... FROM base-table WHERE condition

50 SQL Create Statement Summary Views ORDER DATE LOC QTY
CREATE VIEW view-name (column1, column2, etc...) AS SELECT column1, Sum(column2), AVG(column3), etc... FROM base-table GROUP BY column1

51 SQL Create Statement Alias Alias Alias A D MULTI-MEMBER TABLE
CREATE ALIAS PARTMAST_MBR_A FOR PARTMAST (A)

52 Triggers

53 Trigger Programs Data Base Changes Trigger Program Data Base
Triggers can be written in SQL or as external programs in languages such as RPGLE. If the trigger program needs to abort the update, end it by sending an escape message with a severity of 50 or higher. Up to 300 Triggers can be associated with a single file. iSeries Navigator provides a wizard to assist in creating triggers.

54 Triggers CREATE TRIGGER your-lib.CUST_TRIGGER AFTER INSERT ON KPFLIB.CUST REFERENCING NEW TABLE AS N FOR EACH STATEMENT MODE DB2SQL BEGIN insert into your-lib.custhist (cnumber,cname) select n.cnumber,n.cname from n; END;

55 Triggers New/Old: Referencing New Row as xxx - for insert
Referencing Old Row as yyy – for delete Referencing New Row as xxx Old Row as yyy – for update (use Row syntax with DB2SQL or DB2ROW modes) Referencing New Table as xxx - for insert Referencing Old Table as yyy – for delete Referencing New Table as xxx Old Table as yyy – for update (use Table syntax with DB2SQL mode and not BEFORE triggers)

56 Triggers CREATE TRIGGER your-lib.CUST_TRIGGER AFTER INSERT ON KPFLIB.CUST REFERENCING NEW ROW AS N FOR EACH ROW MODE DB2ROW BEGIN insert into your-lib.custhist (cnumber,cname) values(n.cnumber,n.cname); END;

57 Triggers For Each: Use FOR Each ROW to force the trigger to run for each row affected. Use FOR EACH STATEMENT to force the trigger to run once for each SQL statement that might trigger it. This trigger will run even if no rows are affected. Mode: DB2ROW fires the trigger as each row is affected, and allows access to individual rows only. DB2SQL fires after all the statement is complete, and allows access to either rows or tables.

58 Triggers CREATE TRIGGER Load_Candidates INSTEAD OF INSERT ON ORDERS
REFERENCING NEW AS NEW_ROW FOR EACH ROW MODE DB2SQL INSERT INTO CANDIDATES VALUES(NEW_ROW.A1,NEW_ROW.A2)

59 Summary Schemas Table Creation Scripts Materialized Queries
Global Temporary Tables Indexes Views Constraints Triggers


Download ppt "SQL – DDL Data Definition Language"

Similar presentations


Ads by Google