This action might not be possible to undo. Are you sure you want to continue?
Setting the Stage
After completing this module, you will be able to:
• State the purpose and function of the session
• Recognize differences in transaction modes for
Teradata and ANSI
• Use the various HELP functions available
SQL Version 2 Differences
Teradata V2R2 (and later) consists of: - All existing Teradata features from v1. - ANSI compatible ways to perform many Teradata V1 features. - Completely new features based on ANSI standard.
WITH BY FORMAT
V2R2 allows for sessions to operate in either ... - BTET (Teradata) mode - ANSI mode All syntax, both ANSI and Teradata extensions, is accepted in either mode.
The same syntax might function differently in each mode.
Using ANSI mode to run existing V1 scripts will affect: - Transaction protocol behavior - Case sensitivity and collating sequences - Certain data conversion and display functions
.requires BT to start explicit transaction .uses standard Teradata mode (Begin Txn . To change session mode.Default case sensitivities .SET SESSION TRANSACTION ANSI.Data conversions .Transaction protocol . Affects: .End Txn mode) BTEQ Examples . must LOGOFF first.requires neither for implicit transactions Must be entered prior to LOGON.requires COMMIT to end transaction .SET SESSION TRANSACTION BTET.SQL Session Modes Transaction mode setting ANSI .uses ANSI mode (Commit mode) BTET . .requires ET to end explicit transaction .
COMMIT WORK will commit the currently active Txn. Locks are accumulated until a COMMIT is issued. Statement following a COMMIT automatically starts a new Txn.SET SESSION TRANSACTION ANSI.ANSI . ANSI mode: A transaction is committed only by an explicit COMMIT.explicit rollback of active Txn • Session abort . .rollback of active Txn • SQL statement failure . A rollback occurs when any of the following occur: • ROLLBACK WORK .rollback current statement only Transactions are by definition explicit.Transaction Modes . COMMIT is required immediately following any DDL.
BEGIN and END TRANSACTION are used to create larger transactions out of individual requests.rollback of active Txn • SQL statement failure .rollback of active Txn Locks are accumulated following a BT until an ET is issued.Teradata . Each request is an implicit transaction.Transaction Modes . .explicit rollback of active Txn • Session abort .SET SESSION TRANSACTION BTET. BTET mode: A transaction is by definition implicit. A rollback occurs when any of the following occur: • ROLLBACK WORK . BT begins an explicit Txn. ET commits the currently active Txn.
Transaction Examples ANSI Mode BTET Mode (explicit) BT Upd A Upd B ET (both commit) BT Upd A Upd B (fails) (both rollback) BTET Mode (implicit) Upd A (A commits) Upd B (B commits) Upd A Upd B COMMIT (both commit) Upd A Upd B (fails) COMMIT (A commits) Upd A (A commits) Upd B (fails) (rollback B) Upd A Upd B ROLLBACK (both rollback) BT Upd A Upd B ROLLBACK (both rollback) BT Upd A Upd B LOGOFF (both rollback) (No explicit ROLLBACK in implicit Txn) Upd A Upd B LOGOFF (both rollback) Upd A (A commits) Upd B (B commits) LOGOFF .
[SET] SKIPDOUBLE = OFF ALL [SET] SKIPLINE = OFF ALL [SET] SUPPRESS = OFF ALL [SET] TDP = l5442 [SET] TITLEDASHES = ON for the normal report. [SET] UNDERLINE = OFF ALL [SET] WIDTH = 75 . .LOGON XYZ. [SET] FOLDLINE = OFF ALL [SET] FOOTING = NULL [SET] FORMAT = OFF [SET] FORMCHAR = OFF [SET] HEADING = NULL [SET] INDICDATA = OFF [SET] NOTIFY = OFF [SET] NULL =? [SET] OMIT = OFF ALL [SET] PAGEBREAK = OFF ALL [SET] PAGELENGTH = 55 [SET] QUIET = OFF [SET] RECORDMODE = OFF [SET] RETCANCEL = OFF [SET] RETLIMIT = No Limit [SET] RETRY = ON [SET] RTITLE = NULL [SET] SECURITY = NONE [SET] SEPARATOR = two blanks [SET] SESSION CHARSET = ASCII [SET] SESSION SQLFLAG = NONE [SET] SESSION TRANSACTION = BTET [SET] SESSIONS =1 [SET] SIDETITLES = OFF for the normal report.SHOW Command . it is ON for results of WITH clause number: 1 2 3 4 5 6 7 8 9.XYZ.SHOW CONTROL.BTEQ . And.
use BTEQ settings: .SET FOLDLINE To return to the default settings: .SET SIDETITLES . *** Total elapsed time was 1 second.HELP SESSION Command HELP SESSION. One row.SET DEFAULTS . *** Help information returned. User Name Account Name Logon Date Logon Time Current DataBase Collation Character Set Transaction Semantics Current DateForm Session Time Zone Default Character Type TUSER25 $M_9038_&L 00/06/16 15:14:04 TUSER25 ASCII ASCII Teradata IntegerDate 00:00 LATIN Note: To produce this format.
HELP ‘SQL ALTER TABLE’.Online Syntax HELP Provides help on multiple utilities. command-name’. command-name’. command-name’. Online Syntax help HELP HELP ‘utilityname utilitycommand’. command-name’. HELP ‘SQL’. ‘SQL ‘ARCHIVE ‘BULKLOAD ‘DUMP ‘FASTEXPORT ‘FASTLOAD ‘MULTILOAD ‘PMPC ‘TPCCONS command-name’. Provides global command menu. command-name’. Provides individual command syntax. HELP ‘SQL SELECT’. command-name’. command-name’. command-name’. .
.HELP Examples HELP 'SQL'..tname [ [AS] aname ] ] . One column returned. SET columnname = expr [ . 10 rows found... *** Total elapsed time was 1 second. 35 rows found.. *** Total elapsed time was 1 second.columnname = expr] [ WHERE condition ] [ ]. *** Query completed. On-Line Help --------------------------------------------------------------------------UPD[ATE] tablename [ [AS] aname ] [ FROM tname [ [AS] aname] ] [. On-Line Help --------------------------------------------------------------------------DBS SQL COMMANDS: ABORT BEGIN TRANSACTION COMMIT CREATE INDEX CREATE USER DELETE DROP DATABASE DROP TABLE ECHO EXECUTE GRANT : ALTER TABLE CHECKPOINT COMMENT CREATE MACRO CREATE VIEW DELETE DATABASE DROP INDEX DROP VIEW END LOGGING EXPLAIN GRANT LOGON : BEGIN LOGGING COLLECT STATISTICS CREATE DATABASE CREATE TABLE DATABASE DELETE USER DROP MACRO DROP STATISTICS END TRANSACTION GIVE HELP : HELP 'SQL UPDATE'. . *** Query completed. [ ALL ] . One column returned.
cname tname aname condition INNER JOIN LEFT OUTER JOIN Column or expression name Table or view name Alias for table or view name Criteria for the join All matching rows Table to the left is used to qualify. table on the right has nulls when rows do not match. …] FROM tname [aname] [INNER] LEFT [OUTER] RIGHT [OUTER] FULL [OUTER] CROSS JOIN ON Where: tname [aname] condition . Both tables are used to qualify and extended with nulls. cname . table on the left has nulls when rows do not match.details in Appendix B. SELECT cname [. Table to the right is used to qualify.SELECT Statement ANSI Join Syntax With V2R2 (and later). Teradata supports the ANSI join syntax and outer joins . Cartesian product RIGHT OUTER JOIN FULL OUTER JOIN CROSS JOIN .
B.Column Attributes Storage As entered (default) UPPERCASE UPPER. LOWER CASESPECIFIC (CS) NONCASESPECIFIC (NOT CS) (Teradata default) Comparisons Default (NOT CS) result SELECT first_name . first_name Robert James I. last_name FROM employee WHERE last_name(CS) LIKE ‘%Ra%’.CASE Sensitivity Issues . first_name last_name Larry Ratzlaff Peter Rabbit . Larry Peter last_name Crane Trader Trainer Ratzlaff Rabbit (CS) result SELECT first_name .Teradata Teradata Rules . last_name FROM employee WHERE last_name LIKE ‘%Ra%’.
LOWER (Casespecific is default) Comparisons Default (CS) result SELECT first_name . last_name FROM employee WHERE last_name(CS) LIKE ‘%Ra%’.CASE Sensitivity Issues . first_name last_name Larry Ratzlaff Peter Rabbit .ANSI ANSI Rules . first_name last_name Larry Ratzlaff Peter Rabbit Explicit CS result SELECT first_name . last_name FROM employee WHERE last_name LIKE ‘%Ra%’.Column Attributes Storage None (As entered is default) UPPER.
ESCAPE rule ESCAPE permits use of ‘_’ or ‘%’ as part of string search criteria. Percent sign ‘%’ replaces zero to many characters. test num 15365 comment Result is 95% SELECT filename. filename ANSI_SQL_QRY3 filesize 2068 .Using ESCAPE with LIKE LIKE Wildcard rules Underscore ‘_’ replaces one character. comment FROM test_results WHERE comment LIKE ‘%95a%%’ ESCAPE ‘a’. SELECT test_num. filesize FROM file_table WHERE filename LIKE ‘%ANSIb_SQLb_%’ ESCAPE ‘b’.
m) CHAR(n) VARCHAR(n) CHAR VARYING(n) LONG VARCHAR BYTE(n) VARBYTE(n) GRAPHIC(n) VARGRAPHIC(n) LONG VARGRAPHIC ANSI (Entry) equivalent INTEGER SMALLINT FLOAT REAL DOUBLE PRECISION DECIMAL(n.m) NUMERIC(n.m) DECIMAL(n.Data Types Teradata INTEGER SMALLINT BYTEINT DATE TIME TIME WITH ZONE TIMESTAMP TIMESTAMP WITH ZONE FLOAT FLOAT FLOAT DECIMAL(n.m) CHAR(n) .
Table Level Attributes CREATE MULTISET TABLE sales_period DATABLOCKSIZE = 16384 BYTES FREESPACE = 10 PERCENT (period_num INT). SET MULTISET Don’t allow duplicate rows Allow duplicate rows (ANSI) DATABLOCKSIZE Maximum multi-row blocksize for table in: BYTES KILOBYTES (or KBYTES) Rounded to nearest sector (512) Increments of 1024 MINIMUM DATABLOCKSIZE MAXIMUM DATABLOCKSIZE (6144) (65024) FREESPACE Percent of freespace to keep on cylinder during loading operations (0 .75%) .
Column Attributes Attribute UPPERCASE CASESPECIFIC FORMAT TITLE NAMED/AS COMPRESS COMPRESS NULL COMPRESS value WITH DEFAULT DEFAULT DATE DEFAULT TIME NOT NULL DEFAULT value DEFAULT USER DEFAULT NULL ANSI Teradata Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes .
Indexes (primary or secondary) may be used to improve access. Indexes Primary index . PK’s are always unique and cannot be null. PK’s are not known to the Teradata DBS as such.Primary Keys And Indexes (Review) Primary Keys Primary key .one or more columns used to uniquely identify the rows of a table (one per table). Primary index(PI) choice will affect distribution. Indexes (primary or secondary) may be unique or nonunique. PK’s are implemented as indexes by the Teradata DBS. Indexes (primary or secondary) may be used to enforce uniqueness. .one or more columns used to distribute and locate the rows of a table (one per table). Primary keys (PK) are used in conjunction with foreign keys to define the important relationships in a database. access and thus performance.
department_number INTEGER REFERENCES department(department_number). hire_date DATE NOT NULL. . NO AFTER JOURNAL ( employee_number INTEGER NOT NULL PRIMARY KEY. User must have REFERENCES right on referenced table. All constraints are at the column level.2) NOT NULL) . first_name VARCHAR(30) NOT NULL.Creating Employee Table With Constraints All constraints are unnamed. Referenced columns must be defined as unique. CREATE TABLE employee . birthdate DATE NOT NULL. job_code INTEGER REFERENCES job(job_code).FALLBACK . Primary Key column(s) must be defined NOT NULL. Up to 64 foreign keys may be defined on a table. NO BEFORE JOURNAL. last_name CHAR(20) NOT NULL. salary_amount DECIMAL(10. manager_employee_number INTEGER REFERENCES employee(employee_number).
salary_amount DECIMAL(10.2) NOT NULL. CREATE SET TABLE employee . manager_employee_number INTEGER. department_number INTEGER NOT NULL.Show Table Constraints Employee Table SHOW TABLE employee. FOREIGN KEY ( manager_employee_number ) REFERENCES employee ( employee_number ).FALLBACK . Note: Primary key becomes the Primary index. FOREIGN KEY ( department_number ) REFERENCES department( department_number). last_name CHAR(20) NOT CASESPECIFIC NOT NULL. NO BEFORE JOURNAL. . first_name VARCHAR(30) NOT CASESPECIFIC NOT NULL. birthdate DATE NOT NULL. job_code INTEGER. NO AFTER JOURNAL ( employee_number INTEGER NOT NULL. FOREIGN KEY ( job_code ) REFERENCES job ( job_code ) ) UNIQUE PRIMARY INDEX ( employee_number ). hire_date DATE NOT NULL.
Altering Table Constraints To add constraints to a table: ALTER TABLE tablename ADD CONSTRAINT constrname CHECK ADD CONSTRAINT constrname UNIQUE ADD CONSTRAINT constrname PRIMARY KEY ADD CONSTRAINT constrname FOREIGN KEY To modify existing constraints: ALTER TABLE tablename MODIFY CONSTRAINT constrname To drop constraints: ALTER TABLE tablename DROP CONSTRAINT constrname .
like tables.What is a Trigger? A Trigger may be defined as: • One or more stored SQL statements associated with a table • An event driven procedure attached to a table • An object in a database. GRANT REVOKE CREATE DROP TRIGGER . Privileges are required to create and drop triggers. views and macros Any of the following SQL statements may be applied to triggers: CREATE DROP SHOW ALTER RENAME REPLACE HELP TRIGGERS Triggers may not be used in conjunction with: • The FastLoad utility • The MultiLoad utility • Updateable Cursors (Preprocessor environment) DELETE DATABASE DELETE USER Both cause all triggers to be dropped.
• Creates and keeps table definition in data dictionary .Spool rows are discarded when query finishes • No data dictionary involvement • Commonly used with aggregation Volatile Tables • Local to a session .uses SPOOL space • Uses CREATE VOLATILE TABLE syntax • Discarded automatically at session end • No data dictionary involvement (Global) Temporary Tables • Local to a session .Temporary Table Choices Derived Tables • Local to the query (table and columns are named within query) • Incorporated into SQL query syntax (populated in query via SELECT in FROM) • Materialized in SPOOL .uses TEMPORARY space • Uses CREATE GLOBAL TEMPORARY TABLE syntax • Materialized instance of table discarded at session end.
-----.----------. Will insert defined default values into each column. CREATE TABLE test_tbl (cola SMALLINT NOT NULL DEFAULT 22 .Inserting Default Values INSERT INTO tablename DEFAULT VALUES. INSERT INTO test_tbl DEFAULT VALUES.colb CHAR(1) .-----.cold DEC(3.colc DATE DEFAULT 1000101 FORMAT 'YYYY-MM-DD' . SELECT * FROM test_tbl. If no default defined and null not allowed. cola ------22 22 colb colc cold cole colf ----.----------.2) NOT NULL WITH DEFAULT . insert will fail.--------------.-------22 ? 2000-01-01 .----.00 11:14:37 111437 colg -------PED PED . cola colb colc cold cole colf colg ------.----------.00 11:14:14 111414 ? 2000-01-01 .colf INT DEFAULT TIME .----------? 2000-01-01 . If no default is defined.--------------. will insert a null.00 11:14:14 111414 PED INSERT INTO test_tbl DEFAULT VALUES.cole TIME(0) DEFAULT CURRENT_TIME .colg CHAR(8) DEFAULT USER). SELECT * FROM test_tbl.
executes a file of BTEQ/SQL commands .delete a file . DELETE tablename ALL.displays session information .deletes all rows in a table .exits BTEQ Useful UNIX Commands: ls -l pg (or more) filename vi (or vedit) filename cp file1 file2 mv filename newfilename rm filename exit .lists objects owned by user .QUIT . EXEC macroname.drops table from the database .LOGON tpdid/username HELP SESSION.RUN FILE=filename . DROP TABLE tablename.copies file1 to file2 .long listing of UNIX files) .provides count of rows in table .create or edit a text file .exits UNIX . SELECT COUNT(*) FROM tname. .Lab Environment DBC UNIX userids u____01 u____02 u____xx Note: ___ Instructor Initials Teradata_Factory AU Accounts Customer Trans Lab3_1_1 Lab3_1_2 Accounts Customer Trans ____Students T____01 T____02 Accounts Customer Trans T____xx Accounts Customer Trans Useful Teradata Commands in BTEQ: .logon to Teradata .executes a macro . HELP USER username.shows table creation syntax .help for an SQL command .renames a file .view contents of text file . HELP ‘SQL sqlcommand’. SHOW TABLE tablename.
cname . Table to the right is used to qualify. Where: cname tname aname condition INNER JOIN LEFT OUTER JOIN Column or expression name Table or view name Alias for table or view name Criteria for the join All matching rows Table to the left is used to qualify. …] FROM tname [aname] [INNER] LEFT [OUTER] RIGHT [OUTER] FULL [OUTER] CROSS JOIN ON tname [aname] condition . table on the right has nulls when rows do not match. table on the left has nulls when rows do not match. Cartesian product RIGHT OUTER JOIN FULL OUTER JOIN CROSS JOIN .SELECT Statement Join Syntax SELECT cname [. Both tables are used to qualify and extended with nulls.
SELECT D.Department_Number = D. No information about departments which have no employees assigned to them. .Department_Number AS Dept .Last_name .Department_Number.Department_Name .E. No information about employees who have no department number or an invalid department number.Department_Number AS EmpDept FROM Department D INNER JOIN Employee E ON E.Inner Joins An inner join returns an output row for each successful match between the join tables. Dept Department_Name 402 software support 100 executive 501 marketing sales 301 research and development 301 research and development Last_Name Crane Trainer Runyon Stein Kanieski EmpDept 402 100 501 301 301 Information about employees and their department names where the employee’s department number matches the existing departments.
SELECT D.Department_Number AS Dept . .Department_Number = D. Dept 600 402 ? 501 301 ? 100 301 Department_Name new department software support ? marketing sales research and development ? executive research and development Last_Name ? Crane James Runyon Kanieski Green Trainer Stein EmpDept ? 402 111 501 301 ? 100 301 In addition to output from inner join: Shows employees with null departments.Last_name .Department_Number.Outer Joins An outer join returns matching rows and nonmatching rows.E.Department_Number AS EmpDept FROM Employee E FULL OUTER JOIN Department D ON E. Shows employees with invalid departments. Shows departments with no employees.Department_Name .
Department_Number .Department_Number FROM ON .LEFT Outer Join Example SELECT E.Last_Name Employee E LEFT OUTER JOIN Department D E.Department_Name . Shows employees with invalid departments. . department_number 402 111 501 301 ? 100 301 department_name software support ? marketing and sales research and develop ? executive research and develop last_name Crane James Runyon Stein Green Trainer Kanieski In addition to output from inner join: Shows employees with null departments.Department_Number = D.
Department_Number FROM ON . department_number 600 402 100 501 301 301 department_name new department software support executive marketing sales research and develop research and develop last_name ? Crane Trainer Runyon Stein Kanieski In addition to output from inner join: Shows departments with no employees. .RIGHT Outer Join Example SELECT D.Department_Name .Department_Number = D.Last_Name Employee E RIGHT OUTER JOIN Department D E.Department_Number .
SELECT last_name AS Employee .Job_Code = J. the ON clause needs to be placed appropriately so that the join operation can be evaluated correctly.Job_Code .description AS Job FROM Department D RIGHT OUTER JOIN Employee E ON D. Returns all employees including: employees with invalid departments employees with null departments employees with invalid job codes employees with null job codes .Department_Number LEFT OUTER JOIN Job J ON E. In joining more than two Tables in an outer join.department_name AS Dept .Department_Number = E.Outer Joins of More Than Two Tables Each JOIN must have an associated ON clause.
description AS Job FROM (Department D RIGHT OUTER JOIN (Employee E LEFT OUTER JOIN Job J ON E.Department_Number.Department_Number = E.Job_Code = J. .Job_Code ON D. The same SELECT example could be written as: SELECT last_name AS Employee .department_name AS Dept . The rules are: • The first ON clause (from left to right) is evaluated first.Job_Code ) ON D.Job_Code = J.Department_Number = E.Department_Number).description AS Job FROM Department D RIGHT OUTER JOIN Employee E LEFT OUTER JOIN Job J ON E. SELECT last_name AS Employee .ON Clause Placement The placement of the ON clause in the SELECT is important. • An ON clause applies to the immediately preceding join operation. Using parenthesis can clarify the reading of the statement.department_name AS Dept .
d. SELECT e. Cross join syntax does not allow an ON clause. Output is not meaningful. Cross joins are sometimes called product joins. A WHERE clause may restrict which rows participate from either table.department_number FROM employee e CROSS JOIN department d WHERE e. employee_number department_number --------------------------.employee_number = 1008.---------------------------1008 501 1008 301 1008 402 1008 201 1008 302 1008 600 1008 401 1008 100 1008 403 One employee matched with nine departments results in nine rows of output.Cross Joins A cross join is a join that requires no join condition. .employee_number . Each participating row of one table is joined with each participating row of another table.
department_number.000 row answer set. SELECT employee. Each row of one table is joined to each row of another table. .d. Each employee row (26) matched with each department row (9) yields 234 rows of output.000.Cartesian Products A completely unconstrained cross join is called a ‘Cartesian Product’.department_number FROM employee e INNER JOIN department d ON e. SELECT e.000 row table would yield a 400. A Cartesian product results from a CROSS JOIN without a WHERE clause.d.employee_number .department_number FROM employee e CROSS JOIN department d. The output of a Cartesian product is rarely meaningful.employee_number .000.department_number = d. An 8.000 row table and a 50. Cartesian products can also result from an INNER JOIN with improper aliasing or improper join conditions.000.
Thank You!!! .