Tera SQL Reference PDF
-
Upload
karthik-dc -
Category
Documents
-
view
305 -
download
6
description
Transcript of Tera SQL Reference PDF
The SQL Quick Reference
Guide
Simplicity by Design
First Edition
Tom Coffing
Todd Carroll
Michael J. Larkins
Robert Hines
Steve Wilmes
Published by
Coffing Publishing
First Edition October, 2002
Written by Tom Coffing, Michael Larkins, Todd Carroll, Robert Hines, and
Steve Wilmes
Web Page: www.Tera-Tom.com and www.CoffingDW.com
E-Mail address:
Teradata , NCR , and BYNET are registered trademarks of NCR Corporation,
Dayton, Ohio, U.S.A., IBM and DB2 are registered trademarks of IBM Corporation,
ANSI is a registered trademark of the American National Standards Institute. In
addition to these products names, all brands and product names in this document are
registered names or trademarks of their respective holders.
Coffing Data Warehousing shall have neither liability nor responsibility to any person or
entity with respect to any loss or damages arising from the information contained in this
book or from the use of programs or program segments that are included. The manual is
not a publication of NCR Corporation, nor was it produced in conjunction with NCR
Corporation.
Copyright 2002 by Coffing Publishing
All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of
information contained herein. Although every precaution has been taken in the prepa ration of this book, the publisher and author assume no responsibility for errors or omissions, neither is any
liability assumed for damages resulting from the use of information contained herein. For
information, address:
Coffing Publishing
7810 Kiester Rd.
Middletown, OH 45042
International Standard Book Number: ISBN 0-9704980-4-7
Printed in the United States of America
All terms mentioned in this book that are known to be trademarks or service have been
stated. Coffing Publishing cannot attest to the accuracy of this information. Use of a
term in this book should not be regarded as affecting the validity of any trademark or
service mark.
Acknowledgements and Special Thanks
I dedicate this book to my wife Leona, who is a great mother of my child ren and helped
me build this business from the beginning.
Tom Coffing
I dedicate this book to my parents, Steve and Joanne, and my grandmother who inspired
me to write and publish my first book.
Steve Wilmes
I would like to make a three fold dedication of this book: first,to my wife Kisha and my
mother Linda Wash, the two most precious women and appreciated supporters in my life,
to my grandparents James and Mary Hines who have also been a constant source of
stability and strength, and finally, to all the data warehousing professionals out there
learning and using Teradata while striving to enhance their careers and their lives. Much
appreciation and best wishes to you all.
Robert Hines
I dedicate this book to my parents Linda and Steve for their continual support, strength
and inspiration. Thanks for always being there.
Todd Carroll
We are all grateful to God for the knowledge to complete this book, the perseverance to
see it through, the dedication of from all the team members and the drive to see it through
to completion. Most of all, we have Tom Coffing to thank for his tireless leadership and
coordination of all the resources involved in this effort.
Mike Larkins
About the Author Tom Coffing
Tom is President, CEO, and Founder of Coffing Data Warehousing. He is an
internationally known consultant, facilitator, speaker, trainer, and executive coach with
an extensive background in data warehousing. Tom has helped implement data
warehousing in over 40 major data warehouse accounts, spoken in over 20 countries, and
has provided consulting and Teradata training to over 8,000 individuals involved in data
warehousing globally.
Tom has co- authored the following eight books on Data Warehousing:
• Secrets of the Best Data Warehouses in the World
• Teradata SQL - Unleash the Power
• Tera-Tom on Teradata Basics
• Tera-Tom on Teradata E-business
• Teradata SQL Quick Reference Guide - Simplicity by Design
• Teradata Database Design - Giving Detailed Data Flight
• Teradata Users Guide -The Ultimate Companion
• Teradata Utilities - Breaking the Barriers
Mr. Coffing has also published over 20 data warehousing articles and has been a
contributing columnist to DM Review on the subject of data warehousing. He wrote a
monthly column for DM Review entitled, "T eradata Territory". He is a nationally known
speaker and gives frequent seminars on Data Warehousing. He is also known as "The
Speech Doctor" because of his presentation skills and sales seminars.
Tom Coffing has taken his expert speaking and data warehouse knowledge and
revolutionalized the way technical training and consultant services are delivered. He
founded CoffingDW with the same philosophy more than a decade ago. Centered around
10 Teradata Certified Masters this dynamic and growing company teaches every Teradata
classes, provides world class Teradata consultants, offers a suite of software products to
enhance Teradata data warehouses, and has eight books published on Teradata.
Tom has a bachelor's degree in Speech Communications and over 25 ye ars of business
and technical computer experience. Tom is considered by many to be the best technical
and business speaker in the United States. He has trained and consulted at so many
Teradata sites that students affectionately call him Tera- Tom.
Teradata Certified Master
- Teradata Certified Professional - Teradata Certified SQL Specialist - Teradata Certified Administrator - Teradata Certified Implementation
- Teradata Certified Developer Specialist
- Teradata Certified Designer
About the Author Mike Larkins
Mike graduated with a Bachelors of Science degree in Management Information Systems
from Chapman University in Orange, California. His computer career spans 30 years in a
variety of related positions: computer operations, programmer, systems analyst, operating
systems support, consultant, and college instructor.
Mike retired from NCR Corporation in April 2000 with 18 years of service. His career
has involved work with a variety of computer systems and relational databases. The last
5 years with NCR were entirely focused on Teradata and customer education. Of the 15
courses that he taught for NCR, SQL was his favorite.
Mike has been working with Coffing Data Warehouse since May of 2000 teaching
courses and doing consulting. He earned his Teradata Masters by passing all 6
certification exams. His other book, Teradata SQL Unleash the Power was a best seller
at Partners 2001. This book has also become the course manual for many of the SQL
classes taught by Coffing Data Warehousing.
Other Books: Teradata SQL Unleash the Power
Teradata Certified Master
- Teradata Certified Professional - Teradata Certified SQL Specialist
- Teradata Certified Administrator - Teradata Certified Implementation
- Teradata Certified Developer Specialist - Teradata Certified Designer
About the Author Steve Wilmes
Steve Wilmes is our Chief Technical Officer at Coffing Data Warehousing. He is
considered one of the best Teradata Data Warehousing experts when it pertains to
education and consulting in the industry today. Steve is a recognized expert on NCR
hardware, UNIX, Teradata Database Administration, Physical Database Design, Application Development, Load Utilities, and SQL. He is also renowned internationally
for his knowledge and expertise in these fields as well.
Steve recently completed several assignments involving Teradata training and education.
These data warehousing customers represent numerous major industries across the
communications, financial, pharmaceuticals, airlines, wireless, home improvement and
technology sectors. The education that was delivered includes Teradata basics, SQL
intermediate/advanced, physical database design, application development, load utilities,
and database administration.
Steve has also participated in several assignments involving consulting for two major
NCR Teradata Data Warehousing Customers. Assignments included resolving critical data warehousing implementation, administration, and database conversions.
A Teradata Certified Master and co- author of the Teradata SQL Quick Reference Guide -
Simplicity by Design, Teradata Database Design - Giving Detailed Data Flight, Teradata
Users Guide -The Ultimate Companion, and Teradata Utilities - Breaking the Barriers , along with Steve’s motivation, enthusiasm, and strong business skills has provided him
the ability to work successfully in all global business environments.
Teradata Certified Master
- Teradata Certified Professional - Teradata Certified SQL Specialist
- Teradata Certified Administrator - Teradata Certified Implementation
- Teradata Certified Developer Specialist
- Teradata Certified Designer
About the Author Todd Carroll
Todd Carroll comes to Coffing Data Warehousing with big-time Teradata field
experience. Todd gained experience as the lead database administrator for Industrial Web
Machines. Todd installed Teradata, led core product demonstrations, and handled SQL
Query along with database optimization. He was responsible for all testing of Industrial Web Machines core product releases and development.
Todd has also done Teradata consulting work for the largest data warehouse sites in the
world. Todd has worked closely with users to develop SQL applications and has also
been responsible for converting Oracle and Sybase data to Teradata in many data
warehouse sites. He has developed a repeatable process for synchronizing the
development warehouse with the production warehouse. He has experience with
database design, scrubbing, converting, loading, scripting, and writing Teradata SQL.
Todd combines great field experience with excellent technical expertise to deliver
outstanding Teradata classes for CoffingDW. He is Teradata Certified Master, with all 6
Teradata certifications. Todd teaches Teradata Basics, Utilities, Beginning to Advanced
SQL, and Teradata Physical Database Design. His ability to break down the most
difficult of concepts into easy to understand thoughts offers his students the best route to
Teradata certification. He has trained and consulted at many Fortune 100 companies with
a 100% Teradata Certification pass rate from his students.
His wide span of knowledge provides him the ability to be flexible in terms of Teradata
training and consulting. As a Teradata DBA and consultant, Todd has developed
leadership, technical skills, and a strong decision making background. Combined with
his motivation, enthusiasm, perfectionism, and strong work ethic, his skills provide a
great addition to the Coffing Data Warehousing team.
Teradata Certified Master
- Teradata Certified Professional - Teradata Certified SQL Specialist - Teradata Certified Administrator - Teradata Certified Implementation
- Teradata Certified Developer Specialist
- Teradata Certified Designer
About the Author Robert Hines
After graduating Magna Cum Laude from Benedict College with over a 3.9 grade point average, Robert Hines has emerged as an outstanding IT professional and has serviced
clients all over the United States and Canada. His most notable accomplishments are in
the arenas of training, consulting and providing professional services as a programmer to
numerous industries (Utility, Communications, Financial, Government, E- Busine ss, etc.),
primarily in the Data Warehousing arena. Though he has extensive SQL experience with
Oracle, DB2, Sybase and other database programming languages, it is his
accomplishments in the Teradata world that he is most proud of. Robert's experience as a
Sr. Software Engineer in NCR's E-Business Engineering Center of Expertise is the
foundation of his Teradata knowledge and experience, and his successful quest to become
a Teradata Certified Master.
While serving NCR as a Sr. Software Engineer, Robert was recognized on numerous
occasions for Outstanding Performance. Some of the awarded accomplishments included
completing SQL and Load Utility tasks critical to successful product releases and
mentoring contractors and employees on SQL, Load Utilities and Microstrategy. Along
with successfully completing Microstrategy training courses, Robert served as a Project
Lead on a MicroStrategy conversion project, and also achieved designations as a
Teradata Certified Professional, SQL Specialist, and Implementation Specialist. The
experience at NCR with Teradata and MicroStrategy helped prepare him for his
enormously successful training and consulting career with Coffing Data Warehousing.
As a trainer, course developer, consultant and author with Coffing Data Warehousing
Robert Hines has achieved new levels of accomplishment. He has trained, taught and
mentored hundreds of developers and business users across the country on both Teradata
and Microstrategy. Robert has an uncanny ability to effectively teach non-experienced
and highly experienced students at the same time while satisfying both audiences.
Students rave about his fun and exciting classes that are full of interesting ways of
explaining technical concepts with clarity and simplicity. Consulting clients love his
technical aptitude and ability to finish the job in a professional, yet personable manner,
along with his ability to build relationships and empower end users and IT staff through
effective communication. His wish is that this book will aid him in his quest to impact
and energize the careers of others in the industry through the power of teaching!
Teradata Certified Master
- Teradata Certified Professional - Teradata Certified SQL Specialist
- Teradata Certified Administrator - Teradata Certified Implementation
- Teradata Certified Developer Specialist
- Teradata Certified Designer
The Quicker Reference Index
A B
ACCESS LOCKING 92 BEFORE Triggers 129
= ANY, NOT = ALL 10 BETWEEN 11Abort 100 BT/ET 99Abort/Rollback 100
C Add Column Attributes 110
ADD_MONTHS 48
Advanced Syntax 86 Calendar 51
AFTER Triggers 130 Cartesian Product Join 42
Aggregation 27 CASE 85
ALIAS using NAMED 14 CASE - Nested 88
Aliasing Columns 13 CASESPECIFIC 24
ALL 10 CAST – ANSI 21
ALTER Table 113 CHARACTERS 52
AND 5 COALESCE 84
AND - Multiples 6 Collect Statistics 118
AND/OR Combined 5 Column and Table Constraints 111
AND/OR Comparators: 4 Column Concatenation 57
ANSI INNER Join 40 Column Constraints 111
ANSI OUTER JOIN Syntax 43 Commit Work 100
ANY 10 Concatenation 57
AVERAGE (AVG) 28 Constraints 111
AVG 28 Correlated Subquery 36
= ANY, NOT = ALL 10 COUNT 31
Abort/Rollback 100 CREATE DATABASE 120
Add Column Attributes 110 CREATE GLOBAL TEMP
TABLE 127ADD_MONTHS Function 48
CREATE Macro 93Advanced Syntax 86
Create Table 105AFTER Triggers 130
CREATE USER 121Aggregation Functions 27
Create View Syntax 89ALIAS using NAMED 14
CROSS JOIN Syntax 45Aliasing Columns 13
Cumulative Sum (CSUM) 59ALTER Table 113
ANSI INNER Join Syntax 40
ANSI OUTER JOIN Syntax 43
AVERAGE Function (AVG) 28
The SQL Quick Reference Guide – Simplicity by Design i
The Quicker Reference Index
D G
Data Definition Language Global Temporary Tables105 127
Data Interrogation 81H
Date 46
DATE 47HASHAMP 124 Date and Time Processing 46HASHBAKAMP 124 Default Values 73
HASHBUCKET 124 DELETE 77Hashing Functions 123 Delete with a Join 78HASHROW 123 Delete with a Subquery 78
HAVING Clause 32Derived Tables 125
HELP 17DISTINCT 16HELP STATISTICS 119 DML Commands 72
Horizontal Reporting 87DROP DATABASE 122
DROP Macro 95
I DROP STATISTICS 119
DROP Table 114
IN and NOT IN 9DROP TEMP TABLE 128 INDEX 55DROP USER 122
Index – Primary 106 DROP Views 90INDEX Function 56
Indexes - Join Index 117 E
Indexes - Secondary 116
INNER Join ANSI 40EXCEPT 70
INSERT 72EXECUTE Macro 94
INSERT / SELECT 74EXISTS 37
Inserting Default Values 73EXPLAIN 19
Inserting NULLs 73EXTRACT Function 49
INSTEAD OF Triggers 131
INTEGERDATE 46F
INTERSECT 68
IS NOT NULL 7FALLBACK 108 IS NULL 7FORMAT 22
The SQL Quick Reference Guide – Simplicity by Design ii
The Quicker Reference Index
J N
Join – ANSI 40NAMED 14
Join – ANSI INNER 40Nested CASE 88
Join - Cartesian Product 42NOT = ALL 10
Join - Deletes 78NOT CASESPECIFIC 25
Join Indexes 117 NOT Clause 8
JOIN Outer 43NOT IN 9
Join Syntax 38NULLIF 82
Join UPDATE 76NULLIFZERO 81
Joins 38
O
L
OLAP Functions 58
LIKE Clause OR 12 5
Lock Syntax OR Multiples 96 6
LOCKING FOR ACCESS OR/AND Comparators: 92 4
Locking Modifiers ORDER BY Clause 96 15
LOWER Original Join Syntax 26 38
OUTER JOIN Syntax 43M
P
MACROS 93
MAVG 61 Permanent Journal 109
MAX POSITION 30 55
MDIFF Primary Index 62 106
MIN 29 Primary Index - Multi-Column 106
MINUS 71 Q
Moving Average (MAVG) 61
Moving Difference (MDIFF) 62
Quantifiers 35Moving Sum (MSUM) 60
QUANTILE 63MSUM 60
MULTILOAD UPSERT 80
Multiple Column Primary Index 106
Multiple Subqueries 34
Multiple WITH..BYs 104
MULTISET Table 107
The SQL Quick Reference Guide – Simplicity by Design iii
The Quicker Reference Index
R T
RANDOM Table Constraints 66 111
RANK Temporary Tables 64 125
RENAME Table Teradata Transaction Mode (BT/ET) 115 99
REPLACE Macro Time 95 46
REPLACE Views TIME 91 50
Reporting Totals/Subtotals TIMESTAMP102 50
Rollback TITLE 100 23
Totals (WITH) 102
TPUMP UPSERT S 80
Transaction Mode Settings SAMPLE 65 99
Transaction Mode TypesSAMPLEID 9865
Secondary Indexes Transaction Modes116 98
Transaction Processing SELECT 2 96
Triggers Selecting the DATE 129 47
Sequencing Triggers Triggers - INSTEAD OF 132 131
Triggers - Sequencing SET Table 107 132
Triggers -AFTER Set Operator Commands 129 67
Setting the Trans Mode Triggers BEFORE 99 129
TRIM SHOW 18 53U,V,W,Z Sorting 15
UNION 69Statistics 118UPDATE 75String/Column Concatenation 57UPDATE with a Join 76String Concatenation 57UPDATE with a Subquery 76Subquery 33UPPER 26Subquery - Correlated 36UPSERT 79Subquery - Delete 78User Information Functions 20Subquery UPDATE 76Views 89SUBSTR 54Volatile Temporary Tables 126 SUBSTRING 54WHERE Clause 3Subtotals 102WITH 102 Subtotals (WITH..BY) 103WITH..BY 103 SUM 27WITH..BYs - Multiples 104 System Calendar Columns 51ZEROIFNULL 83
IV The SQL Quick Reference Guide – Simplicity by Design
Table of Contents
TABLE OF CONTENTS
The Select Command....................................................................................................................... 2
The WHERE Clause .................................................................................................................................... 3
Comparators: AND/OR ............................................................................................................................. 4
Combining Comparators: AND/OR ................................................................................................. 5
Combining Multiple AND Comparators or Multiple OR Comparators ................... 6
IS NULL Clause and IS NOT NULL Clause .......................................................................... 7
NOT Clause ......................................................................................................................................................... 8
IN and NOT IN ................................................................................................................................................. 9
= ANY, NOT = ALL .................................................................................................................................10
BETWEEN .........................................................................................................................................................11
LIKE Clause ......................................................................................................................................................12
Aliasing Columns .........................................................................................................................................13
ALIAS using NAMED ............................................................................................................................14
ORDER BY Clause .....................................................................................................................................15
DISTINCT ..........................................................................................................................................................16
Help, Show, Explain, User Information Functions...........................17
HELP .......................................................................................................................................................................17
SHOW ....................................................................................................................................................................18
User Information Functions .................................................................................................................20
Default Database Command ................................................................................................................20
Account ..............................................................................................................................................................20
SELECT Database Command ............................................................................................................20
SESSION ..........................................................................................................................................................20
Data Conversions ..................................................................................................................................21
CAST – ANSI ..................................................................................................................................................21
Implied Cast – Teradata ..........................................................................................................................21
FORMAT ............................................................................................................................................................22
Tricking the ODBC to Format ...........................................................................................................22
CASESPECIFIC ............................................................................................................................................24
NOT CASESPECIFIC .............................................................................................................................25
LOWER and UPPER .................................................................................................................................26
Aggregation Functions .................................................................................................................27
SUM Function .................................................................................................................................................27
AVERAGE Function .................................................................................................................................28
(AVG) .....................................................................................................................................................................28
MINIMUM Function (MIN) ...............................................................................................................29
MAXIMUM Function (MAX) ..........................................................................................................30
The SQL Quick Reference Guide – Simplicity by Design V
Table of Contents
COUNT Function (COUNT) ............................................................................................................31
HAVING Clause ...........................................................................................................................................32
Subquery ..............................................................................................................................................................33
Multiple Subqueries ....................................................................................................................................34
Quantifiers ..........................................................................................................................................................35
Correlated Subquery ...................................................................................................................................36
Exists .......................................................................................................................................................................37
Joins..........................................................................................................................................................................38
Original Join Syntax ...................................................................................................................................38
ANSI INNER Join Syntax (Newer Syntax) ...........................................................................40
Cartesian Product Join ..............................................................................................................................42
ANSI OUTER JOIN Syntax ................................................................................................................43
CROSS JOIN Syntax .................................................................................................................................45
Date and Time Processing......................................................................................................46
INTEGERDATE Formula ....................................................................................................................46
Selecting the DATE ....................................................................................................................................47
ADD_MONTHS Function ....................................................................................................................48
EXTRACT Function ..................................................................................................................................49
TIME and TIMESTAMP .......................................................................................................................50
System Calendar Columns ....................................................................................................................51
Character String Processing .................................................................................................52
CHARACTERS Function .....................................................................................................................52
TRIM Function ...............................................................................................................................................53
SUBSTRING and SUBSTR Functions ......................................................................................54
POSITION and INDEX Functions ................................................................................................55
INDEX Function ...........................................................................................................................................56
String and Column Concatenation .................................................................................................57
OLAP Functions ....................................................................................................................................58
Cumulative Sum Function (CSUM) .............................................................................................59
Moving Sum Function (MSUM) .....................................................................................................60
Moving Average Function (MAVG) ............................................................................................61
Moving Difference Function (MDIFF) ......................................................................................62
QUANTILE Function ...............................................................................................................................63
RANK Function .............................................................................................................................................64
SAMPLE Function and SAMPLEID ...........................................................................................65
RANDOM Function ...................................................................................................................................66
Set Operator Commands ............................................................................................................67
INTERSECT .....................................................................................................................................................68
VI The SQL Quick Reference Guide – Simplicity by Design
Table of Contents
UNION ..................................................................................................................................................................69
EXCEPT ...............................................................................................................................................................70
MINUS ..................................................................................................................................................................71
Data Manipulation Language Commands ......................................................72
INSERT .................................................................................................................................................................72
Inserting NULL and Default Values ..............................................................................................73
INSERT / SELECT .....................................................................................................................................74
UPDATE ..............................................................................................................................................................75
UPDATE with a Subquery ....................................................................................................................76
UPDATE with a Join ................................................................................................................................76
DELETE ...............................................................................................................................................................77
Delete with a Join ...................................................................................................................................78
Delete with a Subquery .......................................................................................................................78
UPSERT ...............................................................................................................................................................79
UPSERT for TPUMP and MULTILOAD ..................................................................................80
DATA INTERROGATION .................................................................................................81
NULLIFZERO ................................................................................................................................................81
NULLIF ................................................................................................................................................................82
ZEROIFNULL ................................................................................................................................................83
COALESCE ......................................................................................................................................................84
CASE ......................................................................................................................................................................85
Basic Syntax ...................................................................................................................................................85
Advanced Syntax .........................................................................................................................................86
Horizontal Reporting ................................................................................................................................87
Nested CASE .................................................................................................................................................88
Views ......................................................................................................................................................................89
Create View Syntax ....................................................................................................................................89
DROP Views ....................................................................................................................................................90
REPLACE Views .........................................................................................................................................91
LOCKING FOR ACCESS ....................................................................................................................92
MACROS.........................................................................................................................................................93
CREATE Macro ............................................................................................................................................93
EXECUTE Macro ........................................................................................................................................94
REPLACE Macro .........................................................................................................................................95
DROP Macro ....................................................................................................................................................95
Transaction Processing ................................................................................................................96
Locking Modifiers .......................................................................................................................................96
Lock Types ......................................................................................................................................................96
Lock Syntax ....................................................................................................................................................96
The SQL Quick Reference Guide – Simplicity by Design VII
Table of Contents
Transaction Modes ......................................................................................................................................98
Transaction Mode Types ........................................................................................................................98
Setting the Transaction Mode .............................................................................................................99
Teradata Transaction Mode (BT/ET) ............................................................................................99
Commit Work .............................................................................................................................................. 100
Abort/Rollback ............................................................................................................................................ 100
Rollback Work ............................................................................................................................................ 101
ROLLBACK WORK ; ....................................................................................................................................... 101
Reporting Totals and Subtotals ..................................................................................... 102
Totals (WITH) ............................................................................................................................................... 102
Subtotals (WITH..BY) ........................................................................................................................... 103
Multiple WITH..Bys ................................................................................................................................ 104
Data Definition Language ..................................................................................................... 105
Create Table .................................................................................................................................................... 105
Multiple Column Primary Index ..................................................................................................... 106
SET | MULTISET Table ...................................................................................................................... 107
FALLBACK ................................................................................................................................................. 108
Permanent Journal .................................................................................................................................... 109
Add Column Attributes ......................................................................................................................... 110
Column and Table Constraints ......................................................................................................... 111
CREATE TABLE with copying an existing table .............................................................. 112
ALTER Table ................................................................................................................................................. 113
DROP Table .................................................................................................................................................... 114
RENAME Table .......................................................................................................................................... 115
Secondary Indexes ..................................................................................................................................... 116
Join Indexes ..................................................................................................................................................... 117
Collect Statistics .......................................................................................................................................... 118
HELP STATISTICS ................................................................................................................................ 119
DROP STATISTICS ............................................................................................................................... 119
CREATE DATABASE ......................................................................................................................... 120
CREATE USER ........................................................................................................................................... 121
DROP DATABASE or USER ......................................................................................................... 122
Hashing Functions ..................................................................................................................................... 123
HASHROW .................................................................................................................................................. 123
HASHBUCKET ......................................................................................................................................... 124
HASHAMP ................................................................................................................................................... 124
HASHBAKAMP ....................................................................................................................................... 124
Temporary Tables .............................................................................................................................. 125
Derived Tables .............................................................................................................................................. 125
Volatile Temporary Tables ................................................................................................................. 126
VIII The SQL Quick Reference Guide – Simplicity by Design
Table of Contents
Global Temporary Tables .................................................................................................................... 127
CREATE GLOBAL TEMPORARY TABLE ....................................................................... 127
DROP TEMPORARY TABLE ...................................................................................................... 128
Triggers .............................................................................................................................................................. 129
BEFORE Triggers ...................................................................................................................................... 129
AFTER Triggers .......................................................................................................................................... 130
INSTEAD OF Triggers .......................................................................................................................... 131
Sequencing Triggers ................................................................................................................................. 132
APPENDIX A: Current Reserved Words ...................................................... 133
Current Reserved Words (continued) ........................................................................................ 134
Current Reserved Words (continued) ........................................................................................ 135
Current Reserved Words (continued) ........................................................................................ 136
Future Reserved Words ......................................................................................................................... 137
APPENDIX B: Data Control Language (DCL)................................... 138
Data Control Language (DCL) Statements ........................................................................... 138
Privileges ........................................................................................................................................................... 138
GRANT Statement .................................................................................................................................... 139
REVOKE Statement ................................................................................................................................. 140
GIVE Statement ........................................................................................................................................... 141
Appendix C: Data Types and Format Symbols ................................. 142
Format Symbols ........................................................................................................................................... 143
Appendix D: Mathematical Functions ............................................................ 146
Appendix E: Qualifying and Table Aliasing ......................................... 147
Qualifying Column Names ................................................................................................................. 147
Creating an Alias for a Table ............................................................................................................ 148
Appendix F: Stored Procedure Syntax ........................................................... 149
The SQL Quick Reference Guide – Simplicity by Design IX
Simplicity by Design
Preface
“You miss 100% of the shots you don't take”
Wayne Gretzky
Asking the right questions is half the battle to greatly impacting the company’s bottom line,
but sometimes knowing the proper SQL inhibits users from taking their shot at corporate
greatness. This book is dedicated to assisting users in asking the right questions by
providing an easy to understand guide that takes the difficulty out of SQL.
The purpose of “SQL Reference Guide – Simplicity by Design” is simple: Users need an
easy and concise reference book at their fingertips that they can refer to, without having to
search through larger books for SQL help. After the generic syntax, there are applied
examples that have been written based on the SQL_CLASS database, which can be
www.CoffingDW.Com downloaded from our website at : .
The “SQL Reference Guide – Simplicity by Design” follows this format for each
command:
• SQL Command – Easy lookup with a great INDEX in the back
• Short Definition
• Syntax
• Examples
• Examples explained
• Hint Man - Tips from pros
• Issues – Common Mistakes
• Solutions to those issues
The standards for “SQL Reference Guide” are as follows:
<database-name> Substitute an actual database name in this location
<table -name> Substitute an actual table name in this location
<comparison> Substitute a comparison in this location, i.e. a=1
<column- name> Substitute an actual column name in this location
<data-value> Substitute a literal data value in this location
[ optional entry ] Everything between the [ ] is optional, not required to be valid
syntax , use when needed
{ use this | or this Use one of the keywords or symbols on either side of the “ | ”, } but not both. I.e. { LEFT | RIGHT } use either “LEFT” or
“RIGHT” but not both
The SQL Quick Reference Guide Page 1
The SQL Reference Guide
The Select Command
The SELECT Command selects which columns are needed for the report (or answer set)
and the tables that contain them.
SELECT { * }
FROM <table- name>;
SELECT * FROM Course_Table;
The asterisk returns every column in the table. The SELECT * relates to columns and the WHERE clause relates to rows selected.
Hint - Man
Issues: The message, “3807: Table/view/trigger ‘<table-name> does not exist.” will occur
when the table being selected from does not reside on Teradata. Or, you are in the
wrong database.
Solutions: Check the spelling of the <table -name>, use the SELECT DATABASE syntax to
confirm you are in the correct database or HELP DATABASE <database-name> to
see all objects in the database.
SELECT { <column-name> }
[…,<column-name> ]
FROM <table- name>;
SELECT Customer_Number FROM Customer_Table;
SELECT Dept_No
, Dept_Name FROM Department_Table;
When requesting multiple columns in a table each column is separated from the next by a comma. Experienced users often place the comma at the beginning for easy debugging.
Hint - Man
Issues: A missing comma could be a problem with this syntax. Here is the Error Message: 3810: Column ‘Column1Column2’ does not exist.
Solution: Search through the SQL code to locate the two columns with no comma between
the two, and place a comma. Or you could have an extra comma at the end of the
last column selected. Take the extra comma out.
Page 2 The SQL Quick Reference Guide
Simplicity by Design
The WHERE Clause
The WHERE clause eliminates certain ROWS from the result set and is used when users
don’t want to see every single row in a table.
SELECT { * | <column-name> }
[…,<column-name> ]
FROM <table- name>
WHERE { <column-name> | <expression> } <comparison> <data-value> ;
SELECT * FROM Employee_Table
WHERE Dept_No = 400;
English: The above example will SELECT all columns from the Employee_Table if the
employee’s department number is 400.
If a query has no WHERE clause then every row will be selected. If you want to access data as fast as possible use the Primary Index column in the WHERE clause.
Hint - Man
Issues: 3535: A character string failed conversion to a numeric value. The <data -value> in
the WHERE clause does not match the data type of the <column-name>. Also
remember that numeric values are not in single quotes ‘ ‘. Character data should be
in single quotes.
Solu tions: The first thing to do is to find out the data type of the <column-name> involved by
running HELP TABLE <table -name>. Next, adjust the <data -value> to match the
data type.
The SQL Quick Reference Guide Page 3
The SQL Reference Guide
Comparators: AND/OR
Many times a single comparison in a WHERE clause is not enough to specify the desired
rows. The AND/OR commands are called logical operators. The AND syntax requires
both comparisons to be true . The OR syntax however, only requires one of the two to
be true.
SELECT <column- name>
[…,<column-name> ]
FROM <table- name>
WHERE <column-name> <comparison> <data- value> AND | OR
<column- name> <comparison> <data-value>;
SELECT * FROM Order_Table
WHERE Customer_Number = 11111111
AND Order_Total > 10000;
English: Above we select all columns if the customer number = 11111111 AND the Order_Total is
greater than 10000. Both have to be true for data to come back.
SELECT Product_Id, Daily_Sales FROM Sales_Table
WHERE Sale_Date = ‘2000-09-28’
ORSale_Date = ‘2000-10-01’;
English: Above we select two columns for any row that has a sale date of eit her September 28 2000
or October 1 2000. Only one of them has to be true.
If you get a syntax error with an OR command it is probably because you did not name the column in the where clause twice. For example, you can’t say WHERE DEPT_NO = 10
OR 20. You must say WHERE DEPT_NO = 10 OR DEPT_NO = 20. Hint - Man
Issues: You get now rows coming back in the answer set
Solutions: Remember that when you use AND that you must utilize two different columns.
For example, an employee could not have a SALARY of $50,000 AND $75,000.You could however have an employee in department 100 AND have a salary of
$50,000.
Page 4 The SQL Quick Reference Guide
Simplicity by Design
Combining Comparators: AND/OR
SELECT <column- name>
[...,<column-name> ]
FROM <table- name>
WHERE ( <column- name> <comparison> <data-value> OR
<column- name> <comparison> <data-value> ) AND
<column- name> <comparison> <data-value> ;
SELECT Last_Name, First_Name FROM Student_Table
WHERE ( Class_Code = ‘JR’ ORClass_Code = ‘SO’ ) AND
Grade_Pt > 2.5;
English: The above selects two columns if the student has a Class_Code of ‘JR’ or ‘SO’ and that‘JR’ or ‘SO’ has a Grade_Pt above 2.5.
When there is an AND/OR combination the AND is always done first by Teradata unless the OR pair is in parentheses, like the above example.
Hint - Man
Issues: The data you expected to come back may not.
Solutions: You need to remember that when combining AND/OR comparators that Teradata
will analyze the AND first unless you place parenthesis around the OR statements.
The SQL Quick Reference Guide Page 5
The SQL Reference Guide
Combining Multiple AND Comparators or Multiple OR Comparators
SELECT <column- name>
[...,<column-name> ]
FROM <table- name>
WHERE <column-name> <comparison> <data- value>AND | OR
<column- name> <comparison> <data-value> AND | OR
<column- name> <comparison> <data-value>
SELECT * FROM Student_Course_Table
WHERE Student_Id = 280023 ORStudent_Id = 333450 ORStudent_Id = 231222;
English: Above we select every column from the row if the Student_Id is 280023 or 333450 or
231222.
SELECT Employee_No FROM Employee_Table
WHERE Dept_No <> 400 AND
Salary > 40000 ANDSalary < 50000;
English: Above we select one column from the row if the Dept_No is not equal to 400 and the
salary is greater than $40000, but less than $50000.
Dealing with NOT, AND an OR can be confusing. You can place parenthesis around the SQL and it will be evaluated first.
Hint - Man
Be careful when using multiple AND statements. Remember that ALL criteria must be met in order for the row to be returned in the result set. For example, a user should not
search for a student with a Grade_pt of 3.0 and 4.0. This will not work because nobody Hint - Man can have a Grade_pt of both 3.0 and 4.0. An OR should have possibly been used.
Page 6 The SQL Quick Reference Guide
Simplicity by Design
IS NULL Clause and IS NOT NULL Clause
NULL data is often described as empty data , but it is actually undetermined data. Therefore you can never check if something is EQUAL to NULL. You can only check if
something IS NULL or IS NOT NULL.
SELECT <column- name>
[...,<column-name> ]
FROM <table -name>
WHERE <column-name> IS NULL
SELECT Last_Name, First_Name FROM Student_Table
WHERE Grade_Pt IS NULL ;
English: Above we select two columns from any row that has a NULL value for Grade_pt.
SELECT Last_Name, First_Name FROM Student_Table
WHERE Grade_Pt IS NOT NULL ;
English: Above we select two columns from any row that does NOT have a NULL value for Grade_pt.
Sometimes when checking if something is = NULL you will get an error and sometimes
you will not get an error, but no rows will be returned. When checking for NULLS the
only valid statements are IS NULL or IS NOT NULL. Hint - Man
Issues: = NULL is not a valid SQL statement. Change the syntax to IS NULL.
3731: The user must use IS NULL or IS NOT NULL to test for NULL values.
Solution: Adjust the SQL syntax from ‘=NULL’ to ‘IS NULL’ or ‘IS NOT NULL’.
The SQL Quick Reference Guide Page 7
The SQL Reference Guide
NOT Clause
The NOT Clause will check for values that are NOT <, > or equal to a value . Teradatasearches for the logical opposite of the <comparison> statement.
SELECT <column- name>
FROM <table- name>
WHERE <column-name> NOT <comparison> <data-value> ;
SELECT Course_Name FROM Course_Table
WHERE Seats NOT >= 20;
English: Above we find all courses where there are less than 20 seats in the course.
SELECT Customer_Name, Phone_Number
FROM Customer_Table
WHERE Customer_Name NOT = ‘ACE Consulting’;
English: Above we SELECT two columns for all Customers except ‘ACE Consulting’.
Alternative Syntax:
SELECT <column- name>
FROM <table- name>
WHERE NOT ( <column-name> <comparison> <data- value> );
SELECT Course_Name FROM Course_Table
WHERE NOT ( Seats >= 20 ) ;
SELECT Customer_Name, Phone_Number
FROM Customer_Table
WHERE NOT ( Customer_Name = ‘ACE Consulting’ ) ;
Running this syntax without parentheses is permissible, but not recommended.
Hint - Man
Issues: Teradata returns the message: 3707: Syntax error, expected something like an ‘IN’
keyword between the ‘NOT’ keyword and ‘<comparison>’. This is a problem
caused by the ‘NOT’ not being properly placed in the SQL.
Solutions: Locate the ‘NOT’ in the SQL and place it directly before the <column-name>, with
the <comparison> after that.
Page 8 The SQL Quick Reference Guide
Simplicity by Design
IN and NOT IN
The IN comparison is an alternative to using one or more OR comparisons on the same
column in the WHERE clause of a SELECT. Teradata actually views the IN clause as a
multiple OR statement. If the criteria are in the <value - list>, a row will be returned.
SELECT <column- name>
[...,<column-name> ]
FROM <table -name>
WHERE <column-name> IN | NOT IN (<value -list>) ;
SELECT Dept_Name, Mgr_No FROM Department_Table
WHERE Dept_No IN ( 200, 300,100 ) ;
English: Above we select two columns from each row where the Dept_no is 200 or 300 or 100.
SELECT * FROM Order_Table
WHERE Order_Number NOT IN (123585, 123456 ) ;
English: Above we select all columns unless the Order_Number is 123585 or 123456.
SELECT * FROM Department_Table
WHERE Dept_Name IN ( ‘Sales’ , ‘Marketing’);
English: Above we select all columns from the Department_Table if the department name is Sales
or Marketing. Notice the single quotes around ‘Sales’ and ‘Marketing’. They are not numbers so
they need single quotes.
Do not place the word ‘NULL’ in the <value-list> for a ‘NOT IN’, being that no rows will be returned every time.
Hint - Man
Issues: 3706: Syntax error: expected something between an {integer | character-string} and
‘;’. This error is caused by a lack of parentheses around the <value -list>.
Solutions: Place a ‘(‘ before the <value -list> and a ‘)’ after the final entry in the <value - list>.
The SQL Quick Reference Guide Page 9
The SQL Reference Guide
= ANY, NOT = ALL
The =ANY command is the logical equivalent to the IN clause . The NOT = ALL
command is similar to the NOT IN clause.
SELECT <column- name>
[...,<column-name> ]
FROM <table -name>
WHERE <column-name> = ANY (<value -list>) ;
SELECT Dept_Name, Mgr_No FROM Department_Table
WHERE Dept_No = ANY ( 200, 300, 100) ;
The above example selects two columns if the Dept_No is 200 or 300 or 100. This English: is the same syntax as WHERE Dept_No IN (200, 300, 100).
SELECT <column- name>
[...,<column-name> ]
FROM <table -name>
WHERE <column-name> NOT = ALL (<value - list>) ;
SELECT * FROM Order_Table
WHERE Order_Number NOT = ALL ( 123585, 123456 ) ;
English: The above example will SELECT all columns WHERE the Order_Number does NOT =
123585 or 123456. This syntax is the same as NOT IN.
Be careful NOT to use NOT = ANY . This is because all rows will be returned unless they Are NULL. This is because the instance a value is not equal to any one in the list, it is
automatically returned. Hint - Man
Issues: Missing the ‘=’ sign is a possible problem.
3707: Syntax Error, expected something like an ‘IN’ keyword or a ‘LIKE’
keyword between the ‘NOT’ keyword and the ‘ALL’ keyword.
Solutions: Add the equal sign before the ‘ANY’ keyword, or after the ‘NOT’
keyword.
Page 10 The SQL Quick Reference Guide
Simplicity by Design
BETWEEN
The BETWEEN statement is another technique to request multiple values for a column that are all in a specific range. The key item to remember is that BETWEEN is inclusive and
most widely used with numeric values. If you write WHERE AGE is BETWEEN 13 and
15 then the answer set would contain individuals whose ages are 13, 14, or 15.
SELECT <column- name>
[...,<column-name> ]
FROM <table -name>
WHERE <column-name> BETWEEN <low-value> AND <high-value>;
SELECT * FROM Sales_Table
WHERE Daily_SalesBETWEEN 25000 AND 42000 ;
English: Select all columns where the Daily_Sales is between 25000 and 42000. This includes
25000 exactly and 42000 exactly.
SELECT Last_Name, First_Name, Grade_Pt FROM Student_Table
WHERE Last_Name
BETWEEN ‘Delaney’ and ‘Phillips’ ;
English: Select three columns where the Last_Name is between Delaney and Phillips. This
includes Delaney, Phillips and any name alphabetically greater than Delaney and Less than Phillip s.
BETWEEN is a command to look for ranges. BETWEEN works well with dates. If you index a date field in a table you can use the ORDER BY VALUES syntax when creating
the date index. Then BETWEEN and DATE ranges work in tandem. To see if a d ate is Hint - Man an index ORDERED BY VALUES run the SHOW TABLE <Tablename> command.
The SQL Quick Reference Guide Page 11
The SQL Reference Guide
LIKE Clause
The LIKE Command searches character data strings and can use wildcards to find datathat is similar. For example, a user can use the LIKE command to request rows where the
last_na me starts with ‘SM’.
SELECT <column- list>
FROM <table -name>
WHERE <column-name> LIKE ‘[<wildcard(s)>]<search-string>[<wildcard(s)>]’;
The wildcard characters are:
Wildcard symbol What it does
_ (underscore) matches any single character, but a character must be present
% (percent sign) matches any single character, a series of characters or the absence of characters
SELECT Course_Name, Course_Id FROM Course_Table
WHERE Course_Name LIKE ‘%SQL’ ;
English: Select two columns from the rows in the course table if Course_Name has SQL at the end
of the string.
SELECT * FROM Student_Table WHERE Last_Name LIKE ‘_m%’ ;
English: Select all columns from the rows in the Student table if Last_Name has an m as the second
character.
LIKE works on Character Data. If I have a name that is CHAR(10) and a name such as Smith then the system sees the name as ‘Smith ‘. Notice the 5 extra spaces. You can
use the TRIM function with the LIKE function to find anyone whose name ended in h. Hint - Man SELECT * FROM Student_Table WHERE TRIM(Last_Name) LIKE ‘%h’;
Issues: The LIKE statement is not returning all the rows expected to be in the result set.
More than likely you are dealing with Character strings of CHAR data type.
Remembe r ‘Smith’ in the eyes of Teradata is ‘Smith+ empty space’. This empty
space resides in the rest of the fixed data space on the system.
Solutions: There are two solutions to this problem. The first solution is to place a ‘%’ at the
end of the <search-string>, as in the second example. The second solution would
be to place the <column-name> in a TRIM function as so: TRIM(<column-name>.
Either solution will take care of the problem.
Page 12 The SQL Quick Reference Guide
Simplicity by Design
Aliasing Columns
You create an ALIAS on a column for the purpose of giving the column a new name . You might do this to shorten the name or to better describe a title you want to see as a
column header. If you ALIAS and use a reserved word such as SELECT place double
quotes around it.
In giving a column an alias, there are two options:
ANSI Standard:
SELECT <column- name> AS <alias-name>
FROM <table- name>;
Teradata Standard:
SELECT <column- name> < alias-name >
FROM <table- name>;
SELECT Dept_No AS DEPT
,Dept_Name AS “Department Name”
,Mgr_No Manager
FROM Department_Table
ORDER BY “Department Name”;
English: We have aliased three columns. The first column does not need double quotes. Thesecond column needs them because there is a space between Department and Name. The third
ALIAS does not have the word AS. The word AS is optiona l when aliasing. Also notice we are
sorting by “Department Name”. We once again use the double quotes.
If a user desires to assign an alias with a space like “Department Name”, be sure to use double quotes around the alias name, otherwise you don’t need the quotes. For example,
Department_Name does not need quotes. Hint - Man
Issues: A common error is using a Teradata Reserved Word for an alias.
3707: Syntax Error, expected something like a name between the {‘AS’ | ‘NAMED’} keyword and the ‘<reserved-word>’ keyword.
Solutions: You can place double quotes around the ALIAS name and it is no longerconsidered a keyword in the query. For example, if you had an ALIAS named
MAX you could place double quotes around it to become “MAX”.
The SQL Quick Reference Guide Page 13
The SQL Reference Guide
ALIAS using NAMED
Teradata Extension that is used to alias a column. Once you use the NAMED command
you must refer to the column with its new name. You can also sort by the new name.
SELECT <column- name> ( NAMED <alias -name> )
FROM <table- name> ;
SELECT Dept_No, Dept_Name (NAMED “Department Name”)FROM Department_Table;
English: The above example is aliasing Dept_Name as “Department Name”. Notice the double
quotes. This is because there is a space between Department and Name. If the alias had been
Department_Name we would not need the double quotes.
Some time after Teradata V2R5 this function will no longer be available. Remember to place double quotes around any aliases with spaces in them, or if they are Teradata
Reserved Words. Hint - Man
Issues: A common error is using a Terada ta Reserved Word for an alias. 3707: Syntax Error, expected something like a name between the {‘AS’ |
‘NAMED’} keyword and the ‘<reserved-word>’ keyword.
Solutions: For reserved word errors place double quotes around the ALIAS name and
Teradata will accept the ALIAS. For example, if you had an ALIAS named MAX
you could place double quotes around it to become “MAX”.
Page 14 The SQL Quick Reference Guide
Simplicity by Design
ORDER BY Clause
Teradata brings back data unsorted unless you use the ORDER BY statement. The
ORDER BY statement will sort the given <column-name> in the desired order . The
default for Teradata is ascending order .
SELECT <column- name>
[...,<column-name>]
FROM <table- name>
ORDER BY { <column-name> | <relative-column-number> } [ ASC | DESC ]
{…, <column-name> | <relative-column-number> } [ ASC | DESC ] ;
SELECT Course_Id, Course_Name FROM Course_Table
ORDER BY 1 ;
English: The above will sort by the first column in the list which is the same thing as stating
ORDER BY Course_Id .
SELECT Customer_Number, Order_Number, Order_TotalFROM Order_Table
ORDER BY Customer_Number DESC, Order_Number ;
English: The above will sort by the Customer_Number in Descending order as the first sort key
and then Order_Number as the second order key. ASC is the default.
Teradata allows the ORDER BY statement to use a column name or number. If you ORDER BY 1 for example Teradata will order by the first column in your select list. If
you said ORDER BY 1 and your select list was SELECT * then Teradata will ORDER Hint - Man BY the 1 column in the table. s t
Issues: 3637: Invalid ORDER BY constant. This error occurs when using the number of a
column rather than its name in the ORDER BY clause. In most cases the number
used is larger than the actual count of columns involved in the query.
Solutions: Identifying how many columns should be returned to the result set is the first thing
to do. Next, find the proper number for the column, or columns desired in the
ORDER BY and adjust the SQL.
The SQL Quick Reference Guide Page 15
The SQL Reference Guide
DISTINCT
If there are duplicate values in <column-name> Teradata will return all rows. Distinct allows the user to eliminate all the duplicates and only return one instance of that value.
SELECT DISTINCT <column- name>
[…, <column-name> … ]
FROM <table- name>;
SELECT DISTINCT Student_Id
FROM Student_Course_Table;
English: SELECT every distinct Student_Id from the Student_Course_Table. No duplicate
Student_Ids will be returned.
SELECT DISTINCT First_Name, Dept_No
FROM Employee_Table ;
English: SELECT every distinct combination of First_Name and Dept_No. For example, Mary in
Dept_No 10 is different than Mary in Dept_No 20. Both would be returned.
This is a useful function but this may cause inaccurate results. The issue with DISTINCT is that it affects all the columns desired in the result set. If there are two
columns in the query, Teradata will search for a unique combination of both. In the second Hint - Man example, the rows returned will be any distinct combinations of First_Name and Dept_No.
Often users will either use DISTINCT or GROUP BY for the same purpose. DISTINCT Is faster when there are only a few duplicates and GROUP BY is faster when there are
Many duplicates. Hint - Man
Page 16 The SQL Quick Reference Guide
Simplicity by Design
Help, Show, Explain, User Information Functions
HELP
The Help Function returns important information regarding the object specified in the
SQL. Results include columns involved in the object, the data type, parameters passed,
table and column comments, etc.
HELP <OBJECT> <Object Name>;
Object Choices:
Database User Table
Volatile Table View Macro
Procedure Trigger Column
Index Statistics Session
HELP Database SQL_CLASS;
HELP Table SQL_CLASS.Student_Table;
HELP Column Course_Table.Course_Name;
HELP Session;
HELP ‘SQL | <Function>’;
HELP ‘SQL Create’;
HELP ‘SQL Explain’;
Issues: A common problem is that an object does not exist. Object <object-name> does
not exist .
Solutions: The easiest and quickest solution is to execute the HELP DATABASE <database- name> command to see what objects are in the database. You might have
misspelled the object name or are pointing to the wrong database. The HELP
SESSION command will tell you what Database you are currently in.
The SQL Quick Reference Guide Page 17
The SQL Reference Guide
SHOW
Teradata will return the actual DDL/Create Text for the given object in the SQL. This is
handy if a user needs to create an object identical or similar in structure. You can also use
this to see what indexes are on a table.
SHOW<OBJECT> <object name>;
Object Choices:
Table View Macro
Trigger Procedure
SHOW Table Department_Table;
SHOW View Department_Table_v;
SHOW Macro SQL_CLASS.Department_Count_m;
SHOW Trigger Update_Department_t;
SHOW Procedure Department_Count_p;
Issues: Object does not exist error code: <object-type> <object-name> does not exist.
Solutions: The first item is to check the spelling of the <object-name> to ensure proper
spelling. The next choice is to simply run the HELP DATABASE <database-
name> command to get a list of all the objects in the database where you believe
the object is located. You can also see which da tabase you are currently point to
with the HELP SESSION command.
The SHOW command is great if you want to see columns definitions, what indexes are defined, and any constraints in the table. If you have to change a view, macro, or
stored procedure with the replace command it is a great idea to do the show command and Hint - Man then copy the current structure to make the necessary changes.
Page 18 The SQL Quick Reference Guide
Simplicity by Design
EXPLAIN
Returns the Optimizer’s plan of how the Teradata system will perform the given SQLrequest. This plan will include information on indexes being used, estimated time for query
execution, estimated range of rows returned, and information about the spool space used
during the query.
EXPLAIN <SQL command>;
EXPLAIN
SELECT * FROM Student_Course_Table;
EXPLAIN
SELECT last_name, first_nameFROM Employee_Table
WHERE Salary > 45000;
EXPLAIN
SELECT Customer_Number, Customer_Name
FROM Customer_Table AS a INNER JOIN Order_Table AS bON a.customer_number = b.customer_number;
It is always recommended to run an EXPLAIN on any new query involving large tables,
or vital tables that are frequently accessed. The EXPLAIN will also tell you the strategy
for joins or the indexes being utilized for a particular query. Hint - Man
The SQL Quick Reference Guide Page 19
The SQL Reference Guide
User Information Functions
Default Database Command
Moves the scope of the user from one database to <Database Name>. This command can
eliminate the need to qualify a table in a certain database.
Database <Database Name>;
DATABASE SQL_CLASS;
AccountReturns the account number for the current user you are logged in as.
Select ACCOUNT ;
SELECT Database Command
This command displays the database that the user iscurrently located .
Select DATABASE ;
SESSION
Retrieves thesession number about the current user.
Select SESSION ;
Page 20 The SQL Quick Reference Guide
Simplicity by Design
Data Conversions
CAST – ANSI
Cast is an ANSI standard function that converts a <column-name> from one data typefor another . This allows for flexibility in creating reports and performing calculations on
non-like data type columns.
SELECT CAST( <column-name> AS <data-type>[(<length>)] )
FROM <table- name> ;
SELECT CAST(Student_id as CHAR(10)) FROM Student_Table;
English: The example above will SELECT the Student_id from the Student_Table and display it asa Character 10 data type. The actual table is unaffected.
Implied Cast – Teradata
This is a Teradata Extension for the ANSI Cast function. It transforms a <column-name>
to another data type to easier perform calculations and reporting.
SELECT <column- name> ( <data-type> [(<length>)]
FROM <table- name>;
SELECT Student_id (CHAR(10)) FROM Student_Table;
Be careful because the results may vary between the Implied Cast and ANSI Standard
CAST.
Hint - Man
Issues: When using these syntaxes a user may run into this error message: 2617: Overflow
occurred computing an expression involving <table-name>.<column -name> . This
tells the user that the <data -type> the <column-name> is being cast to is not large
enough to accommodate the transformation.
Solutions: The best solution would be to perform a HELP TABLE <table -name> to discover the actual data type of the <column-name>. Once that is established, choose a
proper sized data type to transform the <column-name> and change the SQL.
The SQL Quick Reference Guide Page 21
The SQL Reference Guide
FORMAT
Formatting is mainly used to make the reporting of the data easier to read. This is a key
way to truncate data when using a tool like BTEQ, but truncation will not work in ANSI
mode.
SELECT <column- name> (FORMAT <format-scheme>)
FROM <table- name>;
SELECT Customer_Number (FORMAT ‘99999999’) , Order_date (FORMAT ‘YYYY-MM-DD’)
FROM Order_Table;
English: The above example will SELECT two columns from the Order_Table and format the
Customer_Number as 99999999 and Order_Date as YYYY-MM-DD.
Remember when using Queryman the FORMAT function will not be acknowledged by
the ODBC driver and therefore won’t work. Refer to the following sub-section titled
“Tricking the ODBC to Format”. We have found a way to get the FORMAT function toHint - Man work in Queryman.
Tricking the ODBC to Format
Tricking the ODBC is important to know because most users work with applications that
communicate with Teradata using ODBC. This trick is essential in making data format inthe desired manner.
SELECT CAST( ( <data> (FORMAT ‘<format- string’ ) ) AS CHAR(<length>) )
FROM <table- name>;
SELECT CAST(( Student_Id (FORMAT ‘X(10)’)) AS CHAR(10))
FROM Student_Table;
English: The example above will CAST the student_Id as a Character 10. This will allow for the
format statement to work with Queryman. Anytime you want the format statement to work in
Queryman you can cast the result as a character.
The Format statement works in BTEQ. Although it will NOT cause an error in Queryman
The Format will not take in Queryman. By casting the results as character data the format
will work in Queryman. This is a great tip. Hint - Man
Page 22 The SQL Quick Reference Guide
Simplicity by Design
TITLE
This syntax changes the name of a <column-name> only in the heading of the result set , not as the SQL itself. It does not perform like creating an alias.
SELECT <column- name> (TITLE ‘Column title to appear in output’)
, <column- name> (TITLE ‘Level 1 // Level 2 // Level 3’)FROM <table -name>;
SELECT Student_id (TITLE ‘Student // Identification’) ,Grade_Pt (TITLE ‘GPA’)
FROM Student_Table;
English: The above example will TITLE the student Id as Student on the top line and Identification
on the bottom. This is how you stack and can have up to 3 stacks. The stacking feature does notwork in Queryman. The Grade_Pt will have a TITLE of GPA. Sometime s Queryman does not always TITLE what you want.
TITLE is more functional in BTEQ due to the ability to stack the Title in the column
header, which Queryman cannot do. TITLE is only used to Title a column. You can
give a column both a Title and an Alias. The Title is for the title and the Alias is a new way to refer to the column. You can sort with the ALIAS name, but NOT the Title.
Hint - Man
Issues: A common error message when dealing with TITLE is, “3707: Syntax error,
expected something like a string between the ‘TITLE’ keyword and the word
‘Column title to appear in output’.” Teradata is saying that your title needs single
quotes around it.
Solutions: The solution is simple: Place single quotes around the title.
The SQL Quick Reference Guide Page 23
The SQL Reference Guide
CASESPECIFIC
Forces Teradata to compare the given data values with awareness of the difference
between lower case and upper case characters.
SELECT <column- name>
[...,<column-name>]
FROM <table- name>
WHERE <column-name>( CASESPECIFIC ) ={‘<character-literal>’ | <column- name>};
SELECT Customer_Name, Customer_Number
FROM Customer_Table
WHERE Customer_Name (CASESPECIFIC) = ‘ACE Consulting’ ;
English: The above makes Customer_Name CASESPECIFIC so the comparison of Customer_Name must be equal to ACE Consulting with exact upper and lower case characters.
CASESPECIFIC is usually utilized in ANSI mode because ANSI is Case Specific. Teradata Mode is NOT Case Specific so Teradata sees ‘abc’ exactly the same as ‘ABC’.
ANSI Mode does not see ‘abc’ as the same thing as ‘ABC’.
Hint - Man
Issues: 3706: Syntax error: expected something between the word ‘<word1>’ and
‘<word2>’.
This error message usually indicates the lack of single quotes around the
<character-literal> in the SQL.
Solutions: Locate the <character-literal> string in the code and place single quotes around it.
Page 24 The SQL Quick Reference Guide
Simplicity by Design
NOT CASESPECIFIC
Turns off the need to test for upper case or lower case characters. This only needs to be
used while a user is in ANSI Mode .
SELECT <column- name>
[...,<column-name>]
FROM <table- name>
WHERE <column-name> ( NOT CASESPECIFIC ) =
{ ‘<character-literal>’ | <column- name> };
SELECT Customer_Name, Customer_Number
FROM Customer_Table
WHERE Customer_Name (NOT CASESPECIFIC) = ‘ACE Consulting’ ;
English: The above makes Customer_Name NOT CASESPECIFIC so the comparison of
Customer_Name must equal ACE Consulting, but without exact upper and lowercase characters.
NOT CASESPECIFIC is usually utilized in ANSI mode because ANSI is Case Specific. Teradata Mode is NOT Case Specific so Teradata sees ‘abc’ exactly the same as ‘ABC’.
ANSI Mode does not see ‘abc’ as the same thing as ‘ABC’.
Hint - Man
Issues: 3706: Syntax error: expected something between the word ‘<word1>’ and
‘<word2>’.
This error message usually indicates the lack of single quotes around the
<character-literal> in the SQL.
Solutions: Locate the <character-literal> string in the code and place single quotes around it.
The SQL Quick Reference Guide Page 25
The SQL Reference Guide
LOWER and UPPER
The Lower Function changes all the characters in <column- name> to lower case before
any testing is performed. The Upper Function transforms all the characters in <column-
name> to upper case prior to any testing of criteria.
SELECT LOWER (<column- name>)
FROM <table- name>
[WHERELOWER (<column- name>) = { ‘<character-literal>’ | <column- name> }];
SELECT LOWER (Course_Name) FROM Course_Table
WHERE LOWER (Course_Name) = ‘database administration’ ;
English: The above example will display Course_Name in lower case and in the WHERE clause
the comparison of Course_Name will be converted to lowercase before the comparison.
SELECT LOWER(Dept_Name) FROM Department_Table;
English: The above example will SELECT Dept_Name from the Department_Table and display
the Dept_Name in all lowercase.
SELECT UPPER (<column- name>)
FROM <table- name>
[WHEREUPPER (<column- name>) = { ‘<character-literal>’ | <column- name> }];
SELECT UPPER(Course_Name) FROM Course_Table
WHERE Upper(Course_Name) =‘DATABASE ADMINISTRATION’ ;
English: The Course_Name that is selected will be displayed in UPPER Case. The WHERE clause
will also convert Course_Name to UPPER Case in the comparison.
SELECT UPPER (Dept_Name) FROM Department_Table;
English: The Dept_Name will be displayed in uppercase.
Page 26 The SQL Quick Reference Guide
Simplicity by Design
Aggregation Functions
The focus of aggregates is to summarize the values of data in a given column. Aggregates
produce one- line answers for SUM, MAX, MIN, AVG, and COUNT. The main thing to
remember is that aggregates remove any type of detail on that column. It’s important to
know that all the aggregate functions ignore NULL values in the respective calculations.
SUM Function
A user performs this function to add up all the values in the <column- name> and returns
that final value in the result set.
SELECT SUM(<column-name>)
[...,<column-name>]
FROM <table- name>
[WHERE <column- name> <comparison> <value>]
[GROUP BY <column- name>]
[ORDER BY <column-name>];
SELECT SUM(Budget) FROM Department_Table;
SELECT Dept_No, SUM(Salary)FROM Employee_Table
GROUP BY Dept_No ;
SELECT SUM(Daily_Sales) , Product_Id FROM Sales_Table
GROUP BY 2
ORDER BY Product_Id;
GROUP BY is used when a non-aggregate column is in the Select Statement. All non- aggregate columns are required to be in the GROUP BY Statement. The GROUP By
statement will allow you to get aggregates for each GROUP.
Hint - Man
Issues: The most common error with Aggregates is not using GROUP BY with non- aggregate columns. 3504: Selected non-aggregate values must be part of the
associated group.
Solutions: Search through the SQL and find all the columns that are not involved in aggregate
functions. We call these non-aggregates. Next, write a GROUP BY statement with
all the non-aggregate columns, with the desired sequence of grouping. Column
names or numbers are admissible.
The SQL Quick Reference Guide Page 27
The SQL Reference Guide
AVERAGE Function
(AVG)
Teradata returns a calculated average on the given <column- name>. This calculation, like
all other aggregates, is not affected by NULL va lues.
SELECT AVG(<column-name>)
[...,<column-name>]
FROM <table- name>
[WHERE <column- name> <comparison> <value>]
[GROUP BY <column- name>]
[ORDER BY <column-name>];
SELECT AVG(Budget) FROM Department_Table;
SELECT Dept_No, AVG(Salary) FROM Employee_Table
GROUP BY 1 ;
SELECT AVG(Daily_Sales) , Product_Id FROM Sales_Table
GROUP BY Product_Id
ORDER BY Product_Id;
English: In the above examples you see that we are looking for the Averages as our chosen
aggregate. Also notice in some of the examples we are also looking for Dept_No or Product_Id.
These are non-aggregates and so the Group By statement must be used.
GROUP BY is used when a non-aggregate column is in the Select Statement. All non- aggregate columns are required to be in the GROUP BY Statement. The GROUP By
statement will allow you to get aggregates for each GROUP.
Hint - Man
Issues: The most common error with Aggregates is not using GROUP BY with non-
aggregate columns. 3504: Selected non-aggregate values must be part of the
associated group.
Solutions: Search through the SQL and find all the columns that do are not involved in
aggregate functions. We call these non-aggregates. Next, write a GROUP BY
statement with all the non-aggregate columns, with the desired sequence of grouping. Column names or numbers are admissible.
Page 28 The SQL Quick Reference Guide
Simplicity by Design
MINIMUM Function (MIN)
This function searches through all the values of the <column- name> and returns the
smallestvalue to the result set.
SELECT MIN(<column-name>)
[...,<column-name>]
FROM <table- name>
[WHERE <column- name> <comparison> <value>]
[GROUP BY <column- name>]
[ORDER BY <column-name>];
SELECT MIN(Budget) FROM Department_Table;
SELECT Dept_No, MIN(Salary) FROM Employee_Table
GROUP BY 1 ;
SELECT MIN(Daily_Sales) , Product_Id FROM Sales_Table
GROUP BY Product_Id
ORDER BY Product_Id;
English: Notice that in our last two examples we are using the Group By statement because we
have non-aggregates in Dept_No and Product_Id. Notice that we can say Group By 1 meaning thefirst column in our select list or GROUP BY Product Id actually specifying the name.
GROUP BY is used when a non-aggregate column is in the Select Statement. All non- aggregate columns are required to be in the GROUP BY Statement. The GROUP By
statement will allow you to get aggregates for each GROUP.
Hint - Man
Issues: The most common error with Aggregates is not using GROUP BY with non- aggregate columns. 3504: Selected non-aggregate values must be part of theassociated group.
Solutions: Search through the SQL and find all the columns that do are not involved in
aggregate functions. We call these non-aggregates. Next, write a GROUP BY
statement with all the non-aggregate columns, with the desired sequence of grouping. Column names or numbers are admissible.
The SQL Quick Reference Guide Page 29
The SQL Reference Guide
MAXIMUM Function (MAX)
Aggregate function that will return the l argest value in the <column- name> of the MAX
function.
SELECT MAX(<column-name>)
[...,<column-name>]
FROM <table- name>
[WHERE <column- name> <comparison> <value>]
[GROUP BY <column- name>]
[ORDER BY <column-name>];
SELECT MAX(Budget) FROM Department_Table;
SELECT Dept_No, MAX(Salary) FROM Employee_Table
GROUP BY Dept_No ;
SELECT MAX(Daily_Sales) , Product_Id FROM Sales_Table
GROUP BY 2
ORDER BY Product_Id;
GROUP BY is used when a non-aggregate column is in the Select Statement. All non- aggregate columns are required to be in the GROUP BY Statement. The GROUP By
statement will allow you to get aggregates for each GROUP.
Hint - Man
Issues: The most common error with Aggregates is not using GROUP BY with non- aggregate columns. 3504: Selected non-aggregate values must be part of the
associated group.
Solutions: Search through the SQL and find all the columns that do are not involved in
aggregate functions. We call these non-aggregates. Next, write a GROUP BY
statement with all the non-aggregate columns, with the desired sequence of grouping. Column names or numbers are admissible.
Page 30 The SQL Quick Reference Guide
Simplicity by Design
COUNT Function (COUNT)
This function performs a count of the number of values in the <column-name> that exist. A COUNT(*) will be sure to include all NULLs, with it counting the number of rows, not
the number of values in a column.
SELECT COUNT(<column-name>)
[...,<column-name>]
FROM <table- name>
[WHERE <column- name> <comparison> <value>]
[GROUP BY <column- name>]
[ORDER BY <column-name>];
SELECT COUNT(*) FROM Department_Table;
SELECT Dept_No, COUNT(Salary) FROM Employee_Table
GROUP BY Dept_No ;
SELECT COUNT(Daily_Sales) , Product_Id FROM Sales_Table
GROUP BY 2
ORDER BY Product_Id;
GROUP BY is used when a non-aggregate column is in the Select Statement. All non- aggregate columns are required to be in the GROUP BY Statement. The GROUP By
statement will allow you to get aggregates for each GROUP.
Hint - Man
Issues: The most common error with Aggregates is not using GROUP BY with non- aggregate columns. 3504: Selected non-aggregate values must be part of the
associated group.
Solutions: Search through the SQL and find all the columns that do are not involved in
aggregate functions. We call these non-aggregates. Next, write a GROUP BY
statement with all the non-aggregate columns, with the desired sequence of grouping. Column names or numbers are admissible.
The SQL Quick Reference Guide Page 31
The SQL Reference Guide
HAVING Clause
The HAVING clause serves the same purpose of the WHERE clause by eliminating
certain rows from the result set. Teradata performs the aggregate functions, then
HAVIN G serves as a final filter before the results are returned.
SELECT <aggregate- function> (<column-name>)
[...,<column-name>]
FROM <table- name>
HAVING <limiting -constraint> ;
SELECT Dept_No, SUM(Salary) as Total_Sal , AVG(Salary) FROM Employee_Ta ble
HAVING Total_Sal > 120000
GROUP BY Dept_No;
English: In the above example we are selecting Dept_No (a non-aggregate) and SUM of Salary and
AVG of Salary. We are using the GROUP BY statement on the Dept_No and getting our
aggregates for every Dept_No. Then the Having statement will check the SUM(Salary) for a final check to see if the SUM(Salary) aliased as Total_Sal is greater than 120000. If not the group is
eliminated.
WHERE and HAVING are similar but different. WHERE eliminates the base rows
selected for calculation. HAVING has no effect on the base rows. HAVING waits until the aggregate calculation is complete and then eliminates any groups who don’t meet the
HAVING condition. The HAVING clause is the WHERE clause for aggregate groups.
Hint - Man
Page 32 The SQL Quick Reference Guide
Simplicity by Design
Subquery
Subqueries are queries that retrieve information and pass that information to other parts of
the query as a list of values. You can have multiple subqueries in a query. Normal
Subqueries run the bottom query first which passes a list of values to the top query. The
main indicator of a subquery is the WHERE IN or WHERE NOT IN clause.
SELECT <column- name>
[...,<column-name>]
FROM <table -name>
WHERE <column-name>[..., <column-name> ] [ NOT ] IN
( SELECT <column-name> […,<column-name> ]
FROM <table-name>
[ WHERE <column-name>[…, <column-name> ]
) ;
SELECT Employee_No, Last_Name, First_Name
FROM Employee_Table
WHERE Dept_No IN
(SELECT Dept_No FROM Department_TableWHERE Dept_Name LIKE ‘Sale%’) ;
Teradata allows a maximum of 63 subqueries in one SQL statement. Each subquery passes a list of values to be used by the query above.
Hint - Man
Issues: If your query is not bringing back any rows you may have made a logical mistake.The biggest logical mistake with a subquery involves the borders between the top
and bottom query. Here is an example of a correct subquery. Make sure you have
the bolded areas a Primary Key in one table and a Foreign Key in another table.
SELECT * FROM Student_Table WHERE Student_Id IN (SELECT Student_Id FROM Student_Course_Table
WHERE Credits > 3);
Solution: Make sure your bottom query is passing values to the top query that match. If you
are using different tables for the two queries then the bolded values need to be from
the same domain. In other words match apples with apples and in most cases the
columns will be a Primary Key in one table and a Foreign Key in another table.
The SQL Quick Reference Guide Page 33
The SQL Reference Guide
Multiple Subqueries
Multiple Subqueries can have as many as 63 separate subqueries . This flexibility in
Teradata is one more reason why Teradata is the Best in the World!
SELECT <column- name>
[...,<column-name>]
FROM <table -name>
WHERE <column-name>[..., <column-name> ] [ NOT ] IN
( SELECT <column-name> […,<column-name> ]
FROM <table- name>
[ WHERE <column- name>[…, <column- name> [ NOT ] IN
( SELECT <column-name> […,<column-name> ]
FROM <table-name>
[ WHERE <column-name>[…, <column-name> ];
));
SELECT Last_Name, First_Name FROM Student_Table
WHERE Student_Id IN
(SELECT Student_Id FROM Student_Course_Table
WHERE Course_Id IN
(SELECT Course_Id FROM Course_Table
WHERE Course_Name = ‘Teradata Concepts’)) ;
When developing code for multiple subqueries, keep in mind how they are processed: from the ground up. The last subquery is performed first and sends the result set to the
subquery above it.
Hint - Man
Issues: A missing parentheses is one of the most common errors when dealing with
subqueries. Always be sure that each ‘(‘ has a matching ‘)’ in the SQL. The error
for a missing parentheses may look like this: 3707: Syntax error, expected
something like an ‘EXCEPT’ keyword or an ‘UNION’ keyword or a ‘MINUS’
keyword or ‘)’ between ‘)’ and ‘;’.
Solutions: The best means of solving this issue is to start with the first ‘(‘ and find the ‘)’ that
is paired with it. Then move to the second ‘(‘ and find its partner ‘)’, and continuethis process until all the ‘(‘ have a paired up ‘)’. If there is a ‘(‘ with no pair place a
‘)’ at the end of the SQL before the semi-colon.
Page 34 The SQL Quick Reference Guide
Simplicity by Design
Quantifiers
These symbols serve as replacements for the IN or NOT IN clause.
SELECT <column- name>
[...,<column-name>]
FROM <table -name>
WHERE <column-name>[..., <column-name> ]
{ = | > | < | >= | <= | <> } {ANY | ALL }
( SELECT <column-name> […,<column-name> ]
FROM <table- name>
[ WHERE <column- name>[…, <column- name> ]
);
SELECT Customer_Name, Phone_Number FROM Customer_TableWHERE Customer_Number = ANY
(SELECT Customer_Number from Order_Table) ;
English: The above query SELECTS two columns from the Customer_Table if thecustomer has placed an order in the Order_Table.
The = ANY quantifier is the equivalent to IN, as NOT = ALL is equivalent to NOT IN.
Hint - Man
The SQL Quick Reference Guide Page 35
The SQL Reference Guide
Correlated Subquery
A correlated subquery works backwards compared to regular subqueries. It reads one row
in the main query, then performs the subquery and returns the top row if it meets the
criteria from the bottom query. Then it reads the second row, and so forth. This type of
subquery performs quite efficiently in Teradata and is extremely powerful.
SELECT <column- name>
[...,<column-name> ]
FROM <table-name1> [ AS <table1-alias>]
WHERE <column-name> { = | < | > | <= | >= | <> }
( SELECT { MIN | MAX | AVG } (<column-name>)
FROM <table-name2> [AS <table2- alias> ]
WHERE <table1-alias>.<column-name>=<table2-alias>.<column-name> ) ;
SELECT Last_Name, First_Name, Dept_No, Salary
empFROM Employee_Table as
WHERE Salary =
emt (SELECT MAX(Salary) FROM Employee_Table as
emp emt WHERE .Dept_No = .Dept_No);
You can recognize a correlated subquery by the WHERE clause in the bottom query. The
last WHERE clause will compare a value from the top query with a value from the bottom
query. That correlates the top and bottom queries together. Notice the aliasing in the
example.
Hint - Man
Issues: Using a correlated subquery without an aggregate function will produce this error
message: 3669: More than one value was returned by a subquery.
Solutions: The solution is to place one of the aggregate functions in the subquery.
*For more information on Table -Aliasing, refer to Appendix E.
Page 36 The SQL Quick Reference Guide
Simplicity by Design
Exists
Using this syntax allows for Teradata to perform a true -false test within the WHERE
clause . The system will return either one or zero rows to satisfy the test.
SELECT <column- name>
[...,<column-name> ]
FROM <table- name1> [AS <table1-alias>]
WHERE [ NOT ] EXISTS( SELECT <column-name> [...,<column-name> ]
FROM <table- name> [AS <table2-alias>]
WHERE <table1- alias>.<column-name> =
<table2-alias>.<column- name>) ;
SELECT Customer_Name
FROM Customer_Table AS CUST
WHERE EXISTS
(SELECT * FROM Order_Table AS OT
WHERE CUST.Customer_Number =OT.Customer_Number) ;
English: The above selects the Customer_Name if a customer has placed a current order.
SELECT Course_Name
FROM Course_Table AS Course
WHERE NOT EXISTS
(SELECT * FROM Student_Course_Table AS STU
WHERE COURSE.Course_Id = STU.Course_Id) ;
English: The above selects the Course_Name if no students are enrolled.
This is great SQL to use for testing queries prior to putting them into production. You can use EXISTs to see if certain values exist in the database.
Hint - Man
Issues: 3707: Syntax error, expected something like an ‘EXCEPT’ keyword or an
‘UNION’ keyword or a ‘MINUS’ keyword or ‘)’ between ‘)’ and ‘;’. This error will be produced when there is an unneeded semi-colon inside the subquery.
Solutions: Search for the end of the subquery which is indicated by the ‘)’ and remove the
semi-colon inside the ‘)’.
The SQL Quick Reference Guide Page 37
The SQL Reference Guide
Joins
Original Join Syntax
A join involves two or more tables in the same FROM clause of a single SELECT
statement. Teradata is brilliant at performing joins.
SELECT [<table- name>.]<column- name>
[...,<table- name>.<column-name> ]
FROM <table-name> [ AS <table1-alias> ]
,<table-name> [ AS <table2-alias> ]
[ { WHERE [<table1-alias>.]<column-name>= [<table2-alias>.]<column-name> ]
[ … AND [<table1-alias>.]<column-name> = [<table2-alias>.]<column-name> ][ { … AND | OR } <column-name = <data-value> ]
| WHERE <column-name = <data-value> } ] ;
SELECT Employee_No, Last_Name, First_Name,
Dept_Name, dept.Dept_No
FROM Employee_Table AS emp, Department_Table AS dept WHERE emp.Dept_No = dept.Dept_No ;
English: The above example SELECTS 3 columns from the Employee_Table and two columns
from the Department_Table and joins them together.
SELECT STU.Student_Id, Last_Name, First_Name, Course_Name
FROM Student_Table AS STU, Course_Table AS COUR, Student_Course_Table AS STU_COUR
WHERE STU.Student_Id = STU_COUR.Student_Id
AND COUR.Course_Id = STU_COUR.Course_Id ;
English: The above example joins 3 tables together. Notice the WHERE clause joins the
Student_Table with the Student_Course_Table and then the Course_Table with the
Student_Course_Table. The Student_Course_Table is called an associative table.
The most complex part of any join is the WHERE or ON clause. The best technique is to make sure that the columns in the WHERE or ON clause have a Primary Key Foreign Key
relationship. Quite often they will have the same name. In many cases you can look at the two tables and pick the columns that have the same name in both tables.
Hint - Man
Page 38 The SQL Quick Reference Guide
Simplicity by Design
Issues: An ambiguous column name in the SQL exists. This is caused by a column that
exists in two or more of the tables involved in the join. There is a need to qualify
one of the columns in the syntax. 3809: Column ‘<column -name>’ is ambiguous.
Solutions: To eliminate this ambiguity we need to find the column that exists in two or more
of the tables. We can do this by running a ‘SHOW TABLE <table -name>’ for each
table involved in the join. This will display all the columns of each table and allow
the user to find the column that is shared between any of them. After finding that column return to the original join SQL, locate that column, and qualify it to
determine from which table you want the values.
Issues: You are getting back way more rows than expected . You are probably aliasing a
table and not consistently using the alias for that table throughout the query. Forexample,
SELECT Employee_Table .Dept_No, Dept_Name
FROM Employee_Table as E , Department_Table as D
WHERE E .Dept_No = D .Dept_No;
Solutions: The above query would be a problem because we are SELECTING
Employee_Table.Dept_No (In bold). Since we have aliased the Employee_Table
as E we needed to SELECT E.Dept_No or Teradata thinks we are trying to join
three tables. Teradata sees tables E, D, and Employee_Table. Once you alias a
table in the FROM clause that alias applies to the table everywhere.
The SQL Quick Reference Guide Page 39
The SQL Reference Guide
ANSI INNER Join Syntax (Newer Syntax)
A Join involves two or more tables in the FROM clause of a single SELECT statement. The two main differences between this ANSI join syntax and the Te radata join syntax (on
the previous page) are the words INNER JOIN separating the two tables in the FROM
clause and theON Clause instead of the WHERE clause.
SELECT [<table- name>.]<column- name>
[ [...,<table- name>.]<column- name> ] ]
FROM <table-name> [AS <table1-alias>]
[INNER] JOIN <table-name> [AS <table2-alias>]
ON [<table1-alias>.]<column-name>=[<table2-alias>.]<column-name>[ … AND [<table1-alias>.]<column- name> = [<table2- alias>.]<column-name> ]
[ [INNER] JOIN <table- name> [AS <table3-alias> ]
ON [<table3- alias>.]<column-name> = [< {table1 | table2} - alias>.]<column-name> ;
SELECT Employee_No, Last_Name, First_Name, Dept_Name,
EMP. Dept_No
FROM Employee_Table AS emp
INNER JOIN Department_Table AS dept ON emp.Dept_No = dept.Dept_No ;
SELECT STU.Student_Id, Last_Name, First_Name, Course_Name
FROM Student_Table AS STU
INNER JOIN Student_Course_Table AS STU_COUR
ON STU.Student_Id = STU_COUR.Student_Id
INNER JOIN Course_Table AS COUR ON STU_COUR.Course_Id = COUR.Course_Id ;
SELECT Mgr_No, Last_Name, First_Name
FROM Employee_Table AS EMP
INNER JOIN Department_Table AS DEPT
ON EMP.Employee_No = DEPT.Mgr_No
WHERE Budget > = 500000 ;
Notice the difference in syntax from the Original syntax. The two main changes are that INNER JOIN replaces the comma separating the tables in the FROM clause, and the ON
clause overwrites the WHERE clause. This Syntax makes it easier to avoid those
unwanted Product Joins.
Hint - Man
Page 40 The SQL Quick Reference Guide
Simplicity by Design
Issues: An ambiguous column name in the SQL exists. This is caused by a column that
exists in two or more of the tables involved in the join. There is a need to qualify
one of the columns in the syntax. 3809: Column ‘<column -name>’ is ambiguous.
Solutions: To eliminate this ambiguity we need to find the column that exists in two or moreof the tables. We can do this by running a ‘SHOW TABLE <table -name>’ for each
table involved in the join. This will display all the columns of each table and allow
the user to find the column that is shared between any of them. After finding that
column return to the original join SQL, locate that column, and qualify it to
determine from which table you want the values. Below is an example.
SELECT Employee_No, Last_Name, First_Name, Dept_Name,
Dept_No
FROM Employee_Table AS emp
INNER JOIN Department_Table AS deptON emp.Dept_No = dept.Dept_No
Error - 3809: Column Dept_No is ambiguous.
English: The problem with the above query is that the Dept_No (in bold) is in both tablesinvolved in the join. Because the system does not know which Dept_No we mean we need toqualify Dept_No. This could have worked had we stated either emp.Dept_No or Dept.Dept_No.
The SQL Quick Reference Guide Page 41
The SQL Reference Guide
Cartesian Product Join
A Cartesian Product join contains no “WHERE” clause . It is recommended to avoid this
situation because 99% percent of the time this is a bad idea.
SELECT [<table- name>.]<column- name>
[...,<table- name>.<column-name> ]
FROM <table-name> [ AS <table1-alias> ]
,<table-name> [ AS <table2-alias> ] ;
SELECT Employee_No, Last_Name, First_Name, Dept_Name, EMP.Dept_No
FROM Employee_Table AS EMP, Department_Table ;
English: The above example has no WHERE or ON clause so you will get a result set that has the
number of rows in the first table multiplied by the number of rows in the second table. The results
will be garbage.
Page 42 The SQL Quick Reference Guide
Simplicity by Design
ANSI OUTER JOIN Syntax
Outer Joins return all rows from the outer table. It will join matching rows from the joining
table just like an inner join, but put NULL values for all columns of the inner table if there
is not a match. There are LEFT, RIGHT and FULL Outer Joins.
SELECT [<table- name>.]<column- name>
[...,<table- name>.]<column- name>
FROM <table- name> [AS <table1-alias-name>]
{LEFT | RIGHT | FULL} [OUTER] JOIN
<table -name> [AS <table2- alias- name>]
ON [<table-name>.]<column-name> = [<table-name>.]<column-name>
[ WHERE <condition- test> ] ;
SELECT ORD. Customer_Number, Customer_Name ,Phone_Number FROM Customer_Table AS CUST
LEFT OUTER JOIN Order_Table AS ORD
ON CUST.Customer_Number = ORD.Customer_Number ;
In the Left Outer Join, the Customer_Table will be returning all of its rows, looking for matches in the Order_Table based on the Customer_Number defined by the ON statement.
Hint - Man
SELECT Employee_No, Last_Name, DEPT.Dept_No
FROM Employee_Table AS EMP
RIGHT OUTER JOIN Department_Table as DEPT
ON EMP.Dept_No = DEPT.Dept_No ;
In the Right Outer Join, the Department_Table will be returning all of its rows, looking for matches in the Employee_Table based on the Dept_No defined by the ON statement. For
any Department_Table rows with no matches in the Employee_Table the result set will contain NULL values for the columns from the Employee_Table.
Hint - Man
The SQL Quick Reference Guide Page 43
The SQL Reference Guide
SELECT Last_Name, First_Name, Course_Id
FROM Student_Table AS STU
FULL OUTER JOIN Student_Course_Table AS STU_COUR
ON STU.Student_Id = STU_COUR.Student_Id ;
In the Full Outer Join, both the Customer_Table and the Order_Table will be returning all of its rows, looking for matches in each table based on the Customer_Number defined by
the ON statement.
Hint - Man
Issues: An ambiguous column name in the SQL exists. This is caused by a column that
exists in two or more of the tables involved in the join. There is a need to qualifyone of the columns in the syntax. 3809: Column ‘<column -name>’ is ambiguous.
Solutions: To eliminate this ambiguity we need to find the column that exists in two or more
of the tables. We can do this by running a ‘SHOW TABLE <table -name>’ for each
table involved in the join. This will display all the columns of each table and allow
the user to find the column that is shared between any of them. After finding thatcolumn return to the original join SQL, locate that column, and qualify it to
determine from which table you want the values.
Page 44 The SQL Quick Reference Guide
Simplicity by Design
CROSS JOIN Syntax
Cross- Joins are the ANSI equivalent of a Product Join . Both a Product Join and aCartesian Product Join will compare every row from a table with every row from another
table. A Cartesian Product Join will bring back every row where a Product Join will bring
back only the rows that qualify in the WHERE or ON clause.
SELECT [<table- name>.]<column- name>
[[...,<table- name>.]<column- name> ]
FROM <table- name> [AS <table1-alias>]CROSS JOIN <table -name> [AS <table2- alias>]
[WHERE <condition- test> ] ;
SELECT Customer_Name, CUST.Customer_Number, Order_Total
FROM Customer_Table AS CUST
CROSS JOIN Order_Table AS ORDWHERE Order_Total < 10000 ;
The SQL Quick Reference Guide Page 45
The SQL Reference Guide
Date and Time Processing
Teradata has date functionality built into the database. Since dates are stored as integers in
YYYMMDD form the date can be used for calculations of other dates. Users can SELECT
the date directly from the Teradata system. Date refers to the date according to Teradata
standards (YY/MM/DD) and Current_Date refers to the date according to ANSI standards
(YYYY/MM/DD).
Teradata stores data on disk with the formula below.
((Year – 1900) * (10000)) + (Month * 100) + Day
Example:
January 12, 1977 = 770112
August 1, 2002 = 1020824
INTEGERDATE Formula
This is the default display format for most Teradata client utilities. It is in the form ofYY/MM/DD. The INTEGERDATE has nothing to do with how Teradata stores the data,
but how Teradata displays the data.
The IntegerDate is NOT how Teradata stores dates on the physical disks, but is the default
display format for client utilities. The exception is Queryman. Because Queryman uses ODBC as a standard Queryman will display the date format in ANSI format.
Hint - Man
Page 46 The SQL Quick Reference Guide
Simplicity by Design
Selecting the DATE
These functions return the present date in yy/mm/dd format .
SELECT DATE ;
Teradata Extension. Returns result by default in yy-mm-dd format.
Hint - Man
SELECT Current_Date ;
ANSI Standard. Returns result in yyyy-mm-dd format.
Hint - Man
The SQL Quick Reference Guide Page 47
The SQL Reference Guide
ADD_MONTHS Function
Teradata gives a user the ability to calculate a new date. This is a Teradata extension
function. This date can be the future with addition or past with subtraction. The calendar
has intelligence built -in for the number of days in a month as well as leap year.
SELECT ADD_MONTHS(<date-column>, <number-of-months>)FROM <table- name> ;
SELECT ADD_MONTHS(Order_Date, 3) FROM Order_Table ;
SELECT ADD_MONTHS(Sale_Date, -2) FROM Sales_Table ;
English: The above examples will take the date from the column values (inside parenthesis) and
add or subtract months.
The ADD_Months can utilize multiplication. For example, ADD_MONTHS(Date,
12*10) would bring back the date plus 10 years.
Hint - Man
Issues: 3707: Syntax error, expected something like “’||’” or ‘,’ between the word
‘<date -column>’ and the integer ‘<number-of-months>’. This error will be
returned when there is no comma between the <date -column> and the <number-of- months>.
Solutions: In the ADD_MONTHS function place a comma in between the <date -column> and
the <number-of-months>.
Page 48 The SQL Quick Reference Guide
Simplicity by Design
EXTRACT Function
EXTRACT allows users to pull out the desired segment of a date or a time. Users can
extract the YEAR, MONTH, or DAY from a date or HOUR, MINUTE, SECOND from the
time.
SELECT EXTRACT(<date/time-segment> FROM <date/time -data>)
FROM <table- name> ;
SELECT EXTRACT(Year FROM order_date) FROM Order_Table ;
SELECT EXTRACT(Month FROM order_date) FROM Order_Table ;
SELECT EXTRACT(Day FROM order_date) FROM Order_Table ;
SELECT EXTRACT(Hour FROM ’06:35:22’) ;
SELECT EXTRACT(Minute FROM ’06:35:22’) ;
SELECT EXTRACT(Second FROM ’06:35:22’) ;
The SQL Quick Reference Guide Page 49
The SQL Reference Guide
TIME and TIMESTAMP
Time and Current_Time returns the present time on the Teradata system in the
‘HH:MM:SS’ format. Current_Timestamp returns the date and time in the ‘yyyy-mm-dd
HH:MM:SS’ format.
SELECT TIME ;
A Teradata Extension Function. Returns time in hours:minutes:seconds.
Hint - Man
SELECT CURRENT_TIME ;
ANSI Standard Equivalent to TIME. Returns time in hours:minutes:seconds.
Hint - Man
Issues: 3822: Cannot resolve column ‘currenttime’. Specify table or view.
If Terada ta returns this error the underscore ( ‘_’ ) character is missing in the
syntax.
Solution: Edit the SQL by placing a ‘_’ between the end of ‘current’ and the beginning of ‘time’ with no spaces.
SELECT CURRENT_TIMESTAMP ;
ANSI Standard. Return format is ‘yyyy- mm- dd hh:mm:ss’.
Hint - Man
Issues: 3822: Cannot resolve column ‘currenttimestamp’. Specify table or view. If Teradata returns this error the underscore ( ‘_’ ) character is missing in the
syntax.
Solution: Edit the SQL by placing a ‘_’ between the end of ‘current’ and the beginning of ‘timestamp’ with no spaces.
Page 50 The SQL Quick Reference Guide
Simplicity by Design
System Calendar Columns
The following is a list of all the columns in the Calendar view for the system table
sys_calendar.calendar.
Column Name Data Type Description _
calendar_date DATE Standard Teradata date Equivalency: DATE
day_of_week BYTEINT 1-7, where 1 is Sunday
Equivalency: (DATE - DATE) MOD 7
day_of_month BYTEINT 1-31, some months have less
Equivalency: DATE MOD 7
day_of_year SMALLINT 1-366, Julian day of the year Equivalency: DATE MOD 100 or EXTRACT Day
day_of_calendar INTEGER Number of days since 01/01/1900
Equivalency: DATE - 101(date)
weekday_of_month BYTEINT The sequence of a day within a month,
first Sunday=1, second Sunday=2, etc
Equivalency: None known
week_of_month BYTEINT 0-5, sequential week number within a
month, partial week starts at 0
Equivalency: None known
week_of_year BYTEINT 0-53, sequential week number within a
year, partial week starts at 0
Equivalency: None known
week_of_calendar INTEGER Number of weeks since 01/01/1900
Equivalency: (DATE – 101(date))/7
month_of_quarter BYTEINT 1-3, each quarter has 3 months
Equivalency: CASE EXTRACT Month
month_of_year BYTEINT 1-12, up to 12 months per year
Equivalency: DATE/100 MOD 100 or EXTRACT Month month_of_calendar INTEGER Number of months since 01/01/1900 Equivalency: None needed
quarter_of_year BYTEINT 1-4, up to 4 quarters per year
Equivalency: CASE EXTRACT Month
quarter_of_calendar INTEGER Number of quarters since 01/01/1900
Equivalency: None needed year_of_calendar SMALLINT Starts at 1900 Equivalency: EXTRACT Year
Samples for use of Calendar:
SELECT * FROM sys_calendar.calendarWHERE calendar_date = 1020801 ;
SELECT quarter_of_year FROM sys_calendar.calendar
WHERE calendar_date = current_date ;
The SQL Quick Reference Guide Page 51
The SQL Reference Guide
Character String Processing
CHARACTERS Function
Counts the number of characters in a string. This function is most often used with
VARCHAR strings. If used with CHARACTER strings it will return the length of the
column because it counts the spaces. When using the Characters function on fixed length
columns it should be combined with the TRIM function.
SELECT CHARACTERS ( <column-name> )
FROM <table- name>
[ WHERE CHARACTERS ( <column-name> ) <comparison> <data- value> ] ;
SELECT Dept_Name, CHARACTERS(Dept_Name) FROM Department_Table ;
English: The above example selects Dept_Name and the number of Characters in the Dept_Name
for all rows in the Department Table. If a row had a value for Dept_Name as ‘Sales’ the answer set
would state the Dept_Name and the number of characters in the name.
Dept_Name Characters(Dept_Name) ___________ ___________________
Sales 5
SELECT CHAR(TRIM(Customer_Name)) , Customer_Name
FROM Customer_Table
WHERE Customer_Number IS NOT NULL
ORDER BY 1 ;
English: The above example will TRIM the leading and trailing spaces from the Customer_Name
first and then count the number of characters. This is done because Customer_Name is a fixed- length character data type and not a varchar.
Issues: A column may not be a character data type. Check the data type. Teradata will return an error message that looks like this: 3580: Illegal use of CHARACTERS, MCHARACTERS, or OCTET_LENGTH
functions.
Solutions: The first step is to execute the ‘SHOW TABLE <table -name>’ syntax for the table
where the column in question resides. If this column is not of a character data type
it is necessary to choose a different column to run the CHARACTERS function on.
Page 52 The SQL Quick Reference Guide
Simplicity by Design
TRIM Function
TRIM removes the extra spaces from the front, back, or on both ends of a fixed length
character string. The default for TRIM is BOTH.
SELECT TRIM( {TRAILING | LEADING | BOTH } FROM <column-name> )
FROM <table- name> ;
SELECT TRIM(TRAILING FROM Course_Name)
FROM Course_Table ;
SELECT TRIM(LEADING FROM Last_Name) , First_NameFROM Employee_Table ;
SELECT TRIM(BOTH FROM First_Name) FROM Student_Table ;
SELECT TRIM(Customer_Name) FROM Customer_Table ;
English: The above examples will either TRIM the TRAILING, LEADING, or BOTH TRAILING
and LEADING spaces from fixed-length character columns. Notice in the last example we don’t specify LEADING or TRAILING. This will default to BOTH.
The SQL Quick Reference Guide Page 53
The SQL Reference Guide
SUBSTRING and SUBSTR Functions
Both of these functions serve the purpose of returning a desired section of a character
string . A user chooses the starting position and then how many characters to pull out of the
string. The <length> specified must be a positive number , otherwise an error will occur .
SELECT SUBSTRING( <column-name> FROM <start- location> [ FOR <length> ] )
FROM <table- name> ;
SELECT SUBSTRING(Course_Name FROM 3 FOR 4) FROM Course_Table ;
SELECT SUBSTRING(‘Teradata’ FROM 2 FOR 5) ;
English: The last example will return a result of: erada
SELECT SUBSTR ( <column- name>, <start-location> [ , <length> ] )
FROM <table- name> ;
SELECT SUBSTR(Course_Name, 3 , 4) FROM Course_Table ;
SELECT SUBSTR(‘Teradata’, 2 , 5 ) ;
English: The last example will return a result of: erada
Issues: 2662: SUBSTR: string subscript out of bounds. This error will occur when the
<length> in the SQL is a negative number.
Solutions: To remove this problem, simply choose a non-negative number to place in the
<length> parameter.
Issues: String literals must have single quotes around them. This error will come back if single quotes are missing. 3822: Cannot resolve column ‘<string-literal>’. Specify table or view.
Solutions: The solution is to locate the <string-literal> and place single quotes around it.
Page 54 The SQL Quick Reference Guide
Simplicity by Design
POSITION and INDEX Functions
Teradata will return the actual place number of where the <character- string> first occurs
in the values of <column-name>. It is recommended to use the ANSI standard function,
which is POSITION in this case.
SELECT POSITION( <character-string> IN <column- name> )
FROM <table- name> ;
SELECT POSITION(‘e’ IN Course_Name) , Course_Name
FROM Course_Table ;
SELECT POSITION(‘a’ IN ‘Teradata’) ;
English: The last example would return the position of a in Teradata which would be 4.
Teradata will return a ‘4’ when running the second example query.
Hint - Man
POSITION is often used with the SUBSTRING function. Think about the SUBSTRING
syntax: SELECT SUBSTRING(Column, FROM Start Position for End Position). An
example would be SELECT SUBSTRING(‘Teradata’, 5 for 4) which returns the string
‘data’.
POSITION can be substituted inside the SUBSTRING for Start Position or End Position.
An example would be:
SELECT SUBSTRING(‘Teradata Class’, POSITION(‘ ‘ in ‘Teradata Class’) + 1, 5)
The above would take the literal ‘Teradata Class’ and find the position of the first ‘ ‘. That
number would actually be 9. Then the system would add one to it making it 10. So the
actual SUBSTRING would actually be converted to:
SELECT SUBSTRING(‘Teradata Class’, FROM 10 for 5). This returns the word ‘Class’.
The SQL Quick Reference Guide Page 55
The SQL Reference Guide
INDEX Function
Teradata will return the actual place number of where the <character- string> first occurs
in the values of <column-name>.
SELECT INDEX( <column- name> , <character- string> )
FROM <table- name> ;
SELECT INDEX(Course_Name , ‘e’) FROM Course_Table ;
SELECT INDEX(‘Teradata’ , ‘a’) ;
Equivalent Teradata Extension to the ANSI Standard POSITION function. When
choosing to use an ANSI Standard function or the Teradata Extension Equivalent, it is recommended to use the ANSI Standard Function.
Hint - Man
Issues: String literals must have single quotes around them. This error will come back if
single quotes are missing: 3822: Cannot resolve column ‘<string-literal>’. Specify table or view.
Solution: Place single quotes around the literal in question.
Page 56 The SQL Quick Reference Guide
Simplicity by Design
String and Column Concatenation
Concatenation is a very powerful feature that allows a user to combine two or more
columns in the result set to make reporting easier to read. Using concatenation with a
string literal is permissible as well.
SELECT ‘<character-data>’ || ‘<character-data>’ AS <alias>
FROM <table- name> ;
SELECT First_Name || Last_Name AS Full_Name
FROM Employee_Table
WHERE Salary <= 40000 ;
SELECT Class_Code || ‘ Class’ AS Class
FROM Student_Table ;
English: The last example above will take the value in Class_Code and concatenate the value with
the word ‘ Class’. If the value in Class_Code was ‘FR’ then the result set would be:
‘FR’ Class. In both examples above the queries are selecting only one column because the columns
are concatenated.
Flexible in terms of mixing column data with literal strings.
Hint - Man
The SQL Quick Reference Guide Page 57
The SQL Reference Guide
OLAP Functions
OLAP Functions, not only are a Teradata Extension, but they are tools built into Teradata
to give programmers the ability to analyze business trends and mine data into very granular
reports.
There are a few major points that need to be discussed that encompass all of the OLAPtools. OLAP is different than aggregates. While aggregates only return one line of
aggregate data OLAP functions can have detail data mixed with OLAP functions.
OLAP can be thought of very easily if you follow this logic. Each OLAP function will
have a built in sort key. The OLAP query actually sorts the data by the OLAP function
inside the parenthesis first. Then it calculates the OLAP requested only after the data is
sorted. NEVER use the ORDER BY statement with OLAP because all sorts are done
inside the Parenthesis of the OLAP function.
Remember, OLAP sorts the data first by the sort key or keys inside the OLAP parenthesis
and then and only then does the OLAP calculations.
Below is an example of a Cumulative SUM OLAP query.
SELECT Order_Number, Order_Total,
Order_DateCSUM(Order_Total, )
FROM Order_Table ;
English: The above query will SELECT the Order_Number and Order_Total from the
Order_Table. It will also perform an OLAP function on the Order_Total, but before the calculation
takes place Teradata will SORT the data by Order_Date. The Order_Date (in bold) is the Sort Key.
Once the data is sorted by Order_Date Teradata will do a cumulative sum on Order_Total. Read on
and you will understand.
Page 58 The SQL Quick Reference Guide
Simplicity by Design
Cumulative Sum Function (CSUM)
CSUM performs a cumulative sum on all the rows in the given <column-name>. The
CSUM column in the result set will show the running calculation through the rows that are
arranged according to the first <sort- key>.
SELECT CSUM( <column-name>, <sort -key> [ASC | DESC]
[..., <sort -key> [ASC | DESC] … )
FROM <table- name>
[GROUP BY <column- name> [...,<relative- column- number> … ] ] ;
SELECT Order_Number, Order_Total,
CSUM(Order_Total, Order_Date) FROM Order_Table ;
SELECT Dept_No, Salary, CSUM(Salary, Last_Name, Dept_No) FROM Employee_Table
GROUP BY Dept_No ;
The GROUP BY clause resets the Cumulative Sum total. The <sort -key> default for
ordering is ASCENDING. Remember that when using the GROUP BY clause, be sure to include that same column as a <sort- key>. GROUP BY will reset the Cumulative Sum calculation. In the second example the CSUM will be reset for every Department Number
in the Employee Table. Hint - Man
Issues: This message will be returned by Teradata is a user does not place a <sort-key> in
the CSUM syntax: 3706: Syntax error: expected something between the word
‘<column-name>’ and ‘)’.
Solutions: It is essential to select at least one sort-key, which is called a major sort. It wouldbe best to run a ‘SHOW TABLE <table -name>’ to get a list of the columns to
choose from. Then place the desired column in the <sort-key> part of the CSUM
syntax.
The SQL Quick Reference Guide Page 59
The SQL Reference Guide
Moving Sum Function (MSUM)
MSUM adds up the rows in the given <column-name> with a certain <width> based onthe moving window. This <width> serves as a sliding window of which rows to include in
the calculation.
SELECT MSUM( <column-name>, <width>, <sort-key> [ASC | DESC]
[..., <sort -key> [ASC | DESC] )
FROM <table- name>
[ GROUP BY <column-name> [...,<relative -column- number>] ] ;
SELECT Order_Number, Order_Total,
MSUM(Order_Total, 3, Order_Date) FROM Order_Table ;
English: The example above will first sort the data by Order_Date. Then it will perform a
moving sum on Order_Total for every 3 rows.
SELECT Product_Id, Sale_Date,
MSUM(Daily_Sales , 2 , Sale_Date, Product_Id) FROM Sales_Table
GROUP BY Product_Id ;
English: The example above will first sort the data by Product_Id. Then it will perform a
moving sum on Daily_Sales for every 2 rows.
Issues: This message will be returned by Teradata is a user does not place a <sort-key> in
the CSUM syntax: 3706: Syntax error: expected something between the word
‘<column-name>’ and ‘)’.
Solutions: It is essential to select at least one sort-key, which is called a major sort. It would
be best to run a ‘SHOW TABLE <table -name>’ to get a list of the columns to
choose from. Then place the desired column in the <sort-key> part of the CSUM
syntax.
Page 60 The SQL Quick Reference Guide
Simplicity by Design
Moving Average Function (MAVG)
Serves as a function to calculate an average based on the moving <width>.
SELECT MAVG( <column-name>, <width>, <sort -key> [ASC | DESC])
[..., <sort -key> [ASC | DESC] )
FROM <table- name>
[ GROUP BY <column-name> [...,<relative -column- number> ] ] ;
SELECT Order_Number, Order_Total,
MAVG(Order_Total, 3, Order_Date)FROM Order_Table ;
English: The example above will first sort the data by Order_Date. Then it will perform a
moving average on Order_Total for every 3 rows.
SELECT Product_Id, Sale_Date,
MAVG(Daily_Sales , 2 , Sale_Date)FROM Sales_TableGROUP BY Product_Id ;
English: The example above will first sort the data by Sale_Date. Then it will perform a
moving average on Daily_Sales for every 2 rows.
Issues: This message will be returned by Teradata is a user does not place a <sort-key> in
the CSUM syntax: 3706: Syntax error: expected something between the word‘<column-name>’ and ‘)’.
Solutions: It is essential to select at least one sort-key, which is called a major sort. It wouldbe best to run a ‘SHOW TABLE <table -name>’ to get a list of the columns to
choose from. Then place the desired column in the <sort-key> part of the CSUM
syntax.
The SQL Quick Reference Guide Page 61
The SQL Reference Guide
Moving Difference Function (MDIFF)
The MDIFF functio n behaves a little differently than other OLAP functions. In the
MDIFF result set column the difference calculation of <column-name>on Row A is
performed on the entry that is <width> rows above Row A.
SELECT MDIFF(<column-name>, <width>, <sort-key> [ASC | DESC] )
[..., <sort -key> [ASC | DESC] )FROM <table- name>
[ GROUP BY <column-name> [...,<relative -column- number>] ] ;
SELECT Order_Number, Order_Total,
MDIFF(Order_Total, 3, Order_Date) FROM Order_Table ;
English: The example above will first sort the data by Order_Date. Then it will perform a
moving difference on Order_Total for every 3 rows.
SELECT Product_Id, Sale_Date,
MDIFF(Daily_Sales , 2 , Sale_Date) FROM Sales_Table
GROUP BY Product_Id ;
English: The example above will first sort the data by Sale_Date. Then it will perform a
moving difference on Daily_Sales for every 2 rows.
Issues: This message will be returned by Teradata is a user does not place a <sort-key> in
the CSUM syntax: 3706: Syntax error: expected something between an integer
and ‘)’.
Solutions: It is essential to select at least one sort-key, which is called a major sort. It would
be best to run a ‘SHOW TABLE <table -name>’ to get a list of the columns to
choose from. Then place the desired column in the <sort-key> part of the CSUM
syntax.
Page 62 The SQL Quick Reference Guide
Simplicity by Design
QUANTILE Function
This function will divide the result set into a certain number of <partitions> based on the
<column- name>.
SELECT QUANTILE (<partitions>, <column-name> , [<sort -key> [DESC | ASC]])
FROM <table- name>
[QUALIFY QUANTILE (<column-name>) {< | > | = | <= | >=} <number-of-rows>] ;
SELECT Employee_No, Last_Name, Dept_No
, QUANTILE(4, Salary, Dept_No DESC) FROM Employee_Table ;
English: The example above will first sort the data by Dept_No in DESC order. Then it willperform a quantile function on salaries in quantiles of 4. In other words each salary will be
assigned a number from 0-3.
SELECT Product_Id, Daily_Sales,
QUANTILE(100, Daily_Sales, Sale_Date ASC) as “Percentile”
FROM Sales_TableQUALIFY “Percentile” < 5 ;
English: The example above will first sort the data by Sale_Date in ASC order. Then it will
perform a quantile function on Daily_Sales in quantiles of 100 returning all quantiles that are
assigned a number less than 5.
The QUALIFY function is the equivalent to the WHERE and HAVING clauses. It is used
when doing QUANTILE Functions.
Hint - Man
The SQL Quick Reference Guide Page 63
The SQL Reference Guide
RANK Function
Returns the rows of the involved table in a ranked order determined by the
<column-name>. The default order for RANK is DESCENDING or DESC.
SELECT RANK( <column-name> [DESC | ASC] )FROM <table- name>
[GROUP BY <column- name> [...,<relative- column- number> ] ] [ { ASC | DESC } ]
[QUALIFY RANK(<column-name>) {< | <=} <number-of-rows> [DESC | ASC] ] ;
SELECT Employee_No, Last_Name, Dept_No
, RANK(Salary ASC) FROM Employee_Table
GROUP BY Dept_No ;
English: The above example will RANK the salaries in asc order. The query will return the
Employee_Id, Last_Name, Dept_No, and Salary Rank in ascending order by Salary Rank.
SELECT Product_Id, Daily_Sales,
RANK(Daily_Sales DESC) as Ranking
FROM Sales_Table
QUALIFY Ranking < 5 ;
English: The above example will RANK the Daily_Sales in DESC order. The query will return the
Product_Id, Daily_Sales and Rank of Daily_Sales ordered by RANK of Daily_Sales if the rank is
less than 5. The query is actually returning the top four selling products.
Page 64 The SQL Quick Reference Guide
Simplicity by Design
SAMPLE Function and SAMPLEID
SAMPLE returns a random sample of the result set of the given SQL statement . The
sample size is determined by either a number of rows, or percentage of rows. SAMPLEID
shows the user from which sample a certain row is in.
SELECT { <column- name> | * }
[...,<column-name> ]
[,SAMPLEID ]
FROM <table- name>
SAMPLE { <number-of-rows> | <percentage> }
[...,<number-of-rows> | <percentage> ] ;
SELECT Customer_Name, Phone_Number
FROM Customer_TableSAMPLE 3 ;
English: A Sample of 3 rows.
SELECT Course_Name
FROM Course_Table
SAMPLE .25 ;
English: A Sample of 25% rows.
SELECT Sale_Date, Daily_Sales, SAMPLEID
FROM Sales_Table
SAMPLE 4 , 4 ;
English: Two samples of 4 rows.
When requesting a concrete number of rows to be returned in a sample, the actual number of rows in the table should be taken into account. Suppose a user decides to take two
samples from a 1000 row table. One sample is for 800 rows, and the second sample being 300 rows. The second sample will only have 200 rows returned because in SAMPLE there
are no repeats in the same SQL statement!! Hint - Man
Issues: More than 100% of result set wanted for Sample or multiple samples. This issue
appears only when dealing with percentages. 5473: SAMPLE Clause has invalid set of arguments.
Solutions: The key is to adjust the sampling percentages to a proper total. For example if you
are currently attempting to get three samples of .50 each, adjust the percentages to
.33. This will take care of the error.
The SQL Quick Reference Guide Page 65
The SQL Reference Guide
RANDOM Function
Returns a random number between the <low-literal-value> and the
<high-literal-value> .
SELECT RANDOM( <low- literal-value>, <high- literal-value> ) ;
SELECT RANDOM(10, 150) ;
English: SELECT a random number between 10 and 150.
SELECT * FROM Employee_Table
WHERE RANDOM(1,100) = 2 ;
English: Randomly Select 2% of the rows from the table.
Page 66 The SQL Quick Reference Guide
Simplicity by Design
Set Operator Commands
The SET Operators are UNION, INTERSECT, EXCEPT/MINUS. EXCEPT and MINUS
are the same commands. The SET operators will run two queries at once and combine the
result sets together.
Here is an example:
SELECT Employee_No from Employee_Table
INTERSECT
SELECT Mgr_No from Department_Table;
English: The above is looking for managers because both queries will run and then only the
columns that match from the two SETS will be returned.
Here are a few general guidelines for using set operators: 1. Each SELECT statement involved must contain the same number of columns as the others.
All corresponding columns must be of the same domain, which means that their da ta types
and ranges of values must match.
2. The First Select statement formats the results and defines aliases and titles for column
output.
3. The Last SELECT contains the ORDER BY clause for the entire SQL statement. 4. When using multiple set operators in one statement the order of operations is as follows:
INTERSECT, UNION, EXCEPT/MINUS. This order holds true unless parentheses are
used to manipulate the order.
For a more detailed list of guidelines on using Set Operators, refer to “Teradata SQL:
Unleash the Power”, Chapter 11.
Hint - Man
The SQL Quick Reference Guide Page 67
The SQL Reference Guide
INTERSECT
The INTERSECT operator matches like values from two sets of rows similar to an
INNER JOIN. No duplicate rows will be returned in the result set unless the ALL
keyword is used to include duplicate rows (when they exist).
SELECT <column- name>
[,<column-name> … ]
FROM <table -name>
INTERSECT [ ALL ]
SELECT <column- name>
[,<column-name> … ]
FROM <table -name>
[ORDER BY <column-name>] ;
SELECT Customer_Number AS Customers_with_Orders
FROM Customer_Table
INTERSECT
SELECT Customer_Number FROM Order_Table
ORDER BY 1 DESC;
English: The above query returns all Customer_Numbers who have Orders in the Order_Table
eliminating any duplicates.
SELECT Student_Id
FROM Student_Table
INTERSECT ALL
SELECT Student_Id (TITLE ‘Students_With_Courses’)
FROM Student_Course_Table;
English: The above query returns all Student_Ids who have enrolled in courses without eliminating
any duplicates.
INTERSECT ALL is not a valid function for Teradata Versions earlier than Version 2
Release 4.
Hint - Man
Issues: The columns in the two select statements do not match up in terms of data types. 3654: Corresponding select-list expressions are incompatible.
Solutions: The best way to find matching data types is to run ‘SHOW TABLE <table -name>’
for both tables you would like to intersect. Search through the DDL and locate the
columns that match up properly. These are the columns you may use in the
intersect.
Page 68 The SQL Quick Reference Guide
Simplicity by Design
UNION
UNION is a function that stacks one result set on top of the second result respectively. No duplicate rows will be returned in the answer set unless the ALL keyword is used to
include any existing duplicate rows.
SELECT <column- name>
[,<column-name> … ]
FROM <table -name>
UNION [ ALL ]
SELECT <column- name>
[,<column-name> … ]
FROM <table -name>
[ORDER BY <column-name>];
SELECT Student_Id (TITLE ‘All Students – No Duplicates’)
FROM Student_Table
UNION SELECT Student_Id
FROM Student_Course_Table;
English: The above query returns all Student_Ids from both tables eliminating any duplicates.
SELECT Student_Id (TITLE ‘All Students – No Duplicates’) FROM Student_Table
UNION ALLSELECT Student_Id
FROM Student_Course_Table;
English: The above query returns all Student_Ids from both tables and does not eliminate any
duplicates.
Issues: The columns in the two select statements do not match up in terms of data types. 3654: Corresponding select-list expressions are incompatible.
Solutions: The best way to find matching data types is to run ‘SHOW TABLE <table -name>’
for both tables you would like to intersect. Search through the DDL and locate the
columns that match up properly. These are the columns you may use in the union.
The SQL Quick Reference Guide Page 69
The SQL Reference Guide
EXCEPT
EXCEPT serves the purpose of removing rows from the first result set that have a match
in the second result set. No duplicate rows will be returned in the answer set unless the
ALL keyword is used to include any existing duplicate rows.
SELECT <column- name>
[,<column-name> … ]
FROM <table -name>
EXCEPT [ALL]SELECT <column- name>
[,<column-name> … ]
FROM <table -name>
[ORDER BY <column-name>] ;
SELECT Student_Id (TITLE 'Students w/o Courses - No Dups')
FROM Student_Table
EXCEPT
SELECT Student_Id
FROM Student_Course_Table;
English: The above query returns all Student_Ids from the top query (Student_Table) only. It will then eliminate any Student_Id from the top spool if they are in the Student_Course_Table. No data
in the Student_Course_Table can ever be in the answer set. All duplicates in the top query only are
eliminated.
SEL Student_Id (TITLE 'Students w/o Courses – Dups incl.')
FROM Student_Table
EXCEPT ALL
SEL Student_Id
FROM Student_Course_Table;
English: The above query returns all Student_Ids from the top query (Student_Table) only. It will
then eliminate any Student_Id from the top spool if they are in the Student_Course_Table. No data
in the Student_Course_Table can ever be in the answer set. All duplicates in the top query are NOT
eliminated.
Issues: The columns in the two select statements do not match up in terms of data types. 3654: Corresponding select-list expressions are incompatible.
Solutions: The best way to find matching data types is to run ‘SHOW TABLE <table -name>’ for both tables you would like to intersect. Search through the DDL and locate the
columns that match up properly. These are the columns you may use in the except.
Page 70 The SQL Quick Reference Guide
Simplicity by Design
MINUS
The MINUS operator is the ANSI equivalent of its Teradata counterpart EXCEPT . It returns rows from the first result set that do not have matches in the second result set. No
duplicate rows will be returned in the answer set unless the ALL keyword is used to
include any existing duplicate rows.
SELECT <column- name>
[,<column-name> … ]
FROM <table -name>
MINUS [ ALL ]
SELECT <column- name>
[,<column-name> … ]
FROM <table -name>
[ORDER BY <column-name>];
SELECT Student_Id (TITLE 'Students w/o Courses - No Dups')
FROM Student_Table
MINUS
SELECT Student_Id
FROM Student_Course_Table;
English: The above query returns all Student_Ids from the top query (Student_Table) only. It will
then eliminate any Student_Id from the top spool if they are in the Student_Course_Table. No datain the Student_Course_Table can ever be in the answer set. All duplicates in the top query only are
eliminated.
SELECT Student_Id (TITLE 'Students w/o Courses - Dups incl.') FROM Student_Table
MINUS ALLSELECT Student_Id
FROM Student_Course_Table
ORDER BY 1 DESC;
English: The above query returns all Student_Ids from the top query (Student_Table) only. It willthen eliminate any Student_Id from the top spool if they are in the Student_Course_Table. No data
in the Student_Course_Table can ever be in the answer set. All duplicates in the top query are NOT
eliminated.
Issues: The columns in the two select statements do not match up in terms of data types.
3654: Corresponding select-list expressions are incompatible.
Solutions: The best way to find matching data types is to run ‘SHOW TABLE <table -name>’
for both tables you would like to intersect. Search through the DDL and locate the
columns that match up properly. These are the columns you may use in the minus.
The SQL Quick Reference Guide Page 71
The SQL Reference Guide
Data Manipulation Language Commands
INSERT
The INSERT syntax gives a user the ability to place more rows of data into a certain
table . The command must take in account for every column in the table whether it is with
actual data or nulls.
INSERT [ INTO ] <table- name> VALUES
( <literal-data-value1> [ , <literal-data-value2> [, …] ) ;
INSERT INTO Student_Table VALUES
( 999333, 'Jones', 'Jerry', 'SR', 3.00 );
INSERT INTO Student_Table VALUES ( 999444, 'Smith', 'Jean', , NULL);
INSERT INTO Student_table (First_Name, Last_Name, Student_Id) .
VALUES ( 'Russel', 'Paul', 999111);
INSERT INTO Student_table
(First_Name='Russel', Last_Name='Paul', Student_Id=999111);
English: The above examples use multiple ways to INSERT data into the Student_Table.
When using the INSERT command, inserting column values in the proper order is essential. The order of values inserted must correspond to the order that the columns are
defined in the table unless you name the columns. Take notice of the two ways in which NULL values are inserted (NULL or ,). Since the column names are specified in the last two syntax examples in the column order is arbitrary. Hint - Man
Issues: Too many values are being inserted in the target table. There are too many
arguments in the Insert statement for the table to handle.3706: Syntax error, Column name list shorter than value list.
Solutions: Running a ‘SHOW TABLE <table -name>’ or a ‘HELP TABLE <table -name>’ is
the best way to find out how many columns there are, and what data types they are.One you know this information you can edit the SQL to adhere to the structure of the table.
Page 72 The SQL Quick Reference Guide
Simplicity by Design
Inserting NULL and Default Values
These three statements are ways to insert a row of nulls into the Student table. The third
statement works in Teradata Version 2 Release 3 and l ater. When using this statement, any
default values defined for columns will be inserted in place of nulls.
INSERT INTO Student_Table VALUES (, , , , , ) ;
INSERT INTO Student_Table VALUES
(NULL, NULL, NULL, NULL, NULL, NULL) ;
INSERT INTO Student_Table DEFAULT VALUES ;
Issues: The values that are being inserted do not match up properly with the columns in thetarget table. 3706: Syntax error, Column name list shorter than value list.
Solutions: Running a ‘SHOW TABLE <table -name>’ or a ‘HELP TABLE <table -name>’ isthe best way to find out how many columns there are, and what data types they are.
One you know this information you can edit the SQL to adhere to the structure ofthe table.
The SQL Quick Reference Guide Page 73
The SQL Reference Guide
INSERT / SELECT
The INSERT/SELECT statement serves as a very fast way to move data from one table to
another. It is very flexible in addition to being great for performance.
INSERT [ INTO ] <table1- name>
SELECT <column1- name> [ ,<column2- name> [ , …] ]
FROM <table2- name> ;
INSERT INTO New_Employee_Table
SELECT * FROM Employee_Table;
INSERT INTO New_Employee_Table
SELECT ( Employee_No, Last_name, First_name, , ) FROM Employee_Table;
INSERT INTO New_Employee_Table (Dept_No, First_name, Last_name, Employee_No) SELECT Dept_No, First_name, Last_name, Employee_No
FROM Employee_Table;
Issues: 3813: The positional assignment list has too many values. This error comes up
when there are too many columns in the SELECT table for the target table to
handle.
Solutions: There are two solutions for this issue. The first solution would be to look in the
SELECT table DDL, with a ‘SHOW TABLE <table -name>’ then adjust theSELECT statement to choose only the columns that match with the target table.
The second solution would be to alter the structure of the target table, but this is
normally not recommended.
INSERT INTO Employee_Table_USA
SELECT * FROM Employee_Table_West UNION
SELECT * FROM Employee_Table_East;
The above query does an INSERT SELECT into an empty table. Because the target table was empty there is no need to take before image pictures with the Transient Journal.
Because we have used the UNION command to make both SELECTS part of the same transaction we can INSERT the rows from both tables much faster. This is a clever trick.
Hint - Man
Page 74 The SQL Quick Reference Guide
Simplicity by Design
UPDATE
This syntax serves the purpose of changing data values of one or more existing rows that meet the criteria specified in SQL request.
UPDATE <table -name> [ AS <alias-name> ]
[ FROM <table2-name> [AS <alias2-name> ] ]
SET <column- name> = <expression-or- data- value>
[ , <column-name> = <expression-or-data-value> … ]
[ WHERE <condition- test> ]
[ AND <condition- test> … ] [ OR <condition- test> … ]
[ALL] ;
UPDATE Student_table
SETGrade_Pt = Grade_Pt + 1.0
WHERE Last_Name = 'Jones' AND First_Name = 'Jerry'
AND Class_Code = 'JR';
UPDATE Student_table
SETGrade_Pt = 2.50,Class_Code = 'JR'
WHERE Student_Id = 999333;
UPDATE Employee_Table
SETSalary = Salary * 1.1
All;
English: The above query examples are updating. The top two examples are updating only one
row, but the last example gives everyone in the Employee_Table a 10% raise.
The ALL command is completely optional. Teradata would have updated every row in
the table for the last example.
Hint - Man
The SQL Quick Reference Guide Page 75
The SQL Reference Guide
UPDATE with a Subquery
Using a subquery is a very advanced means of updating rows.
UPDATE<table -name> [ AS <alias- name> ]
[ FROM <table -name2> [AS <alias-name2> ] ]
SET <column- name> = <expression-or- data- value>
[ , <column-name> = <expression-or-data-value> … ]
WHERE<column- name> [ , <column- name2> [ , …]]
IN ( SELECT <column- name> [,<column- name2> [ , …]]
FROM <table- name> [ AS <alias-name> ]
[ WHERE <condition- test> … ] )
[ ALL ] ;
UPDATE Employee_Table
SET Salary = Salary * 1.10
WHERE Dept_No IN (SELECT Dept_NoFROM Department_Table
WHERE Budget > 500000) ;
UPDATE with a Join
When a programmer understands his or her data well enough, it could be very beneficial to
use this syntax.
UPDATE<table -name1> [ AS <alias- name1> ]
[ FROM <table -name2> [ AS <alias-name2> ] ]
SET <column- name> = <expression-or- data- value>
WHERE[<table -name1>.]<column-name> = [<table -name1>.]<column-name>
[ AND <condition- test> ] [ OR <condition- test> ]
[ ALL ];
UPDATE Employee_Table
FROM Department_Table dept SET Sala ry = Salary * 1.10
WHERE Employee_Table.Dept_No = dept.Dept_No
AND Budget > 500000 ;
Page 76 The SQL Quick Reference Guide
Simplicity by Design
DELETE
Unlike most databases Teradata has the ability to quickly delete rows from a given table. It is recommended to delete all rows from a table rather than drop it , then recreate that
table.
DELETE [ FROM ] <table- name> [ AS <alias-name> ]
[ WHERE condition ] [ ALL ];
DELETE FROM Student_Table ALL ;
DELETE FROM Student_Table WHERE Grade_Pt < 1.0 ;
Issues: The table having rows deleted does not exist.
3807: Table/view/trigger ‘Student’ does not exist.
Solutions: Check the spelling of the <table -name>, use the SELECT DATABASE syntax to
confirm you are in the correct database or HELP DATABASE <database-name> to
see all objects in the database.
The SQL Quick Reference Guide Page 77
The SQL Reference Guide
Delete with a Join
On occasion, you may wish to delete rows from a table based on values in another table .
The Delete command can be used with a join or subquery operation to accomplish this task.
DELETE <table - name1>
[ FROM <table- name2> [ AS <alias- name> ] ]
WHERE <table -name1>.<column- name>=<table -name1>.<column-name>
[ AND <condition> ]
[ OR <condition> ]
[ ALL ];
DELETE Employee_Table
FROM Department_Table AS dept
WHERE Employee_Table.Dept_No = dept.Dept_No
AND Budget < 400000 ;
DELETE Employee_Table
WHERE Employee_Table.Dept_No = Department_Table.Dept_No
AND Budget < 400000 ;
Keep in mind when omitting the optional FROM clause an alias cannot be used.
Hint - Man
Delete with a Subquery
DELETE <table - name> [ AS <alias- name> ]
WHERE<column- name> [ , <column- name2> [, …] ]
IN ( SELECT <column- name> [,<column- name2> [, …]
FROM <table- name> [ AS <alias-name> ]
[ WHERE condition … ] )
[ ALL ];
DELETE FROM Employee_Table
WHERE Dept_No IN (SELECT Dept_No
FROM Department_Table
WHERE Budget < 500000) ;
Page 78 The SQL Quick Reference Guide
Simplicity by Design
UPSERT
UPSERT combines UPDATE and INSERT into a single command. If the row already
exists, then the Update will occur. If the row does not exist, then the row will be inserted.
In Teradata versions prior to V2R4.1 TPUMP and MULTILOAD could only use this
syntax. In Teradata V2R4.1 and later, this functionality is present in Queryman and BTEQ
as well.
UPDATE <table -name>
SET <column- name> = <expression> [ ,<column-name> = <expression> … ]
WHERE [<table -name1>.]<column-name> = [<table - name1>.]<column- name>
[ AND <condition- test> ] [ OR <condition- test> ]
ELSE INSERT INTO <table-name> VALUES ( <value -list> ) ;
UPDATE Student_Table
SET Grade_Pt = 4.0
WHERE Last_Name = 'Jones'
AND First_Name = 'Jasmine' AND Class_Code = 'JR' AND Student_Id = 555555
ELSE INSERT INTO Student_Table VALUES( 555555,'Jones','Jasmine','JR',4.0 ) ;
English: In the above example we are attempting to UPDATE the Student_Table. If the UPDATE
works the query is done, however, if Teradata does not find the row in the table it will INSERT the
record into the table.
For a more information on using UPSERT, refer to “Teradata SQL: Unleash the Power”,
book by Larkins and Coffing, Chapter 12.
Hint - Man
Issues: Missing the ‘ELSE’ before the INSERT statement. 3706: Syntax error: expected something between an integer and the ‘INSERT’
keyword.
Solutions: In the SQL request, locate the word ‘INSERT’ and place ‘ELSE’ before it.
The SQL Quick Reference Guide Page 79
The SQL Reference Guide
UPSERT for TPUMP and MULTILOAD
This UPSERT syntax is to be used in TPUMP and MULTILOAD only . Teradata will not
recognize the command without the Label and DO INSERT code.
.DML LABEL <label-name>
DO INSERT FOR MISSING UPDATE ROWS;
UPDATE<table -name>
SET <column- name> = <expression> [ ,<column-name> = <expression> … ]
WHERE [<table -name1>.]<column-name> = [<table - name1>.]<column- name>
[ AND <condition- test> ] [ OR <condition- test> ] ;
INSERT INTO <table- name> VALUES ( <value- list> ) ;
.DML LABEL UPSERT1
DO INSERT FOR MISSING UPDATE ROWS;
UPDATE Student_Table
SET Grade_Pt = 4.0
WHERE Last_Name = 'Jones' AND First_Name = 'Jasmine' AND Class_Code = 'JR'
AND Student_Id = 555555
INSERT INTO Student_Table VALUES
( 555555,'Jones','Jasmine','JR',4.0 ) ;
:
In the above example you see the statement: Do INSERT for Missing UPDATE rows.
This is a required statement and not just a comment. Often users don’t think they need
this in Multiload and they do. For more information see the “Teradata Utilities – Breaking
Hint - Man the Barriers” by Coffing, Jones, Larkins, Volters and Wilmes.
Page 80 The SQL Quick Reference Guide
Simplicity by Design
DATA INTERROGATION
NULLIFZERO
This Teradata extension returns a NULL value when the column value is equal to zero .
This function is helpful with eliminating any division by zeros.
SELECT NULLIFZERO( <column-name> )
,<Aggregate> ( NULLIFZERO(<column-name> ) )
FROM <table -name>
GROUP BY 1;
SELECT Class_code
, NULLIFZERO(Grade_pt) AS "Class AVG"
FROM Student_table;
SELECT Last_Name
,First_Name
,Class_Code
,Grade_Pt , Grade_pt / ( NULLIFZERO(Grade_Pt) * 2 ) AS "Calc"
FROM Student_TableORDER BY 3,4;
The second example illustrates a good use of the NULLIFZERO Function by eliminating
division by zero errors.
Hint - Man
Issues: The user is attempting to use this function on a non-numeric column.
2621: Bad character in format or data of Student_table.Class_code.
Solutions: The only answer to this problem would be to choose another column that is of
numeric data type. Executing a ‘SHOW TABLE <table -name>’ or a ‘HELP
TABLE <table -name>’ command will display the information you need to make an
educated decision.
The SQL Quick Reference Guide Page 81
The SQL Reference Guide
NULLIF
An ANSI Statement that compares two values and returns a NULL when the values are
equal .
SELECT NULLIF(<column-name>, <value> )
[,<Aggregate>(NULLIF(<column-name>, <value> ) )]
FROM <table- name>
[GROUP BY 1] ;
SELECT Class_Code
, AVG(NULLIF(Grade_pt, 0) ) AS CLASSAVG
FROM Student_table
GROUP BY Class_Code;
English: In the above example Grade_Pt is compared to 0. If Grade_Pt equals 0 a NULL value is
returned. Since aggregates like AVG ignore nulls the AVG won’t be pulled way down for a 0.
Issues: Attempting to use this function on a non-numeric column.
2621: Bad character in format or data of Student_table.Class_code.
Solutions: The only answer to this problem would be to choose another column that is of
numeric data type. Executing a ‘SHOW TABLE <table -name>’ or a ‘HELP
TABLE <table -name>’ command will display the information you need to make an
educated decision.
Page 82 The SQL Quick Reference Guide
Simplicity by Design
ZEROIFNULL
It returns a zero when the data value in a column contains a NULL . This function can be
used with mathematical formulas and functions in order to eliminate the use of NULL
values in calculations.
SELECT ZEROIFNULL(<column-name> )
[,<Aggregate> ( ZEROIFNULL(<column-name> ) )]
FROM <table- name>
[GROUP BY 1] ;
SELECT Last_Name
,First_Name,Class_code
, ZEROIFNULL(Grade_pt) AS GPA
FROM Student_table
ORDER BY 4 DESC;
SELECT Class_Code
, AVG(ZEROIFNULL(Grade_pt)) CLASSAVG
FROM Student_table
GROUP BY 1
ORDER BY 2;
This function can be used with mathematical formulas and functions in order to eliminate
the use of NULL values in calculations.
Hint - Man
Issues: Attempting to use this function on a non-numeric column.
2621: Bad character in format or data of Student_table.Class_code.
Solutions: The only answer to this problem would be to choose another column that is of
numeric data type. Executing a ‘SHOW TABLE <table -name>’ or a ‘HELP
TABLE <table -name>’ command will display the information you need to make an
educated decision.
The SQL Quick Reference Guide Page 83
The SQL Reference Guide
COALESCE
This ANSI statement returns the first Non-NULL value in a list that can include columns, literals, or both. If all columns in the list are NULL Coalesce returns a NULL.
SELECT COALESCE (<column-list> [,<literal> ] )
[,<Aggregate>( COALESCE(<column-list>[,<literal>] ) )]
FROM <table- name>
[GROUP BY 1];
SELECT Last_name
,First_Name
, COALESCE(Class_code, 'Missing Classification') Class
FROM Student_Table
ORDER BY 1;
SELECT Last_name
,First_Name
, COALESCE(Class_code, Grade_Pt,'Missing Class and
Grade') AS Class
FROM Student_Table
ORDER BY 1;
English: The above COALESCE statements will SELECT Class_code unless Class_code is NULL. If Class_code is NULL then another column or literal will be chosen.
One technique that will guarantee no NULL is returned is to place a literal value at the
end of the list. For example (watch for the bold below):
‘No Phone’ Hint - Man SELECT COALESCE(HomePhone, WorkPhone, );
Issues: 3810: Column ‘<string-literal>’ does not exist. This error is caused by not properly identifying a character string in the
COLAESCE function.
Solutions: The solution is to find the character string that is suspected of the error and place
sin gle quotes around that string.
Page 84 The SQL Quick Reference Guide
Simplicity by Design
CASE
The CASE statement is a flexible SQL function that provides for multiple levels of testingdata . There are a few different styles, which give the user the choice of how much data
interrogation can be performed on the rows.
Basic Syntax
This is the simplest syntax of all the styles of case statements. Only one column can be
tested is this format.
CASE <column- name>
WHEN <value1> THEN <true -result1>
WHEN <value2> THEN <true -result2>
…
[ ELSE <false-result> ]
END ;
SELECT First_Name , Last_Name
, CASE Class_CodeWHEN 'FR' THEN 'Freshman'
WHEN 'SO' THEN 'Sophomore' WHEN 'JR' THEN 'Junior' WHEN 'SR' THEN 'Senior'
ELSE 'Not Classified' END "Classification"
FROM Student_Table ;
In a case statement, the ELSE clause is optional. If you choose not to use the else, any
arguments that do not match any of the criteria will return a NULL value to the result set.
Hint - Man
The SQL Quick Reference Guide Page 85
The SQL Reference Guide
Advanced Syntax
This advanced syntax returns results based on various conditions , which can test more
than one column if desired.
CASE
WHEN <condition- test1> THEN <true- result1>WHEN <condition- test2> THEN <true- result2>
…
[ ELSE <false-result> ]
END ;
SELECT First_Name || ' ' || Last_Name
, CASE
WHEN Class_Code = 'FR' THEN 'Freshman' WHEN Class_Code = 'SO' THEN 'Sophomore' WHEN Class_Code = 'JR' THEN 'Junior' WHEN Class_Code = 'SR' THEN 'Senior' ELSE 'Not Classified' END "Classification"
FROM Student_Table;
English: The above query example will concatenate the First_Name and Last_Name together with
a space in between. Then the Class_Code will be inte rrogated and the proper literal will be placed
in the report. The alias is called “Classification”.
SELECT First_Name || ' ' || Last_Name
,Salary
, CASE
WHEN Salary > 50000 THEN 'Top of Pay Scale' WHEN Salary BETWEEN 40000 AND 50000
THEN 'Reaching Top Pay' WHEN Salary BETWEEN 35000 AND 39999
THEN ‘Low End' WHEN Salary IS NULL THEN 'Missing Salary' ELSE 'Entry Level' END "Clas sification" FROM Employee_Table
ORDER BY 2;
Both syntaxes allow for an alternative result when all values/conditions evaluated are
false. Knowledge of your data and business rules is critical to properly utilize the CASE statement.
Hint - Man
Page 86 The SQL Quick Reference Guide
Simplicity by Design
Horizontal Reporting
The CASE Statement below will display Average salaries for Departments 100-400 in a
manner of one row, rather than four separate rows. This style of Case Statement is called
Horizontal Reporting .
SELECT AVG(CASE Dept_No
WHEN 100 THEN SalaryELSE NULL END) AS "Dept 100 AVG SAL"
,AVG(CASE Dept_NoWHEN 200 THEN SalaryELSE NULL END) AS "Dept 200 AVG SAL"
,AVG(CASE Dept_NoWHEN 300 THEN Salary
ELSE NULL END) AS "Dept 300 AVG SAL"
,AVG(CASE Dept_NoWHEN 400 THEN SalaryELSE NULL END) AS "Dept 400 AVG SAL"
FROM Employee_Table
WHERE Dept_No IS NOT NULL;
English: The above query is brilliant, but you must first understand that aggregates ignore NULLS.
Normally a query such as this will be performed showing the Dept_No and AVG(Salary) and
grouping by Dept_No. The result set would produce a one line total for each department. If therewere four departments then there would be four rows in the answer set. The above query delivers a
one -line answer set. With four case statements and four aliases a row will either qualify in one of the four case state ments and be part of the average or is made NULL and therefore ignored by the
AVG. The output would look something like this:
Dept 100 AVG SAL Dept 200 AVG SAL Dept 300 AVG SAL Dept 400 AVG SAL
________________ _________________ _________________ _________________ 50000.00 60000.00 55000.00 80000.50
The SQL Quick Reference Guide Page 87
The SQL Reference Guide
Nested CASE
Each nested CASE statement is enclosed in parentheses and has a corresponding END
statement . This allows for further testing of a value that passes the first level of the nested
case statement.
SELECT TRIM(Last_name) || ', ' || First_Name
,CASE Class_code
WHEN 'FR' THEN 'Freshman ' || (CASE WHEN Grade_pt < 2
THEN 'Unacceptable' WHEN Grade_pt < 3.5
THEN 'Satisfactory' ELSE 'Honor Roll' END)
WHEN 'SO'
THEN 'Sophomore ' || (CASE WHEN Grade_pt < 2
THEN 'Unacceptable' WHEN Grade_pt < 3.5
THEN 'Satisfactory' ELSE 'Honor Roll' END)
WHEN 'JR' THEN 'Junior ' || (CASE WHEN Grade_pt < 2
THEN 'Failing' WHEN Grade_pt < 3.5
THEN 'Satisfactory' ELSE 'Honor Roll' END)
ELSE 'Senior ' || (CASE WHEN Grade_pt < 2
THEN 'Unacceptable' WHEN Grade_pt < 3.5
THEN 'Satisfactory' ELSE 'Honor Roll' END)
END AS "Grade Status"
FROM Student_Table
ORDER BY Class_Code, Last_Name;
For more details refer to “Teradata SQL: Unleash the Power”, Chapter 13.
Hint - Man
Issues: Possibly missing parentheses in the SQL.
3707: Syntax error, expected something like ‘)’ between the ‘END’ keyword and
the ‘END’ keyword .
Solutions: The best means of solving this issue is to start with the first ‘(‘ and find the ‘)’ that
is paired with it. Then move to the second ‘(‘ and find its partner ‘)’, and continue
this process until all the ‘(‘ have a paired up ‘)’. If there is a ‘(‘ with no pair place a
‘)’ at the end of the SQL before the semi-colon.
Page 88 The SQL Quick Reference Guide
Simplicity by Design
Views
In all the classes that I’ve taught, I always get the question of why views are a big part of
Teradata. There are many ways that can be answered. Views are used as a means to
customize the way users can access a certain table by deriving columns, restricting
columns, or joining multiple tables together to make reporting an easier task. Most
Enterprises use views as a means of protecting the raw data from any accidental corruption
by users.
Create View Syntax
Views allow a user to manipulate the columns returned with the reporting format desired,
which is very useful. The WITH CHECK OPTION statement allows a user to only insert or modify rows that are compliant with the WHERE Clause in the CREATE VIEW
syntax.
CREATE VIEW <view- name> [( <alias- name>, <alias-name>, … ) ] AS SELECT
<column- name> [AS <alias- name> ]
[…, <column-name> [AS <alias- name> ] ]
FROM <table- name>
[ WHERE <conditional-tests> ]
[ WITH CHECK OPTION ] ;
CREATE VIEW Employee_V AS
SELECT Employee_No, Last_Name
, First_Name, Dept_No
FROM Employee_Table ;
CREATE VIEW Course_Credits_V (CourseName, Hours) AS
SELECT Course_Name, Credits
FROM Course_Table ;
CREATE VIEW Roster_400_V AS
SELECT STU.Student_Id, Last_Name, First_NameFROM Student_Table STU
INNER JOIN Student_Course_Table STU_COURON STU.Student_Id = STU_COUR.Student_Id
WHERE Course_Id = 400
WITH CHECK OPTION ;
The SQL Quick Reference Guide Page 89
The SQL Reference Guide
The “Create View” Syntax can be replaced by “CV”, which is a Teradata specific feature.
In the fourth example, a user may only insert or modify rows that are compliant to
“Course_Id = 400” due to the WITH CHECK OPTION statement.
Hint - Man
Issues: Table does not exist from which the view is pulling from. A misspelling of some sort could cause this error, or the table you are looking for could not be in that database.
3807: Table/view/trigger ‘<table-name>’ does not exist.
Solutions: The first thing to do is search for the table name and ensure it is properly spelled. The next step is to run a ‘HELP DATABASE <database-name>’ command to locate the table desired
to have a view on. Then put the proper table name in the view create text.
DROP Views
The DROP View syntax completelyremoves a view from the Data Dictionary.
DROP VIEW [<database- name<.]<view- name> ;
DROP VIEW Employee_V ;
DROP VIEW Course_Credits_V ;
Page 90 The SQL Quick Reference Guide
Simplicity by Design
REPLACE Views
Use the word REPLACE to change a view.
REPLACE VIEW [<database- name>.]<view- name>
AS SELECT <column- name>
[...,<column-name> ]
FROM <table -name>
[ WHERE <conditional-tests> ]
[ WITH CHECK OPTION ] ;
REPLACE VIEW Sales_Low_V AS
SELECT * FROM Sales_Table
WHERE Daily_Sales <= 40000 ;
REPLACE VIEW Roster_400_V AS
SELECT Last_Name, First_Name
FROM Student_Table STU
INNER JOIN Student_Course_Table STU_COURON STU.Student_Id = STU_COUR.Student_Id
WHERE Course_Id = 400
WITH CHECK OPTION ;
A clever technique to replacing a view is to run the SHOW VIEW <ViewName>
command. Then when the answer set shows the current view structure you can copy it
and then change the word CREATE to REPLACE and make your changes. This is safer
Hint - Man and more efficient then trying to retype the entire view in again.
The SQL Quick Reference Guide Page 91
The SQL Reference Guide
LOCKING FOR ACCESS
Using an Access Lock is like a “Dirty Read” . Access Locks provide compatibility with
all other lock types except for an Exclusive Lock.
REPLACE } VIEW [<database- name>.]<view-name> { CREATE | AS LOCKING <table-name> FOR ACCESS
SELECT <column- name>
[...,<column-name> ]
FROM <table -name>
[ WHERE <conditional-tests> ]
[ WITH CHECK OPTION ] ;
CREATE VIEW Employee_V AS
LOCKING Employee_Table FOR ACCESS
SELECT Employee_No, Last_Name
, First_Name, Dept_No
FROM Employee_Table ;
CREATE VIEW Course_Credits_V (CourseName, Hours) AS
LOCKING Course_Table FOR ACCESS SELECT Course_Name, Credits
FROM Course_Table ;
CREATE VIEW Sales_Low_V AS
LOCKING Sales_Table FOR ACCESS
SELECT * FROM Sales_Table
WHERE Daily_Sales <= 35000 ;
English: The above examples are explicitly telling Teradata to put an ACCESS Lock on the tables
being read instead of the default READ Lock.
Teradata places locks for users automatically, but in a data warehouse Decision Support
Environment many users don’t want to wait on a table or row that has a WRITE Lock
placed on it. The above queries tell Teradata to put an ACCESS lock on the table so they
won’t wait on a WRITE Lock. Only do this for queries where the answer does not have to Hint - Man
be exact.
For more information on Lock Types, refer to “Teradata SQL: Unleash the Power” by
Larkins and Coffing, Chapter 16, or “Tera-Tom on Teradata Basics” by Jones and
Coffing.
Hint - Man
Page 92 The SQL Quick Reference Guide
Simplicity by Design
MACROS
Often in sports each team has a number of set plays that they run during a game sometimes
in order to guarantee success. In Teradata, these set plays are called Macros. Each macro
has a set order of SQL commands that has a predictable result, just like the plays used by a
basketball team. Another important thing to remember about Macros is that Teradata treats
them as one single transaction. What this means is either the macro works or does not. There is no partial success.
CREATE Macro
It is very important to remember that ‘CM’ does not work with any ODBC tool, only on
BTEQ. Once this SQL is run Teradata will store the definition and also the parsed plan of
execution.
CREATE MACRO <macro-name> (<variable -name> <data- type>, … ) AS
( [ INSERT … ; ]
[ UPDATE … ; ]
[ DELETE … ; ]
[ SELECT … ; ] ) ;
CREATE MACRO Add_Dept_M AS
(d_no SMALLINT, d_name char(20), Mgr_No INTEGER, budget DECIMAL(10,2) )
( INSERT INTO Department_Table
(dept_no, dept_name, Mgr_No, budget) ; ) ;
English: The macro above is set up to take input parameters when executed.
CREATE MACRO Remove_Sales_Date_M AS( DELETE FROM Sales_Ta ble
WHERE Sale_Date = Current_Date – 30 ; ) ;
CREATE MACRO Check_Orders AS
( SELECT * FROM Order_Table ;
SELECT * FROM Customer_Table WHERE Customer_Number IN
(SELECT Customer_Number FROM Order_Table) ; ) ;
English: The macro above runs multiple queries within the same ma cro.
When CREATING a MACRO remember that every Macro ends with ;);
The first semi -colon ends the last SQL statement in the macro and the close parenthesis and ending semi -colon ends the Macro itself. Hint - Man
The SQL Quick Reference Guide Page 93
The SQL Reference Guide
It is always recommended to write out the full ‘CREATE MACRO’ syntax in order to
eliminate any possible confusion of users looking at the query at a later time.
Hint - Man
Issues: 3707: Syntax error, expected something like ';' between a ‘<any SQL>’ and ')'.
When Teradata returns this message, there is a need for a semi-colon inside the
parentheses of the macro declaration.
Solutions: Directly inside the ‘)’, place a ‘;’ character, and execute the CREATE MACRO
request again.
EXECUTE Macro
This is the syntax allows a user to run a macro, with passing along any parameters if
needed.
EXEC <macro-name> [ ( <parameter- value -list> ) ] ;
EXEC Add_Dept_M(600, ‘Technical Support’, 2341218, 525000);
EXEC Update_Sal_M ;
Page 94 The SQL Quick Reference Guide
Simplicity by Design
REPLACE Macro
Teradata treats this syntax as a “Smart Replace” . Teradata will recreate the macro
<macro- name> as if it does not already exist. This syntax changes the DDL of a macro.
REPLACE MACRO <macro-name> AS
( [ INSERT … ; ]
[ UPDATE … ; ]
[ DELETE … ; ]
[ SELECT … ; ] ) ;
REPLACE MACRO Update_Sal_M AS
( UPDATE Employee_Table SET Salary = Salary * 1.10 ; ) ;
REPLACE MACRO Remove_Sales_Date_M AS
( DELETE FROM Sales_Table
WHERE Sale_Date = Current_Date – 60 ; ) ;
REPLACE MACRO Order_M AS
( SELECT * FROM Order_Table
WHERE Order_Total > 10000 ; ) ;
A clever technique to replacing a macro is to run the SHOW MACRO <MacroName>
command. Then when the answer set shows the current macro structure you can copy it and then change the word CREATE to REPLACE and make your changes. This is safer
and more efficient then trying to retype the entire macro in again. Hint - Man
DROP Macro
DROP MACRO completely removes a macro’s definition and parsed execution plan from
Teradata’s Data Dictionary.
DROP MACRO <macro-name> ;
DROP MACRO Remove_Sales_Date_M ;
DROP MACRO Add_Dept_M ;
The SQL Quick Reference Guide Page 95
The SQL Reference Guide
Transaction Processing
Locking Modifiers
Lock Types
Lock Type Brief Description
Exclusive Used mainly when Table or Database DDL is being modified. Causes object to be inaccessible. Locks at the Database or Table Level.
Write A data block is being modified, making it temporarily unavailable.
Read Data is retrieved from a disk, with no changes made. <DEFAULT for all
users>
Access A “Dirty Read”. Allows a user to access data that is currently locked with a
Write Lock.
For more details on Locks and Lock compatibility, refer to Chapter 16, ‘Teradata SQL:
Unleash the Power’ book by Larkins and Coffing.
Hint - Man
Lock Syntax
The default level of locking for this syntax is Row Level . NOWAIT serves the purpose of
ignoring any lock that is on that specific row, and performing the SQL immediately.
LOCKING[<table -name>] FOR <desired- locking> [NOWAIT]
LOCKING Order_Table for READ SELECT * FROM Order_Table ;
LOCKING Department_Table for WRITE NOWAIT
INSERT INTO Department_Table
(700, ‘Shipping’, 1000234, 450000) ;
Page 96 The SQL Quick Reference Guide
Simplicity by Design
LOCKING ROW FOR <desired- locking>
LOCKING ROW FOR ACCESS
SELECT * FROM Customer_Table
WHERE Customer_Name = ‘ACE Consulting’ ;
LOCKING DATABASE <database- name> FOR <desired-locking>
LOCKING DATABASE Sql_Class FOR EXCLUSIVE
MODIFY DATABASE Sql_Class AS
Permanent = 5500000 BYTES ;
LOCKING VIEW <view-name> FOR <desired-locking>
LOCKING VIEW Employee_V FOR READ
SELECT * FROM Employee_V ;
LOCKING TABLE <table -name> FOR <desired- locking>
LOCKING Department_Table for WRITE NOWAIT
INSERT INTO Department_Table
(700, ‘Shipping’, 1000234, 450000) ;
The SQL Quick Reference Guide Page 97
The SQL Reference Guide
Transaction Modes
Teradata offers two types of Transaction Modes in ANSI or Teradata mode. Teradata
mode is called BTET, which stands for Begin Transaction End Transaction. The difference
between the two modes is represented in the table below. One big key to remember is that
users can utilize either mode and all SQL commands work in either mode.
Transaction Mode Types
TERADATA Mode ANSI Mode
Data comparison is not case specific . Data comparison is case specific . Character literal
Character literal values can be coded in the values must be coded using the correct case in order SQL as lower case or upper case. The search for the search engine to determine a match. An ‘A’
engine would view an ‘A’ the same as an ‘a’ is different than an ‘a’ and data would not be
and the data would be returned. returned.
Allows truncation of displayed data. Certain Forbids truncation of display data. Any attempt SQL commands covered in the chapter allow to return less than all the data stored in a column
the user to request less characters be returned will cause the SQL to fail with an error (3996).
than the number of characters stored in a column. This is perfectly acceptable.
A transaction is implicit by nature – each All transactions are explicit only and at the end of a
SQL statement is a stand-alone transaction transaction a COMMIT WORK command is
and the work committed upon a successful required in order to commit all successfully completion. A transaction can also be explicit completed work and make it permanent. with a BEGIN TRANSACTION (BT)
command and an END TRANSACTION (ET)
command. The presence of the ET command
will cause all succes sfully completed SQL
work to be committed and make it permanent.
The CREATE TABLE will default to: The CREATE TABLE will default to:
SET table (no duplicate rows allowed) MULTISET table (duplicate rows allowed)
Non-case specific character data columns Case specific character data columns
Page 98 The SQL Quick Reference Guide
Simplicity by Design
Setting the Transaction Mode
This syntax sets the mode to Teradata Mode , which is normally the default when a userlogs in. This syntax is only to be used in BTEQ.
.SET SESSION TR ANSACTION BTET ;
The syntax places the user session into ANSI Mode , which is a Case Sensitive mode that requires the user to COMMIT WORK after transactions. This syntax is only to be used in
BTEQ .
.SET SESSION TRANSACTION ANSI ;
When setting the transaction mode in BTEQ, you must set the Transaction mode BEFORE
logging onto the Teradata system. If you are already logged in and would like to change modes you must logoff, set the mode, and then log back on.
Hint - Man
Teradata Transaction Mode (BT/ET)
BT/ET allows for establishing a manual transactionwhile in Teradata mode . BT stands
for Begin Transaction, ET stands for End Transaction.
BT ;
<SQL- statement>
[… <SQL- statement>]
ET ;
BT ; UPDATE Employee_Table
SET Salary = Salary * 1.15
WHERE Employee_No = 1232578 ;
.if errorcode > 0 then .quit 12
UPDATE Department_Table
FROM Employee_Table AS ESET Budget = Budget + (Salary * .015) WHERE E.Dept_No = Department_Table.Dept_No
AND E.Employee_No = 1232578 ;
ET ;
Normally the BT/ET Statement is used in BTEQ. In BTEQ error checking is available.
The above example is BTEQ Specific. For more information refer to Chapter 16 “Teradata SQL: Unleash the Power” book by Larkins and Coffing.
Hint - Man
The SQL Quick Reference Guide Page 99
The SQL Reference Guide
Commit Work
The Commit Work syntax is used only in ANSI Transaction Mode . It ensures that all
transactions prior to the statement have been properly processed.
COMMIT WORK ;
UPDATE Employee_Table
SET Salary = Salary * 1.15
WHERE Employee_No = 1232578 ; .if errorcode > 0 then .quit 12
UPDATE Department_Table
FROM Employee_Table AS E
SET Budget = Budget + (Salary * .015) WHERE E.Dept_No = Department_Table.Dept_No
AND E.Employee_No = 1232578 ;
COMMIT WORK ;
Issues: User is in Teradata mode, therefore commit work is not needed.
3706: Syntax error: COMMIT WORK not allowed for a DBC/SQL session.
Solutions: If there is a need to be in ANSI mode, a user must be running BTEQ . Before
logging onto the Teradata system enter the ‘.SET SESSION TRANSACTION
ANSI’ command. This will put you in ANSI mode. If there is no need for ANSI
mode simply remove ‘COMMIT WORK’ or use the BT/ET SQL syntax.
Abort/Rollback
These statements are used only in Teradata mode in the middle of a BT/ET Transaction.
An alternative for this is simply logging off to end the session before the ET in the
Transaction.
ABORT;
Or
ROLLBACK ;
BT ;
SELECT * FROM Department_Table ;
INSERT INTO Department_Table
(800, ‘Administration’, 1423546, 250000) ;
ABORT ; (Alternative: ROLLBACK ; )
Page 100 The SQL Quick Reference Guide
Simplicity by Design
Rollback Work
This syntax is used to roll back a transaction while using ANSI Transaction Mode .
ROLLBACK WORK ;
SELECT * FROM Department_Table ;
INSERT INTO Department_Table
(800, ‘Administration’, 1423546, 250000) ;
ROLLBACK WORK ;
The example is written under the assumption the user is in ANSI Transaction Mode.
Hint - Man
Issues: User is in Teradata Mode, therefore this syntax is not valid. Use ABORT instead.
The SQL Quick Reference Guide Page 101
The SQL Reference Guide
Reporting Totals and Subtotals
Managers are always asking for detailed reports and information on performances broken
down into various sections. In quoting Jim Carrey from the move Liar, Liar: “And the
truth shall set you free!!!” Using WITH and WITH..BY will break down the truth, the
whole truth, and nothing but the truth and result in detailed reports that are logical and easy
to read. One big thing to remember is that these are to be used in BTEQ rather than
Queryman.
Totals (WITH)
Using the WITH provides the user the ability to Total a given <column-name> . All
aggregate functions may be applied.
SELECT <column- name>
,[…, <column-name> ]
FROM <table- name>
WITH <aggregate-function>( <column-name> ) [ (TITLE ‘<title-string>:’) ]
[...,<aggregate-function>( <column-name> ) [ (TITLE ‘<title-string>:’) ] ] ;
SELECT Dept_No, Dept_Name, Budget FROM Department_Table
WITH SUM(Budget) (TITLE ‘Total Budget’) ;
English: The above example will select detail lines for Dept_No, Dept_Name, and Budget. At
the end of the report a grand total for SUM(Budget) will be given.
SELECT Last_Name, First_Name, Dept_No, Salary
FROM Employee_Table
WITH AVG(Salary) , SUM(Salary) ;
English: The above example will select detail lines for Last_Name, First_Name, Dept_No, and
Salary. At the end of the report a grand total for AVG(Salary) and SUM(Salary) will be given.
This syntax can NOT be used in Queryman, so you must use BTEQ for this command.
Hint - Man
Issues: An aggregate function must be used in a WITH statement.
3504: Selected non-aggregate values must be part of the associated group.
Solutions: Place an aggregate function of your choice in the WITH statement.
Page 102 The SQL Quick Reference Guide
Simplicity by Design
Subtotals (WITH..BY)
WITH..BY allows for subtotals based on the BY <column-name> clause.
SELECT <column- name>
,<column- name>
FROM <table- name>
WITH SUM( <column-name> ) [...,<aggregate-function>( <column-name> ) ]
BY <column-name> [ (TITLE ‘<title-string>:’) ]
[ …WITH SUM( <column-name> ) [...,<aggregate-function>( <column-name> ) ]
BY <column-name> [ (TITLE ‘<title-string>:’) ] ] ;
SELECT Dept_No, Dept_Name, Budget
FROM Department_Table
WITH SUM(Budget) (TITLE ‘Total Budget’)
BY Dept_No ;
English: The above query will produce detail lines for Dept_No, Dept_Name, and Budget. It will
also produce a SUM(Budget) subtotal for each Dept.
This syntax is not available in Queryman, but is supported in BTEQ. BTEQ is the
recommended tool to use when creating reports with totals and subtotals.
Hint - Man
Issues: An aggregate function must be used in a WITH..BY statement.3504: Selected non-aggregate values must be part of the associated group.
Solutions: The way to fix this problem is to place the aggregate of choice after the ‘WITH’ inthe request statement.
The SQL Quick Reference Guide Page 103
The SQL Reference Guide
Multiple WITH..Bys
Using a combina tion of the WITH and WITH..BY functions can be very powerful. Thisallows the user to create complex reports that include both grand totals and subtotals.
SELECT Product_Id, Sale_Date, Daily_Sales
FROM Sales_Table
WITH SUM(Daily_Sales) (TITLE ‘By Month’) BY Sale_Date/100
WITH SUM(Daily_Sales) (TITLE ‘By Product) BY Product_Id
WITH SUM(Daily_Sales) WHERE Product_Id IN (1000, 2000) ORDER BY Sale_Date ;
English: The above query will produce detail lines for Product_Id, Sale_Date, and Daily_Sales. It will then produce subtotals of SUM(Daily_Sales) By Month. Then another subtotal break of
SUM(Daily_Sales) will be produced by Product within month. There will be a Grand_Total of
SUM(Daily_Sales) at the end of the report.
Page 104 The SQL Quick Reference Guide
Simplicity by Design
Data Definition Language
If you use the keywords CREATE, DROP or ALTER you are using Data Definition
Language. You are defining objects or the way objects look or function.
Create Table
Teradata is extremely flexible and allows the user to create a table without declaring a
Primary Index. However, Teradata will assign by default a Non-Unique Primary Index
on the first column if a Primary Index is not defined in the Create Table statement.
CREATE TABLE [<database- name>.]<table -name>
( <column-name> <data- type>
[...,<column-name> <data- type> ] )
[UNIQUE] PRIMARY INDEX [<index-name>] (<column-name>) ;
CREATE TABLE SQL_CLASS.VENDOR_TABLE
(Vendor_Id INTEGER
,Vendor_Name VARCHAR(20) ,Phone_Number CHAR(8)
)UNIQUE PRIMARY INDEX (Vendor_Id) ;
Using the <database-name> to identify the table is known as qualifying, which is
discussed in Appendix E.
Hint - Man
*Detailed information on Data Types can be found in Appendix C.
The SQL Quick Reference Guide Page 105
The SQL Reference Guide
Multiple Column Primary Index
Although multiple column Primary Indexes are allowed, it is recommended to use singlecolumn Primary Indexes whenever possible.
CREATE TABLE [<database- name>.]<table -name>
( <column-name> <data- type>
[...,<column-name> <data- type> ] )
[UNIQUE] PRIMARY INDEX [<index-name>](<column- name> [..,<column-name>] ) ;
CREATE TABLE SQL_CLASS.VENDOR_TABLE
(
Vendor_Id INTEGER
,Vendor_Name VARCHAR(20) ,Phone_Number CHAR(8)
)
UNIQUE PRIMARY INDEX VNDRIDX (Vendor_Id, Vendor_Name) ;
Issues: 3707: Syntax error, expected something like an 'UNIQUE' keyword between the
word '<column-name>' and ','. The error is caused by not assigning a data type to a
column that is being defined.
Solutions: The only way to fix this syntax is to look at the create statement and locate the
column name that does not have a data type, then assign it a data type accordingly.
Page 106 The SQL Quick Reference Guide
Simplicity by Design
SET | MULTISET Table
MULTISET Tables allow for multiple instances of the same row . The default for
Teradata Mode is SET . The default for ANSI Mode is MULTISET . A SET table will
throw out any rows that are complete duplicates. If you don’t care which type you have it
is better to have a Multi- Set table because SET tables must always compare rows for
duplicates.
CREATE [SET | MULTISET] TABLE [<database- name>.]<table -name>
( <column-name> <data- type>
[...,<column-name> <data- type> ] )
[UNIQUE] PRIMARY INDEX [<index-name>](<column- name>[…,<column- name>]) ;
CREATE SETTABLE SQL_CLASS.VENDOR_TABLE
(Vendor_Id INTEGER
,Vendor_Name VARCHAR(20) ,Phone_Number CHAR(8)
)UNIQUE PRIMARY INDEX VNDRIDX(Vendor_Id, Vendor_Name) ;
CREATE MULTISET TABLE SQL_CLASS.VENDOR_TABLE
(Vendor_Id INTEGER
,Vendor_Name VARCHAR(20)
,Phone_Number CHAR(8) )UNIQUE PRIMARY INDEX VNDRIDX(Vendor_Id, Vendor_Name) ;
MULTISET tables are quite useful when using Teradata for accounting purposes.
Hint - Man
Issues: A common error could be caused by having a spa ce in ‘MULTISET’. This is the
error returned by Teradata: 3706: Syntax error: Expected GLOBAL TEMPORARY.
Solutions: The only solution to this is to remove the space in the ‘MULTISET’ phrase.
The SQL Quick Reference Guide Page 107
The SQL Reference Guide
FALLBACK
FALLBACK is a Table specific Teradata feature to protect against AMP failure . The
default is NO FALLBACK.
CREATE [SET | MULTISET] TABLE [<database-name>.]<table - name>
[, FALLBACK ]
( <column-name> <data- type>
[...,<column-name> <data- type> ] )
[UNIQUE] PRIMARY INDEX [<index-name>](<column- name>[…,<column- name>]) ;
CREATE SET TABLE SQL_CLASS.VENDOR_TABLE, FALLBACK
(
Vendor_Id INTEGER
,Vendor_Name VARCHAR(20)
,Phone_Number CHAR(8) )
UNIQUE PRIMARY INDEX (Vendor_Id) ;
You can FALLBACK protect all tables, no tables, or some tables. You can also add or
drop FALLBACK at any time.
Hint - Man
Issues: A missing comma between the <table -name> and FALLBACK. 3706: Syntax error: expected something between the word ‘VENDOR_TABLE2’
and the ‘FALLBACK’ keyword.
Solutions: Simply place a comma before the ‘FALLBACK’ keyword.
Page 108 The SQL Quick Reference Guide
Simplicity by Design
Permanent Journal
There are three variances for the Permanent Journal: BEFORE, AFTER, DUAL
BEFORE/DUAL AFTER. The BEFORE Journal takes a picture of the affected rows
before any changes are made. The AFTER Journal takes a picture of the affected rows
after any changes are made. The DUAL BEFORE or DUAL AFTER Journal takes two
pictures before the rows are changed and saves them on two different AMPs. The
DUAL AFTER Jounal takes two pictures after that rows are changed and stores them
on two different AMPs . All the pictures are stored on disk, so be sure to purge the
Journal after a full system backup.
CREATE [SET | MULTISET] TABLE [<database-name>.]<table - name>
[, FALLBACK ] [, [DUAL ] BEFORE JOURNAL ] [, [DUAL ] AFTER JOURNAL ]
( <column-name> <data- type>
[...,<column-name> <data- type> ] )
[UNIQUE] PRIMARY INDEX [<index-name>](<column- name>[…,<column- name>]) ;
CREATE SET TABLE SQL_CLASS.VENDOR_TABLE, FALLBACK
, BEFORE JOURNAL( Vendor_Id INTEGER
,Vendor_Name VARCHAR(20) ,Phone_Number CHAR(8) )
UNIQUE PRIMARY INDEX VNDRIDX(Vendor_Id, Vendor_Name) ;
CREATE SET TABLE SQL_CLASS.VENDOR_TABLE, FALLBACK
, AFTER JOURNAL
( Vendor_Id INTEGER
,Vendor_Name VARCHAR(20) ,Phone_Number CHAR(8) )
UNIQUE PRIMARY INDEX VNDRIDX(Vendor_Id, Vendor_Name) ;
CREATE SET TABLE SQL_CLASS.VENDOR_TABLE, FALLBACK
, DUAL BEFORE JOURNAL, DUAL AFTER JOURNAL
( Vendor_Id INTEGER
,Vendor_Name VARCHAR(20) ,Phone_Number CHAR(8)
) UNIQUE PRIMARY INDEX VNDRIDX(Vendor_Id, Vendor_Name) ;
The most common journal is the AFTER JOURNAL. This will be used in conjunction
with Full System Backups. If a crash occurs the DBA can go to the last Full System
Backup and then add the After Journal.
Hint - Man
The SQL Quick Reference Guide Page 109
The SQL Reference Guide
Add Column Attributes
CREATE [SET | MULTISET] TABLE [<database-name>.]<table - name>
[, FALLBACK ] [, [DUAL ] BEFORE JOURNAL ] [, [DUAL ] AFTER JOURNAL ]
( <column-name> <data- type> [<column-level-attribute>]
[...,<column-name> <data- type> ][<column-level-attribute>] )
[UNIQUE] PRIMARY INDEX [<index-name>](<column- name>[…,<column- name>]) ;
The following is a list of all the column level attributes.
Hint - Man
UPPERCASE Convert and store entered data in uppercase
CASESPECIFIC Treat data as case specific for all comparisons
FORMAT Establishes the display format
TITLE Establishes the title attribute
NAMED Establishes an alias nameWITH DEFAULT Default numeric values to zero, characters values to blanks
DEFAULT DATE Use today’s date as default value
DEFAULT TIME Use current time as default value
COMPRESS Compress nulls to take no disk space
COMPRESS NULL Compress nulls to take no disk spaceCOMPRESS <value> Compress specified value to take no disk space. The value is stored
one time in the table header.CHARACTER SET Establishes the computer internal storage rules and how it should be
interpreted. i.e. LATIN and KANJI
NOT NULL Disallow nulls to be stored in the column
DEFAULT Value Use default value if null entered
DEFAULT User Use the user’s ID as the default value for the columnDEFAULT NULL Use null as the default value for the column
CREATE SET TABLE SQL_CLASS.VENDOR_TABLE, FALLBACK
, BEFORE JOURNAL
(
Vendor_Id INTEGER NOT NULL,Vendor_Name VARCHAR(20) TITLE ‘Vendor Name’,Phone_Number CHAR(8) DEFAULT NULL
)
UNIQUE PRIMARY INDEX (Vendor_Id) ;
Page 110 The SQL Quick Reference Guide
Simplicity by Design
Column and Table Constraints
CREATE [SET | MULTISET] TABLE [<database-name>.]<table - name>
[, FALLBACK ] [, [DUAL ] BEFORE JOURNAL ] [, [DUAL ] AFTER JOURNAL ]
( <column-name> <data- type> [<column-level-attribute>] [<column-level-constraint>]
[...,<column-name> <data- type>][<column-level- attribute>] [<column-level-constraint>] )
[UNIQUE] PRIMARY INDEX [<index-name>](<column- name>[…,<column- name>])
[<column-level-constraint>]
[… ,<column-level-constraint>] ;
For more information and examples refer to “Teradata SQL: Unleash the Power”, Chapter
18.
Hint - Man
This chart is used to determine the level constraints can be named:
Constraint Used as Column Level Used as Table Level
PRIMARY KEY Yes Yes
UNIQUE Yes Yes
CHECK Yes Yes
REFERENCES Yes Yes
FOREIGN KEY No Yes
This chart is used to determine the functio n of the constraints:
PRIMARY KEY A PRIMARY KEY enforces uniqueness. You must have the NOT
NULL constraint also defined when defining a PRIMARY KEY.
UNIQUE UNIQUE enforces uniqueness on a column. You must have the
NOTNULL constraint also defined when defining a UNIQUE
constraint. CHECK Allows range or value constraints to be placed on the column.
REFERENCES Requests a referential integrity check. This requires values to be
reference checked or selected from another table before accepting
a new row into this table
CREATE SET TABLE SQL_CLASS.VENDOR_TABLE, FALLBACK, BEFORE JOURNAL
(Vendor_Id INTEGER NOT NULL
CONSTRAINT UNIQUE_1
UNIQUE,Vendor_Name VARCHAR(20) TITLE ‘Vendor Name’
,Phone_Number CHAR(8) DEFAULT NULL);
The SQL Quick Reference Guide Page 111
The SQL Reference Guide
CREATE TABLE with copying an existing table
The Teradata Lingo for this syntax is the “Create Table AS” statement. The default for
this statement isNO DATA .
CREATE TABLE [<database- name>.]<table -name> AS
{ <SELECT-statement>}
WITH { DATA | NO DATA }
[ [ UNIQUE ] PRIMARY INDEX (<column-list>) ] ;
CREATE TABLE SQL_CLASS.Employee_Table2 AS
( SELECT * FROM Employee_Table )
WITH DATA ;
English: The above example will CREATE a table called Employee_Table2 in the SQL_CLASS
database that has the exact same structure as the Employee_Table. The data from the
Employee_Table is also copied into the Employee_Table2 table.
CREATE TABLE SQL_CLASS.Employee_Table2 AS
( SELECT * FROM Employee_Table ) WITH NO DATA
UNIQUE PRIMARY INDEX(Employee_Id) ;
English: The above example will CREATE a table called Employee_Table2 in the SQL_CLASS
Database that has the exact same structure as the Employee_Table, but the data is not copied. The
new table is completely empty of data.
For more information and examples refer to “Teradata SQL: Unleash the Power” book by
Larkins and Coffing, Chapter 18.
Hint - Man
Page 112 The SQL Quick Reference Guide
Simplicity by Design
ALTER Table
ALTER TABLE is used to modify a Table or column level attribute and constraint . A
user may not change column names, but adding or dropping columns are permissible. If
column changes are required, then the table must be dropped and re- created with the
column name changes included.
ALTER TABLE [<database-name>.]<table- name>
[, <table- level- attributes> ]
[ WITH JOURNAL TABLE = <table- name> ]
[ ADD <column-name>[<data-type>][<attribute-list>][<column-level-constraint>] ]
[ DROP <column-name>]
[ ADD <table-level-constraint> ]
[ MODIFY <table-level-constraint> ]
[ DROP <table-level-constraint> ] ;
ALTER TABLE SQL_CLASS. Vendor_Table
, NO BEFORE JOURNAL, AFTER JOURNAL
ADD Vendor_Desc VARCHAR(65), DROP VENPK ;
ALTER TABLE SQL_CLASS.Course_Table
ADD Prerequisites VARCHAR(150) TITLE ‘Prereqs’ ADD CONSTRAINT COURSE_Unique UNIQUE(Course_Name) ;
In the first example VENPK is a <table-level-constraint> defined in the example section
of Column and Table Constraints.
Hint - Man
Issues: The table being altered does not exist. 3807: Table/view/trigger ‘Course_Table2’
does not exist.
Solutions: There are two possible causes and they are a misspelled <table -name> or you may
be looking in the wrong database. To solve both causes run ‘HELP DATABASE
<database-name>’ to do research about the table you are looking to alter.
The SQL Quick Reference Guide Page 113
The SQL Reference Guide
DROP Table
If a user is looking to permanently remove a table from the Teradata Warehouse, this is
the proper SQL to run. However, unlike other databases, Teradata is capable of deleting all
rows of a table very quickly. It is recommended to delete all rows rather than drop a table
and recreating it.
; DROP TABLE [<data-base- name>.]<table -name>
DROP TABLE SQL_CLASS.Vendor_Table ;
It is recommended to delete all rows rather than drop a table and recreating it. The
DELETE Syntax is addressed in the Data Manipulation Section of the book.
Hint - Man
Issues: The table being dropped does not exist. 3807: Table/view/trigger ‘Course_Table2’ does not
exist.
Solutions: There are two possible causes are a misspelled <table-name> or you may be looking in the wrong database. To solve both causes run ‘HELP DATABASE <database-name>’ to do
research about the table you are looking to alter.
Page 114 The SQL Quick Reference Guide
Simplicity by Design
RENAME Table
When renaming a table, the <database- name> cannot be changed.
RENAME TABLE [database-name>.]<table - name>
TO [database-name>.]<table- name> ;
RENAME TABLE SQL_CLASS.Department_Table
TO SQL_CLASS.Dept_Table ;
If there is a need to have a table with the same structure in a separate database, use the
CREATE TABLE AS syntax which can be located in the Data Definition Language section of this book.
Hint - Man
Issues: The table being renamed does not exist. 3807: Table/view/trigger ‘Course_Table2’ does not exist.
Solutions: There are two possible causes are a misspelled <table -name> or you may be
looking in the wrong database. To solve both causes run ‘HELP DATABASE
<database-name>’ to do research about the table you are looking to alter.
The SQL Quick Reference Guide Page 115
The SQL Reference Guide
Secondary Indexes
Secondary Indexes are used in Teradata as another method to accessing data . Value -
Ordered NUSIs are limited to numeric values that are no larger than 4 bytes long. Also, the
index name is optional.
CREATE [UNIQUE] INDEX [ <index-name> ] (<column-list>)
[ORDER BY VALUES [ (<column-list>) ] ] on [database.]<table-name>
[ALL] ;
CREATE UNIQUE INDEX (Course_Name)ON SQL_CLASS.Course_Table ;
English: Above we have created a Unique Secondary Index (USI) on Course_Name.
CREATE INDEX (Course_Id)
ORDER BY VALUES
ON SQL_CLASS.Student_Course_Table ;
English: Above we have created a Value -Ordered NUSI on Course_Id.
CREATE INDEX Full_Name_Idx(First_Name,Last_Name)
ON SQL_CLASS.Employee_Table ;
English: Above we have created a Multi-Key Non-Unique Secondary Index (NUSI) on
First_Name and Last_Name combined. We have given the index a name called Full_Name_Idx.
Refer to the “Teradata Users Guide” by T.Coffing, L.Coffing, C.Coffing, S.Wilmes and
R.Hines for further information on Secondary Index selection and Performance Optimization.
Hint - Man
A Unique Secondary Index (USI) is always a two -AMP retrieve when the USI column is
used in the WHERE clause of the SQL.
A Non-Unique Secondary Index (NUSI) is an All-AMP operation, but not a Full Table Hint - Man Scan (FTS).
DROP INDEX { <index- name> | (<column- list>) } ;
DROP INDEX Crs_Nm_Indx ;
Page 116 The SQL Quick Reference Guide
Simplicity by Design
Join Indexes
Join Indexes provide the means of improving performance on any type of recurring query
that involves joins and/or aggregate functions. A Join Index pre-joins tables and physically
keeps them on disks. The Teradata optimizer will decide whether a query can run faster on
the base tables or with the Join Index table. The Join Index table will be kept current by
Teradata if the base tables change.
CREATE JOIN INDEX [<database-name>.]<join- index-name>
[[NO] FALLBACK]
AS SELECT
[<columns>]
[SUM numeric -expression]
[COUNT column- expression]
[EXTRACT year | month from date- expression]
FROM [<database-name(s)>.]<table- names>]
[WHERE <search- condition>]
[GROUP BY <column- name>]
[ORDER BY <column-name>]
PRIMARY INDEX(<column- name>)
[index <column-name> ORDER by HASH | VALUES] ;
CREATE JOIN INDEX SQL_CLASS.Course_Roster
NO FALLBACK AS
SELECT STU.Last_name ,STU.First_name
,STU.Class_code
,COUR.Course_name
,COUR.Credits
,STU_COUR.Student_ID
FROM
Student_table STU
INNER JOIN Student_Course_Table STU_COURON STU.Student_ID = STU_COUR.Student_ID
INNER JOIN Course_Table COUR
ON STU_COUR.Course_ID = COUR.Course_ID;
Teradata Versions V2R4.1.2xx and later allows for single table join indexes to be created.
This is extremely beneficial when you create a single table join index on larger tables that
are being utilized in joins with smaller tables. In addition, single table join indexes do not require all the columns to be listed in order for Teradata to utilize the join index. Partial covering of the join index is supported, which provides a significant performance Hint - Man enhancement and greatly flexibility.
DROP JOIN INDEX [<database-name>.]<join-index- name>;
DROP JOIN INDEX SQL_CLASS.Student_Table_Indx ;
The SQL Quick Reference Guide Page 117
The SQL Reference Guide
Collect Statistics
This is a very important part of optimizing and maintaining the Teradata System. When a
query is run the Parsing Engine (PE) optimizer will check if statistics were run on the table.
Collect statistics will tell the PE what the data demographics are in order for the PE to
come up with a plan for the AMPs to get the data. You can collect statistics at the column
or index level.
COLLECT STATISTICS ON [ TEMPORARY ] <table - name> | <join-index- name>
[ { COLUMN <column-name> | INDEX(<column- list>) } ] ;
COLLECT STATISTICS ON Employee_Table column Last_Name ;
English: Above we collect statistics on the column Last_Name in the Employee_Table.
COLLECT STATISTICS ON Employee_Table
index(Last_Name, First_Name) ;
English: Above we collect statistics on the multi-column index of Last_Name and First_Name.
COLLECT STATISTICS ON Employee_Table
English: Above we refresh statistics on all columns and indexes that have current statistics.
Collecting Statistics causes a Full Table Scan (FTS) and should be done during off hours.
You don’t collect on every index and column in a table. Collect Statistics for all Non- Unique Secondary Indexes, columns used in the WHERE clause on queries or joins, and
on Primary indexes of all small tables. Hint - Man
Refresh statistics when a table adds or deletes data and this changes the table by more than
10%. Always collect statistics at the column level even if a column is an index. The
exception to this rule is on Multi-Column indexes.
Hint - Man
Page 118 The SQL Quick Reference Guide
Simplicity by Design
HELP STATISTICS
HELP STATISTICS is used to discover what columns and indexes have statistics run on
them . Information returned contains the time and date statistics of when last time statistics
were collected.
HELP STATISTICS <table-name> ;
HELP STATISTICS Student_Table ;
DROP STATISTICS
DROP STATISTICS is recommended when the decision has been made to no longer keep
statistics on the given <table -name>.
DROP STATISTICS ON [ TEMPORARY ] <table-name> | <join- index-name>
[ { COLUMN <column-name> | INDEX(<column- list>) } ] ;
DROP STATISTICS ON SQL_CLASS.Department_Table ;
DROP STATISTICS ON Student_Table
INDEX (Last_Name) ;
The SQL Quick Reference Guide Page 119
The SQL Reference Guide
CREATE DATABASE
You create a database to normally hold objects such as Tables, Views, Macros, Triggers, and Stored Procedures. A Database and a User are almost the same in Teradata because
both can have Perm and Spool space, which allow them to hold objects. The only
difference between a user and a database is that a user has a password and can logon andrun queries.
{ CREATE | MODIFY } DATABASE <database-name> FROM
<parent-database-name> AS[ PERM[ANENT] = <num-of-bytes>
SPOOL = <num-of-bytes>
TEMPORARY = <num-of-bytes>
ACCOUNT = <acctid>
[NO] FALLBACK
[NO | DUAL] BEFORE JOURNAL
[NO | DUAL | LOCAL | NOT LOCAL] AFTER JOURNAL
DEFAULT JOURNAL TABLE = <database-name>.<table-name> ] ;
CREATE DATABASE SQL_CLASS2 FROM SYSADMIN AS
PERM = 5000000
, SPOOL = 2000000
, TEMPORARY = 1000000
, ACCOUNT = ‘carrolltg’ , NO FALLBACK
, NO BEFORE JOURNAL
, NO AFTER JOURNAL
, DEFAULT JOURNAL TABLE = SQL_CLASS2.Journal_Table ;
When defining the upper limit for Perm space, remember to have enough disk space in the
system to have 20% in Spool Reserve. It’s a good idea to research the impact on the
system when creating large databases.
Hint - Man
Page 120 The SQL Quick Reference Guide
Simplicity by Design
CREATE USER
You create a USER so that user can logon to Teradata and run queries. A user in Teradata
can hold objects such as Tables, Views, Macros, Triggers, and Stored Procedures. A
Database and a User are almost the same in Teradata because both can have Perm and
Spool space, which allow them to hold objects. The only difference between a user and a
database is that a user has a password and can logon and run queries.
{ CREATE | MODIFY } USER <user-name> FROM
<parent-database-name> AS
PERM[ANENT] = <num-of-bytes>
PASSWORD = { <password> | NULL }
[
,STARTUP = <string>
,SPOOL = <num-of-bytes>
,TEMPORARY = <num-of-bytes>
,DEFAULT DATABASE = <database-name>
,COLLATION = <collation-sequence>
,ACCOUNT = <acctid>
,[NO] FALLBACK
,[NO | DUAL] BEFORE JOURNAL
,[NO | DUAL | LOCAL | NOT LOCAL] AFTER JOURNAL
,DEFAULT JOURNAL TABLE = <database-name>.<table-name> ] ;
CREATE USER SQL26 FROM SQL00 AS
PERM = 1000000, PASSWORD = SQL26
, STARTUP = ‘SET SESSION ANSI;’
, SPOOL = 10000000
, TEMPORARY = 5000000
, DEFAULT DATABASE = SQL_CLASS
, COLLATION = HOST
, ACCOUNT = ‘carrolltg’, NO FALLBACK
, NO BEFORE JOURNAL
, NO AFTER JOURNAL ;
Teradata views a User as a Database with a password. A User may store all objects in its
PERM space, and behave exactly like a database.
Hint - Man
The SQL Quick Reference Guide Page 121
The SQL Reference Guide
DROP DATABASE or USER
This syntax will remove the DDL of a User or Database from the Data Dictionary.
DROP{ DATABASE | USER } <database-name> ;
DROP DATABASE SQL_CLASS ;
DROP USER SQL00 ;
Page 122 The SQL Quick Reference Guide
Simplicity by Design
Hashing Functions
Hashing functions allow users to see how data is distributed across the AMPs. Even data
distribution can be very important to Teradata because Teradata processes data in parallel.
HASHROW
The HASHROW function returns an 8- digit Hexidecimal number, which represents the
result of putting the <data-column-value> into Teradata’s Hash Formula.
SELECT HASHROW ( [ <data- column-value> [..., <data- column- value> … ] ] ) ;
SELECT HASHROW (Dept_No) from Department_Table ;
SELECT COUNT(*) / COUNT(DISTINCT( HASHROW (Student_Id)))
AS AVG_ROW_CNT
FROM Student_Table ;
A great demonstration of how to use this function powerfully is in the second example.
Hint - Man
The SQL Quick Reference Guide Page 123
The SQL Reference Guide
HASHBUCKET
This function produces the 16-bit binary Hash Bucket from the Data Distribution Hash
Map. The result will be between 0 and 65536. The input into this function is the 32- bit
Row Hash value, which can be produced using the HASHROW function.
SELECT HASHBUCKET ( [ <row- hash-value> ] ) ;
SELECT COUNT(*), HASHBUCKET (HASHROW(Student_Id))
AS Bucket FROM Student_Table ;
Group by Bucket
Issues: A 32-bit row hash value was not plugged into the function. 3794: The argument
type for the HASHBUCKET function is invalid.
HASHAMP
HASHAMP returns the identification number for the AMP in which the hash bucket
number points to. The correct application is using HASHBUCKET and HASHROW
together. A proper use of this function would be to place the Primary Index column in the
formula to discover the distribution among all the AMPs in the system.
SELECT HASHAMP ( <hash-bucket> ) ;
SELECT HASHAMP (HASHBUCKET(HASHROW(Student_Id))) FROM Student_Table ;
HASHBAKAMP
HASHBAKAMP identifies the FALLBACK AMP for a given hash bucket number. Just as HASHAMP a correct application is with HASHBUCKET and HASHROW.
SELECT HASHBAKAMP ( <hash-bucket> ) ;
SELECT HASHBAKAMP (HASHBUCKET(HASHROW(Student_Id))) FROM Student_Table ;
Page 124 The SQL Quick Reference Guide
Simplicity by Design
Temporary Tables
Teradata allows users to create Temporary tables with great ease. There are three types of
Temporary tables in Derived, Volatile, and Global Temporary tables. Each is described
below.
Derived Tables
Derived tables exist for the length of time it takes to run the query . The derived table
definition begins after the FROM clause in the statement and are automatically deleted at
query end. The space to material the rows comes from the users SPOOL space.
SELECT <column- name> [..., <column- name> ]
FROM ( SELECT <column-name> [ AS <alias-name> ][ … ,<column-name> ] FROM <table-name> )
<Derived-table-name> [ ( <alias-name> […,<alias-name> ] ) ;
SELECT *
FROM (SELECT MIN(SALARY) FROM Employee_Table) DT
(Min_Sal) ;
SELECT L_Name, F_Name, CC
FROM
(SELECT Last_Name, First_Name, Class_Code FROM
Student_TableWHERE Grade_Pt >= 3.0 ) DT (L_Name, F_Name, CC) ;
SELECT Dept_No, Dept_Name, AVG_Budget FROM
(SELECT AVG(Budget) FROM Department_Table) DT
(AVG_Budget), Department_Table
ORDER BY Dept_No ;
Once the result set is returned to the user, the derived table no longer exists. For more
detailed information and examples refer to Chapter 19, “Teradata SQL: Unleash the Power” by Larkins and Coffing.
Hint - Man
Issues: The derived table has not been given a name. 3707: Syntax error, expected something like a name between ‘)’ and ‘;’
Solutions: The only way to fix this is to place a ‘DT’ at the end of the derived tabledeclaration.
The SQL Quick Reference Guide Page 125
The SQL Reference Guide
Volatile Temporary Tables
Volatile Temporary Table, or Volatile Table, is available throughout the user session . A
user may log onto the Teradata system, create a Volatile Table and use it until logging off.
The LOG option allows a Volatile Table to use the Transient Journal during transactions.
The “ON COMMIT” clause gives two options to the user: whether to keep the rows in the
table after a transaction, or to have the rows deleted upon a comp lete transaction. The
default value is ON COMMIT DELETE ROWS, so users beware!
CREATE VOLATILE TABLE <table -name> [ , { LOG | NO LOG} ]
( <column-name> <data- type>
[ , <column-name> <data- type>[ , <column-name> <data- type> ] )
[ [ UNIQUE ] PRIMARY INDEX (<column-list>) ]
[ ON COMMIT { PRESERVE | DELETE } ROWS ] ;
CREATE VOLATILE TABLE Sales_Report_vt, LOG
(
Sale_Date DATE
,Sum_Sale DECIMAL(9,2) ,Avg_Sale DECIMAL(7,2)
,Max_Sale DECIMAL(7,2)
,Min_Sale DECIMAL(7,2) )
ON COMMIT PRESERVE ROWS ;
Now that the Volatile Table has been created, the table must be populated with an
INSERT/SELECT statement like the following:
INSERT INTO Sales_Report_vt SELECT Sale_Date
,SUM(Daily_Sales) ,AVG(Daily_Sales)
,MAX(Daily_Sales) ,MIN(Daily_Sales)
FROM Sales_Table
GROUP BY Sale_Date;
Imagine you have to get monthly information from a yearly table. A great idea is to create
a Volatile table. INSERT into the table the information from the specific month and then run your queries. In theory, they should run 12 times faster than if you queried the yearly
table. When you logoff the table is deleted. The space comes from the users spool space. Hint - Man
Page 126 The SQL Quick Reference Guide
Simplicity by Design
Global Temporary Tables
CREATE GLOBAL TEMPORARY TABLE
Global Temporary Tables, or Global Tables are a new breed of temporary table that is very
powerful. The definition of the table is stored in the Data Dictionary and that allows for
multiple users to have access to the table definition. However, each user may put different data into their own copy of the table definition.
CREATE GLOBAL TEMPORARY TABLE <table -name> [ { LOG | NO LOG} ]
( <column-name> <data- type>
[ , <column-name> <data- type> ]
[ [ UNIQUE ] PRIMARY INDEX (<column-list>) ]
[ ON COMMIT { PRESERVE | DELETE } ROWS ] ;
CREATE GLOBAL TEMPORARY TABLE Sales_Report_gt, LOG(
Sale_Date DATE
,Sum_Sale DECIMAL(9,2) ,Avg_Sale DECIMAL(7,2) ,Max_Sale DECIMAL(7,2)
,Min_Sale DECIMAL(7,2)
)PRIMARY INDEX(Sale_Date) ON COMMIT PRESERVE ROWS ;
If a user desires to remove the table definition from the Data Dictionary the user must
implement a DROP TABLE command. The LOG option allows a Temp Table to use the Transient Journal during transactions.
Hint - Man
To materialize a copy of the Global Temp definition and populate it perform the
following syntax:
INSERT INTO Sales_Report_gt SELECT Sale_Date
,SUM(Daily_Sales),AVG(Daily_Sales),MAX(Daily_Sales)
,MIN(Daily_Sales)FROM Sales_Table
GROUP BY Sale_Date ;
The SQL Quick Reference Guide Page 127
The SQL Reference Guide
DROP TEMPORARY TABLE
This syntax removes any temporary table . However it will not drop the Global Temporary table definitionfrom the Data Dictionary.
DROP TEMPORARY TABLE <table -name> ;
DROP TEMPORARY TABLE Sales_Report_vt ;
Issues: The temporary table does not exist in the user session.
3807: Table/view/trigger ‘<table-name>’ does not exist.
Page 128 The SQL Quick Reference Guide
Simplicity by Design
Triggers
When dealing with triggers, a user must understand the difference between the two types of
triggers: Row Triggers and Statement Triggers. Both are mutually exclusive, meaning that
a created trigger can either be a Row Trigger type or a Statement Trigger type but not both. A Row Trigger fires off for each row that is affected by the triggering statement. A
Statement Trigger fires off only once per triggering statement. Triggers are most widely
used as a means for Referential Integrity.
BEFORE Triggers
In this scenario, the <TRIGGERED ACTION> is being performed before the specific
<TRIGGERING ACTION>.
CREATE TRIGGER <Trigger-name>
BEFORE
<TRIGGERING ACTION > {INSERT | UPDATE | DELETE |
INSERT/SELECT}
[ OF (<column-name>, … ) ] ON <subject- table>
REFERENCING OLD_TABLE AS <before -image>
NEW_TABLE AS <after-image>
{ FOR EACH STATEMENT | FOR EACH ROW }
[ WHEN ( optional condition ) ]
( <TRIGGERED ACTION> { INSERT | IN SERT/SELECT | UPDATE | DELETE |
ABORT/ROLLBACK | EXEC } ; )
CREATE TRIGGER CUST_ORD_TRIG
BEFORE INSERT ON Order_Table
REFERENCING NEW AS ord_row
FOR EACH ROWWHEN (ord_row.customer_number NOT IN
(SELECT customer_number FROM Customer_Table))(INSERT INTO Customer_Table
VALUES (ord_row.customer_number, ‘Customer Name’, ‘999-9999’););
A good example would be when inserting a new order into the Order_Table, a trigger
could be created to ensure the Customer who is making the order exists in the
Customer_Table. If not, then insert a row into the Customer_Table BEFORE inserting a row into the Order_Table. The above example illustrates this scenario. Hint - Man
Issues: There is not a FOR EACH ROW or FOR EACH STATEMENT clause present in
the code. 5423: This trigger contains an invalid REFERENCING clause.
Solutions: Fixing this problem is as simple as deciding whether to use the ‘FOR EACH
ROW’ or the ‘FOR EACH STATEMENT’, and then adding in the statement after the ‘BEFORE INSERT ON <table -name>’ command.
The SQL Quick Reference Guide Page 129
The SQL Reference Guide
AFTER Triggers
The AFTER Trigger, causes the <TRIGGERED ACTION> to fire afterthe<TRIGGERING ACTION> is performed. The importing thing to remember is that an
AFTER Trigger is helpful for making changes on one table depending on the modifications
of another table.
CREATE TRIGGER <Trigger- name>
AFTER<TRIGGERING ACTION > {INSERT | UPDATE | DELETE | INSERT/SELECT}
[ OF (<column- name>, … ) ] ON <subject- table>
REFERENCING OLD_TABLE AS <before- image>
NEW_TABLE AS <after- image>
{ FOR EACH STATEMENT | FOR EACH ROW }
[ WHEN ( optional condition ) ]
( <TRIGGERED ACTION> { INSERT | INSERT/SELECT | UPDATE | DELETE |
ABORT/ROLLBACK | EXEC } ; ) ;
CREATE TRIGGER Salary_Fraud_Trig
AFTER UPDATE OF (salary) ON Employee_Table
REFERENCING OLD AS before_row
NEW AS after_row
FOR EACH ROW
WHEN ((after_row.salary – before_row) / before_row.salary > .10 )
(INSERT INTO Salary_Fraud VALUES
(after_row.employee_no, before_row.salary, after_row.salary, DATE) ;) ;
A good application would be a table that is updated if any employee’s salary is raised
more than 10%. This would be useful to detect any type of salary fraud within the company. The above example reflects this scenario.
Hint - Man
Page 130 The SQL Quick Reference Guide
Simplicity by Design
INSTEAD OF Triggers
This style of trigger is fairly direct. It tells Teradata to do the <TRIGGERED ACTION> in
place of the <TRIGGERING ACTION>.
CREATE TRIGGER <Trigger- name>
INSTEAD OF
<TRIGGERING ACTION > {INSERT | UPDATE | DELETE | INSERT/SELECT}
[ OF (<column- name>, … ) ] ON <subject- table>
REFERENCING OLD_TABLE AS <before- image>
NEW_TABLE AS <after- image>
{ FOR EACH STATEMENT | FOR EACH ROW }
[ WHEN ( optional condition ) ]
( <TRIGGERED ACTION> { INSERT | INSERT/SELECT | UPDATE | DELETE |
ABORT/ROLLBACK | EXEC } ; ) ;
CREATE TRIGGER New_Student_Trig
INSTEAD OF
INSERT ON Student_Table
REFERENCING NEW AS newstu
FOR EACH STATEMENT
(INSERT INTO New_Student_Table
Select * from newstu; ) ;
A Database Administrator may want to keep track of and maintain any new rows added
into the Student_Table. What this means is that the “INSTEAD OF Trigger”, will place any new rows inserted into the Student_Table in a separate table. Then at a later time the new rows can be placed into the Student _Table. The example of this scenario follows. Hint - Man
The SQL Quick Reference Guide Page 131
The SQL Reference Guide
Sequencing Triggers
The idea behind sequencing triggers is to set an order of operations for triggers that are
set off by the same event. This is to allow the Database Administrator flexibility to place a
preference on one trigger over another one. A User may number their triggers (1 through
32,767). Order 1 triggers will be kicked off before Order 2 triggers, etc .
CREATE TRIGGER <Trigger- name>
{BEFORE | AFTER | INSTEAD OF}
[ ORDER <sequence -number> ]
<TRIGGERING ACTION > {INSERT | UPDATE | DELETE | INSERT/SELECT}
[ OF (<column- name>, … ) ] ON <subject- table>
REFERENCING OLD_TABLE AS <before- image>
NEW_TABLE AS <after- image>
FOR EACH STATEMENT[ WHEN ( optional condition ) ]
( <TRIGGERED ACTION> { INSERT | INSERT/SELECT | UPDATE | DELETE | ABORT/ROLLBACK | EXEC } ; ) ;
CREATE TRIGGER Save_GPA_Trig
BEFORE UPDATE ON Student_Table ORDER 100REFERENCING NEW AS new_row
OLD AS old_row
FOR EACH ROW
WHEN (new_row.Grade_pt <> old_row.Grade_pt) (INSERT INTO Save_GPA_Table VALUES
(old_row.Student_Id, old_row.Grade_pt) ; );
CREATE TRIGGER GPA_Fraud_Trig
BEFORE UPDATE ON Student_Table ORDER 150REFERENCING NEW AS new_row
OLD AS old_row
FOR EACH ROW
WHEN(new_row.Grade_pt <> old_row.Grade_pt)
(INSERT INTO GPA_Fraud_Table VALUES
(old_row.Student_Id, old_row.Grade_pt, new_row.Grade_pt); );
Issues: 5432: A trigger Order value must be within a range of 0 to 32767.
Ordering triggers is important, but you need to keep the range in mind.
Solutions: Locate the ‘ORDER’ statement and replace the <sequence-number> with a number
between 0 and 32767.
Page 132 The SQL Quick Reference Guide
Simplicity by Design
APPENDIX A: Current Reserved Words
The following list indicates all of the Teradata release V2R4.1 reserved words. These are
words that need to be avoided when creating database objects. If they are used for anything
other than their reserved meaning, they will need to be enclosed in double quotes (“).
- A -
ABORT ABORTSESSION ABS ACCESS_LOCK
ACCOUNT ADD ADD_MONTHS AFTER
ALL ALTER AMP ANDANSIDATE ANY AS ASCAT ATOMI C AVE AVERAGE
AVG
- B -
BEFORE BEGIN BETWEEN BOTH
BT BUT BY BYTE
BYTEINT BYTES
- C -
CALL CASE CASESPECIFIC CAST
CD CHAR CHARACTER CHARACTERS
CHARACTER_LENGTH CHARS CHAR2HEXINT
CHAR_LENGTH CHECK CHECKPOINT CLUSTER
CM COALESCE COLLATION COLLECTCOLUMN
COMMENT COMMIT COMPRESS CONSTRAINTCONTINUE CONVERT_TABLE_HEADER CORR OLAPCOUNT COVAR_POP CREATE CROSS
CS CSUM CT CURRENTCURRENT_DATE CURRENT_TIME CURRENT_TIMESTAMP
CURSOR CV
- D -
DATABASE DATABLOCKSIZE DATE DATEFORM
DAY DEC DECIMAL DECLARE
DEFAULT DEL DELETE DESC
DIAGNOSTIC DISABLED DISTINCT DO
DOUBLE DROP DUAL DUMP
- E -
EACH ECHO ELSE ELSEIF
ENABLED END EQ ERRORERRORFILES ERRORTABLES ESCAPE ET
EXCEPT EXEC EXECUTE EXISTS
EXIT EXP EXPLAIN EXTRACT
The SQL Quick Reference Guide Page 133
The SQL Reference Guide
Current Reserved Words (continued)
- F -
FALLBACK FASTEXPORT FLOAT FOR
FOREIGN FORMAT FREESPACE FROM
FULL
- G -
GCOUNT OLAP GE GIVE GRANT
GRAPHIC GROUP GSUM GT
- H -
HANDLER HASH HASHAMP HASHBAKAMP
HASHBUCKET HASHROW HAVING HELP
HOUR
- I -
IF IMMEDIATE IN INCONSISTENT
INDEX INITIATE INNER INOUT
INS INSERT INSTEAD INT
INTEGER INTEGERDATE INTERSECT INTERVAL
INTO IS ITERATE
- J-
JOIN JOURNAL
- K -
KEY KURTOSIS
- L -
LE LEADING LEAVE LEFT
LIKE LN LOADING LOCAL
LOCK LOCKING LOG LOGGING
LOGON LONG LOOP LOWER
LT
- M -
MACRO MAVG MAX MAXIMUM
MCHARACTERS MDIFF MIN MINDEX
MINIMUM MINUS MINUTE MLINREG
MLOAD MOD MODE MODIFY
MONITOR MONRESOURCE MONSESSION MONTH
MSUBSTR MSUM MULTISET
Page 134 The SQL Quick Reference Guide
Simplicity by Design
Current Reserved Words (continued)
- N -
NAMED NATURAL NE NEW
NEW_TABLE NO NOT NOWAIT
NULL NULLIF NULLIFZERO NUMERIC
- O -
OCTET_LENGTH OF OFF OLD
OLD_TABLE ON OPTION OR
ORDER OUT OUTER OVER
OVERLAPS OVERRIDE
- P -
PASSWORD PERCENT PERM PERMANENTPOSITION PRECISION PRESERVE PRIMARY
PRIVILEGES PROCEDURE PROTECTION PUBLIC
- Q -
QUALIFY QUANTILE
- R -
RANDOM RANK REAL REFERENCESREFERENCING REGR_INTERCEPT REGR_SLOPE RELEASE
RENAME REPLACE REPLICATION REPOVERRIDE
REQUEST RESTART RESTORE RESUME
RET RETRIEVE REVALIDATE REVOKE
RIGHT RIGHTS ROLE ROLLBACK
ROLLFORWARD ROW ROWID ROWS
- S -
SAMPLE SAMPLEID SECOND SEL
SELECT SESSION SET SETRESRATE
SETSESSRATE SHOW SKEW SMALLINT
SOME SPOOL SQLEXCEPTION SQRT
SS STARTUP STATEMENT STATISTICS
STDDEV_POP STDDEV_SAMP STRING_CS SUBSCRIBER
SUBSTR SUBSTRING SUM SUSPEND
The SQL Quick Reference Guide Page 135
The SQL Reference Guide
Current Reserved Words (continued)
- T -
TABLE TBL_CS TEMPORARY TERMINATE
THEN TIME TIMESTAMP TIMEZONE_HOUR
TIMEZONE_MINUTE TITLE TO
TRAILING TRANSACTION TRANSLATE TRANSLATE_CHK
TRIGGER TRIM TYPE
- U -
UC UNDEFINED UNDO UNION
UNIQUE UPD UPDATE UPPER
UPPERCASE USER USING
- V -
VALUE VALUES VARBYTE VARCHAR
VARGRAPHIC VARYING VAR_ POP VAR_SAMP
VIEW VOLATILE
- W -
WHEN WHERE WHILE WITH
WORK
- Y-
YEAR
- Z -
ZEROIFNULL ZONE
A
Page 136 The SQL Quick Reference Guide
Simplicity by Design
Future Reserved Words
The following words are reserved for the future:
- A -
ALIAS AUTHORIZATION
- D -
DESCRIPTOR
- G -
GO GOTO
- I -
INDICATOR
- P -
PRIVATE
- W -
WAIT
The SQL Quick Reference Guide Page 137
The SQL Reference Guide
APPENDIX B: Data Control Language (DCL)
Data Control Language (DCL) Statements
Data Control Language (DCL) is normally used by the database administrator (DBA).
These statements control the ownership and access by users to the database objects.
There are three DCL statements that will be covered:
• GRANT – gives permission to perform a specific operation
• REVOKE – takes away permission to perform a specific operation
• GIVE - transfers ownership of a database or user
Privileges
Access rights, often referred to as privileges, define what a user can and cannot do with a
particular object.
The privileges are defined in the following categories:
• CREATE - make a new object
• DROP - remove an object
• CHECKPOINT - mark rows as valid
• DUMP - backup or archive to the checkpoint
• RESTORE - return to disk from an archive
• EXECUTE - run a macro or stored procedure
• REFERENCES - table or column level access
• INDEX - secondary index operations
• DELETE - remove rows from a table or view
• INSERT - build new rows in a table or view
• SELECT - read rows from a table or view
• UPDATE - modify columns or rows in a table or view
The database objects that can be allowed with the CREATE / DROP:
• DATABASE / USER
• TRIGGER
• PROCEDURE
• MACRO
• TABLE
• VIEW
Page 138 The SQL Quick Reference Guide
Simplicity by Design
GRANT Statement
Compatibility: ANSI
The GRANT statement is used to explicitly provide one or more privileges to one or more
users. All granted privileges are stored in the Data Dictionary.
The GRANT syntax for SQL privileges:
GRANT [ { ALL | ALL BUT } ] <privilege> […,<privilege>]
ON [ PROCEDURE ] [<database-name>.]<object-name>
TO [ ALL ] { <user-name> […,<user-name> ] | PUBLIC }
[ WITH GRANT OPTION ] ;
It is not a good idea to use PUBLIC in Teradata due to the larger number of users. The
ALL causes the privilege(s) to cascade downward to all dependents of the user specified.
Hint - Man
The GRANT syntax for LOGON :
GRANT LOGON { ALL | <host-id> […,<host-id>] }
TO { <database-name> […,<database-name> ] | AS DEFAULT }[ WITH NULL PASSWORD ] ;
The GRANT syntax to provide MONITOR operations:
GRANT <monitor-privilege> […,<monitor_privilege>]MONITOR [ {PRIVILEGES | BUT NOT <monitor-privilege> […,<monitor-privilege>]} ]TO [ ALL ] { <user-name> […,<user-name> ] | PUBLIC }
[ WITH GRANT OPTION ] ;
The monitor privileges:
• MONRESOURCE
• MONSESSION
• ABORTSESSION
• SETRESRATE
• SETSESSRATE
The SQL Quick Reference Guide Page 139
The SQL Reference Guide
REVOKE Statement
Compatibility: ANSI
The REVOKE statement is used to explicitly remove one or more privileges from one or
more users. All granted privileges are stored in the Data Dictionary.
THE REVOKE syntax for SQL privileges:
REVOKE [GRANT OPTION FOR ] [ { ALL | ALL BUT } ] <privilege> […,<privilege>]
ON [ PROCEDURE ] [<database-name>.]<object-name>
{ TO | FROM } [ ALL ] { <user-name> […,<user-name> ] | PUBLIC } ;
It is not a good idea to use PUBLIC in Teradata due to the larger number of users. The
ALL causes the privilege(s) to cascade downward to all dependents of the user specified.
Hint - Man
The REVOKE syntax forLOGON :
REVOKE LOGON { ALL | <host-id> […,<host-id>] }
{ { TO | FROM } { <database-name> […,<database-name> ] | AS DEFAULT } ;
The REVOKE syntax to provide MONITOR operations:
REVOKE [GRANT OPTION FOR ] <monitor-privilege> […,<monitor-privilege>]
MONITOR [ {PRIVILEGES | BUT NOT <monitor-privilege> […,<monitor-privilege>]} ] { TO | FROM } [ ALL ] { <user-name> […,<user-name> ] | PUBLIC } ;
The monitor privileges:
• MONRESOURCE
• MONSESSION
• ABORTSESSION
• SETRESRATE
• SETSESSRATE
Page 140 The SQL Quick Reference Guide
Simplicity by Design
GIVE Statement
Compatibility: Teradata
The GIVE statement is used to transfer the ownership of a database or user to another
database or user. This transfer reallocates all space and privileges with it.
The GIVE syntax:
GIVE { <database-name> | <user-name> }
TO { <database-name> | <user-name> } ;
The SQL Quick Reference Guide Page 141
The SQL Reference Guide
APPENDIX C: Data Types and Format Symbols
The following table is a chart of all the ANSI Standard Data Types that Teradata supports.
Data Type Description Data Value Range
INTEGER Signed whole number -2,147,483,648 to
2,147,483,647
SMALLINT Signed smaller whole -32,768 to 32,767
number
DECIMAL (X,Y) Signed decimal number Largest value DEC(18,0)
Where: X=1 thru 18, total 18 digits on either side of the Smallest value DEC(18,18)
number of digits in the decimal point number And Y=0 thru 18 digits to
the right of the decimal
NUMERIC (X,Y) Synonym for DECIMAL Same as DECIMAL
Same as DECIMAL
FLOAT Floating Point Format <value>x10 to <value>x10 3 0 7 -
(IEEE) 3 0 8
REAL Stored internally as FLOAT
PRECISION Stored internally as FLOAT
DOUBLE PRECISION Stored internally as FLOAT
CHARACTER (X) Fixed length character 1 to 64,000 characters long,
CHAR (X) string, 1 byte of storage per pads to length with space
Where: X=1 thru 64000 character,
VARCHAR (X) Variable length character 1 to 64,000 characters as a
CHARACTER string, 1 byte of storage per maximum. The system only
VARYING (X) character, plus 2 bytes to stores the characters presented
CHAR VARYING (X) record length of actual data to it.
Where: X=1 thru 64000
DATE Signed internal Currently to the year 3500 as a
representation of positive number and back into
YYYMMDD (YYY AD years as a negative
represents the number of number.
years from 1900, i.e. 100 for Year 2000)
TIME Identifies a field as a TIME
value with Hour, Minutes
and Seconds
TIMESTAMP Identifies a field as a
TIMESTAMP value with
Year, Month, Day, Hour, Minute, and Seconds
Page 142 The SQL Quick Reference Guide
Simplicity by Design
Teradata also has its own data types that are acknowledged as Teradata Extensions:
Data Type Description Data Value Range
BYTEINT Signed whole number -128 to 127
BYTE (X) Binary 1 to 64,000 bytes
Where: X=1 thru 64000
VARBYTE (X) Variable length binary 1 to 64,000 bytes
Where: X=1 thru 64000
LONG VARCHAR Variable length string 64,000 characters (maximum
data length) The system
only stores the characters
provided, not trailing
spaces.)
GRAPHIC (X) Fixed length string of 16-bit 1 to 32,000 KANJI
Where: X=1 thru 32000 bytes (2 bytes per character) characters
VARGRAPHIC (X) Variable length string of 16- 1 to 32,000 characters as a
Where: X=1 thru 32000 bit bytes maximum. The system only
stores characters provided.
Format Symbols
Forma tting symbols are very powerful. These symbols allow the user to control the way
data can be inserted into a row and displayed in the result set. It provides for more
predictable result sets.
Be sure to keep in mind that the ODBC will ignore formatting, unless you trick it. To see
true formatting, the user should use BTEQ.
Hint - Man
Basic Numeric and Character Data Formatting Symbols
Symbol Mask character and how used
X or x Character data. Each X represents one character. Can repeat value – i.e.
XXXXX or X(5). 9 Decimal digit. Holds place for numeric digit for a display 0 through 9. All
leading zeroes are shown if the format mask is longer than the data value. Can
repeat value – i.e. 99999 or 9(5).
V or v Implied decimal point. Aligns data on a decimal value. Primarily used onimported data without actual decimal point.
E or e Exponential. Aligns the end of the mantissa and the beginning of the exponent.
G or g Graphic data. Each G represents one logical (double byte - KANJI or Katakana)
character. Can repeat value – i.e. GGGGG or G(5).
The SQL Quick Reference Guide Page 143
The SQL Reference Guide
Advanced Numeric and Character Formatting Symbols
Symbol Mask character and how used
$ Fixed or floating dollar sign. Inserts a $ or leaves spaces and moves (floats)
over to the first character of a currency value. With the proper keyboard, additional currency signs are available: Cent, Pound and Yen.
, Comma. Inserted where appears in format mask. Used primarily to make large
numbers easier to read. . Period. Primary use to align decimal point position. Also used for: dates and
comma in some currencies. - Dash character. Inserted where appears in format mask. Used primarily for
dates and negative numeric values. Also used for: phone numbers, zip codes, and social security (USA).
/ Slash character. Inserted where appears in format mask. Used primarily for
dates. % Percent character. Inserted where appears in format mask. Used primarily for
display of percentage – i.e. 99% vs. .99
Z or z Zero-suppressed decimal digit. Holds place for numeric digit displays 1through 9 and 0, when significant. All leading zeroes (insignificant) are shown
as space since their presence does not change the value of the number being
displayed.
B or b Blank data. Insert a space where appears in format mask.
SELECT ‘ABCDE’ (FORMAT ‘XxX’) AS Fmt_Shorter
,2014859999 (FORMAT ‘999-999-9999’) AS Fmt_Phone
,1021.53 (FORMAT ‘ZZZZZZ9.9999’) AS Z_press
,991001 (FORMAT ‘$$$$,$$$.99’) AS Fmt_Pay ;
Page 144 The SQL Quick Reference Guide
Simplicity by Design
In addition to have the abilit y to format Numeric and Character Data Types, a user may
also format Dates.
Date Formatting Symbols
Symbol Mask character and how used (not case specific)
M or m Month. Allows month to be displayed any where in the date display. When
‘MM’ is specified, the numeric (01-12) value is available. When ‘MMM’ is
specified, the three character (JAN-DEC) value is available.
D or d Day. Allows day to be displayed any where in the date display. When ‘DD’ is
specified, the numeric (01-31) value is available. When ‘DDD’ is specified, the three-digit day of the year (001-366) value is available.
Y or y Year. Allows day to be displayed any where in the date display. The normal‘YY’ has been used for many years for the 20 century with the 19YY th
assumed. However, since we have moved into the 21 century, it is st
recommended that the ‘YYYY’ be used.
SELECT
991001(date) (FORMAT ‘Yyddd’) AS Fmt_Julian
,991001(date) (FORMAT ‘YYYY-mm-dd’) AS Fmt_ANSI
,9991001(date) (FORMAT ‘yy/mm/dd’) AS Fmt_Teradata ;
The SQL Quick Reference Guide Page 145
The SQL Reference Guide
APPENDIX D: Mathematical Functions
This is a chart of those Teradata arithmetic, trigonometric and hyperbolic math functions:
Operator Operation performed Modulo returns the remainder from a division (1 mod 2 derives 1, as the MOD x
remainder of division, 2 goes into 1, 0 times with a remainder of 1. Then, 2
mod 10 derives 2, 10 goes into 2, 0 times with a remainder of 2). MOD always
returns 0 thru x-1. As such, MOD 2 returns 0 for even numbers and 1 for odd;
MOD 7 can be used to determine the day of the week; and MOD 10, MOD 100, MOD 1000, etc can be used to shift the decimal of any number to the left by the
number of zeroes in the MOD operator.
Absolute value, the absolute value of a negative number is the same number as a ABS( x )
positive x. (ABS(10-12) = 2) Exponentiation, e raised to a power, ( EXP(10) derives 2.20264657948067E004 EXP( x )
)
Logarithm calculus function, ( LOG(10) derives the value LOG(x )
1.0000000000000E000 )
Natural logarithm, ( LN(10) derives the value 2.30258509299405E000 ) LN(x )
Square root, ( SQRT(10) derives the value 3.16227766016838E000) SQRT( x )
Takes an angle in radians (x ) and returns the ratio of two sides of a right triangle. COS( x )
The ratio is the length of the side adjacent to the angle divided by the length of the hypotenuse. The result lies in the range -1 to 1, inclusive where x is any
valid number expression that expresses an angle in radians. Takes an angle in radians (x ) and returns the ratio of two sides of a right triangle. SIN( x )
The ratio is the length of the side opposite to the angle divided by the length of
the hypotenuse. The result lies in the range -1 to 1, inclusive where x is any
valid number expression that expresses an angle in radians.
Takes an angle in radians (x ) and returns the ratio of two sides of a right triangle. TAN( x )
The ratio is the length of the side opposite to the angle divided by the length of the side adjacent to the angle where x is any valid number expression that
expresses an angle in radians. Returns the arccosine of x. The arccosine is the angle whose cosine is x where xACOS( x )
is the cosine of the returned angle. The values of x must be between -1 and 1, inclusive. The returned angle is in the range 0 to ?? radians, inclusive.
Returns the arcsine of ( x) . The arcsine is the angle whose sine is x where x is the ASIN( x )
sine of the returned angle. The values of x must be between -1 and 1, inclusive. The returned angle is in the range ? /2 to ?? /2 radians, inclusive.
Returns the arctangent of ( x) . The arctangent is the angle whose tangent is ar g. ATAN( x )
The returned angle is in the range ? /2 to ?? /2 radians, inclusive.
Returns the arctangent of the specified (x,y) coordinates. The arctangent is the ATAN2
angle from the x-axis to a line contained the origin(0,0) and a point with ( x,y )
coordinates (x,y). The returned angle is between ? and ?? radians, excluding ? . A positive result
represents a counterclockwise angle from the x-axis where a negative result represents a clockwise angle. The ATAN2(x,y) equals ATAN(y/x), except that x
can be 0 in ATAN2(x,y) and x cannot be 0 in ATAN(y/x) since this will result in
a divide by zero error. If both x and y are 0, an error is returned.
Returns the hyperbolic cosine of ( x) where x is any real number. COSH( x )
Returns the hyperbolic sine of ( x) where x is any real number. SINH( x )
Page 146 The SQL Quick Reference Guide
Simplicity by Design
Returns the hyperbolic tangent of ( x) where arg is any real number. TANH( x )
Returns the inverse hyperbolic cosine of ( x) . The inverse hyperbolic cosine is the ACOSH( x )
value whose hyperbolic cosine is a number so that x is any real number equal to,
or greater than, 1.
Returns the inverse hyperbolic sine of ( x) . The inverse hyperbolic sine is the ASINH( x )
value whose hyperbolic sine is a number so that x is any real number.
Returns the inverse hyperbolic tangent of ( x) . The inverse hyperbolic tangent is ATANH( x )
the value whose hyperbolic tangent is a number so that x is any real number
between 1 and -1, excluding 1 and -1).
APPENDIX E: Qualifying and Table Aliasing
This section provides techniques to specifically reference table and columns throughout all
databases and to temporarily rename tables with an alias name.
Qualifying Column Names
3- level reference: <database- name>.<table - name>.<column- name>
2- level reference: <database- name>.<table - name>
2- level reference: <table -name>.<column-name>
SELECT SQL_CLASS.Employee_Table.Dept_No
FROM Employee_Table ;
SELECT *
FROM SQL_CLASS.Employee_Table ;
SELECT Student_Table.Student_Id
FROM Student_Table
INNER JOIN Student_Course_Table
ON Student_Table.Student_Id= Student_Course_Table.Student_Id ;
The SQL Quick Reference Guide Page 147
The SQL Reference Guide
Creating an Alias for a Table
Once an alias is established for a table, the alias must be used or the real table will also be
included in the query and possibly cause a product join.
SELECT <column- list>
FROM <table- name> AS <table-alias-name> ;
SELECT *
FROM Customer_Table as CUST ;
SELECT CUST.Customer_Name
FROM Customer_Table as CUST ;
SELECT STU.Student_Id, STU_COUR.Course_Id
FROM Student_Table as STU
INNER JOIN Student_Course_Table as STU_COURON STU.Student_Id
= STU_COUR.Student_Id ;
Alternative Syntax:
SELECT <column- list>
FROM <table- name> <table-alias-name> ;
SELECT * FROM Customer_Table CUST ;
SELECT CUST.Customer_Name
FROM Customer_Table CUST ;
Page 148 The SQL Quick Reference Guide
Simplicity by Design
APPENDIX F: Stored Procedure Syntax
Stored Procedures are a relatively new concept for Teradata. Despite being new, they are
quite powerful, flexible, and easy to write. This appendix is a focus on the Create Syntax,
and all the possible Stored Procedure Language (SPL) options.
CREATE PROCEDURE [<database- name>.]<procedure-name>
( [ <parameter- list> ] )
<procedure- body> ;
This is the simplest syntax for a stored procedure with <procedure-body> including loops,
if statements, and other SPL choices.
Hint - Man
The following is a list of all the SPL features that Teradata supports:
BEGIN / END Establishes the range of the <procedure-body>.
CALL Executes one procedure from the procedure being run.
DECLARE Introduces local variables or handlers to the procedure.
FOR / END FOR Serves as a FOR Loop, for each ro w returned from Teradata.
IF / END IF Provides a conditional test for a given variable.
ITERATE Terminates the remaining steps in any loop, returning back to
corresponding Label.
LEAVE Used to exit a loop prematurely.
LOOP / END LOOP Defines the length of the loop.
PRINT Used for testing and debugging of a procedure.
SET Establishes a value to a variable in the procedure.
WHILE / END WHILE Loop with a conditional test before the code in the loop.
For further information about Stored Procedures and SPL, please refer to “Teradata SQL:
Unleash the Power”, Chapter 21. Detailed information is included on each SPL feature, and
the whole concept of Stored Procedures.
The SQL Quick Reference Guide Page 149
Index of Contents
Correlated Subquery i, 36 A COS( X ) 146
COSH( X ) 146 Abort i, 100
Count (Count) 31 ABS( X ) 146
Create ACOS( X ) 146
Database i, 120 ACOSH( X ) 147
Global Temporary Table 127Add_Months i, 48
Macro i, 93 After Journal 109, 110, 111, 113, 120, Table i, 105, 112 121
User i, 121 After Triggers i, 130
View i, 89 Aliasing Columns i, 13
Cross Join i, 45 Alter Table i, 113
Current Reserved Words 134, 135, 136 And/Or 4, 5
Current_Time 50, 133 Ansi Mode 25, 98, 99, 107
Current_Timestamp 50, 133 AS i, 13, 144, 145
ASIN( X ) 146 D ASINH( X ) 147
ATAN( X ) 146 Data Control Language (Dcl) 138 ATAN2 ( X,Y ) 146 Data Interrogation ATANH( X ) 147 Case i, 51, 85, 86, 87, 88, 133Average (Avg) i Coalesce i, 84, 133
Nullif iii, 82, 135 B Nullifzero iii, 81, 135
Zeroifnull 4, 83, 136 Befor e Journal 109, 110, 111, 113, 120, Data Manipulation 121
Delete ii, 77, 78, 93, 95, 126, 127, 129, Before Triggers i, 129
130, 131, 132, 133, 138 Begin / End 149
Insert ii, 72, 73, 74, 79, 80, 93, 95, 96, Between i, 11, 86, 133
97, 100, 101, 126, 127, 129, 130, Byte (X) 143
131, 132, 134, 138 Byteint 51, 133, 143
Insert / Select ii, 74
C Update iii, 4, 75, 76, 79, 80, 93, 95, 99,
100, 129, 130, 131, 132, 136, 138 Calendar_Date 51
Upsert iii, 4, 79, 80 Call 133, 149 Data Types Cartesian Product Join i, 42, 45
Byte (X) 143Case i, 51, 85, 86, 87, 88, 133 Byteint 51, 133, 143
Casespecific i, 24, 25, 110, 133 Character (X) 142
Character (X) 142 Date ii, 4, 47, 51, 110, 126, 127, 130, Character Set 110
133, 142 Characters 52 Decimal (X,Y) 142 Coalesce i, 84, 133 Double Precision 142
Collect Statistics i, 118 Float 134, 142
Commit Work i, 100 Graphic (X) 143 Compress 110, 133
Compress Null 110
Integer 51, 93, 105, 106, 107, 108, View ii, 90
109, 110, 111, 134, 142 Drop Statistics ii, 119
Long Varchar 143 Dual After Journal 109
Numeric (X,Y) 142 Dual Before Journa l 109
Precision 135, 142
E Real 135, 142
Smallint 51, 93, 135, 142 Except ii, 34, 37, 67, 70, 71, 133 Time 4, 50, 110, 133, 136, 142 Execute Macro ii, 94 Timestamp 4, 50, 133, 136, 142 Exists 37 Varbyte (X) 143 EXP( X ) 146 Varchar (X) Character 142 Explain ii, 19, 133 Vargraphic (X) 143 Extract ii, 49
Database
Create i, 120 F
Drop 122 Fallback ii, 108, 109, 110, 111, 117, 120,
Give 141 121, 124, 134 Grant 139
Float 134, 142 Revoke 140 For / End For 149 DATE ii, 4, 47, 51, 110, 126, 127, 130, Format ii, 22, 110, 134, 144, 145
133, 142 Format Symbols 142, 143
Integerdate 46 Function Date Functions
Characters 52 Add_Months i, 48 Cumulative Sum (Csum) 59 Extract ii, 49 Hashing ii, 123
Day_Of_Calendar 51 Index 55
Day_Of_Month 51 Moving Average (Mavg) 61Day_Of_Week 51 Moving Difference (Mdiff) 62 Day_Of_Year 51 Moving Sum (Msum) 60 Decimal (X,Y) 142 Position 55
Declare 133, 149 Quantile 63
Default Date 110 Random 66 Default Null 110, 111 Rank 64 Default Time 110 Substring And Substr 54 Default User 110 Trim 53
Default Value 110 Future Reserved Words 137
Delete ii, 77, 78, 93, 95, 126, 127, 129, 130, 131, 132, 133, 138
G Derived Table ii, 125
Give 141 Distinct ii, 16, 123, 133
Global Temporary Table ii, 127 Double Precision 142
Create 127Drop
Grant 139 Database 122
Graphic (X) 143 Macro ii, 95
Table ii, 114
H Temporary Table 128
User 122 Hashamp ii, 124, 134
Hashbakamp ii, 124, 134 JHashbucket ii, 124, 134
Join iii, 38 Hashing ii, 123
Cartesian Product Join i, 42, 45 Hashrow ii, 123, 124, 134
Cross Join i, 45 Having ii, 32
Inner Join 40 Help 2, 3, 17, 18, 21, 72, 73, 77, 81, 82,
Outer Join i, 43 83, 90, 113, 114, 115, 119, 134
Join Index iii, 117 Column 17
Database 17 L Index 17
Leave 134, 149 Macro 17 Like iii, 12 Procedure 17 LN( X ) 146 Session 17 Locking Statistics 17
Database 97Table 17 Modifiers iii, 96 Trigger 17 Table 97 User 17 View 97 View 17
Locking Modifiers 96 Volatile Table 17 LOG( X ) 146 Horizontal Reporting ii, 87 Long Varchar 143
Loop / End Loop 149 I
Lower And Upper 26 If / End If 149
In ii, 9 M Index Function 55
Macro Indexes Create Macro i, 93 Non- Unique Primary Index 105 Drop Macro ii, 95Non- Unique Primary Index (NUPI) Execute Macro ii, 94105 Replace Macro 4, 95 Primary Index iii, 105, 106, 124
Math Functions Secondary 116 ABS( X ) 146 Secondary Index 4, 116 ACOS( X ) 146 Unique Primary Index 105 ACOSH( X ) 147 Inner Join 40 ASIN( X ) 146 Insert ii, 72, 73, 74, 79, 80, 93, 95, 96, ASINH( X ) 147 97, 100, 101, 126, 127, 129, 130, 131, ATAN( X ) 146 132, 134, 138 ATAN2 ( X,Y ) 146 Insert / Select ii, 74 ATANH(X ) 147 Instead Of Triggers ii, 131 Begin / End 149Integer 51, 93, 105, 106, 107, 108, 109, Call 133, 149110, 111, 134, 142 COS( X ) 146 Integerdate 46 COSH( X ) 146 Intersect ii, 67, 68, 134 Declare 133, 149Is Null 7 EXP( X ) 146 Iterate 134, 149 For / End For 149
If / End If 149 P
Iterate 134, 149 Permanent Journal iii, 109
Leave 134, 149 Position Function 55
LN( X ) 146 Precision 135, 142
LOG( X ) 146 Primary Index iii, 105, 106, 124
Loop / End Loop 149 Print 149
MOD X 146 Privileges 138
Print 149
Set 4, 67, 75, 76, 79, 80, 95, 98, 99, Q 100, 107, 108, 109, 110, 111, 121,
Qualifying Column Names 147 135, 149 Quantifiers iii, 35 SIN( X ) 146 Quarter_Of_Calendar 51 SINH( X ) 146 Quarter_Of_Year 51 SQRT( X ) 146
TAN( X ) 146 R
TANH( X ) 147
While / End While 149 Real 135, 142
Maximum (Max) 30 Rename Table 4, 115
Minimum (Min) 29 Replace Macro 4, 95
Minus iii, 34, 37, 67, 71, 134 Replace View 4, 91
MOD X 146 Revoke 140
Month_Of_Calendar 51 Rollback i, 4, 100, 101
Month_Of_Quarter 51 Rollback Work 101
Month_Of_Year 51
S Multiple Subquery iii, 34
Multiset Table 107 Secondary Index 4, 116
Select 2, 3, 4, 6, 9, 10, 11, 12, 19, 33, 37, N
51, 66, 74, 91, 92, 93, 95, 96, 97, 100,Named i, iii, 13, 14, 110, 135 101, 112, 148
Nested CASE iii, 88 Sequencing Triggers 4, 132
Non- Unique Primary Index (Nupi) 105 Set 4, 67, 75, 76, 79, 80, 95, 98, 99, 100,
Non- Unique Primary Index (NUPI) 105 107, 108, 109, 110, 111, 121, 135, 149
Not iii, 8 Set Operators
Not Casespecific iii, 25 Except ii, 34, 37, 67, 70, 71, 133
Not In ii, 9 Intersect ii, 67, 68, 134Not Null ii, 7, 52, 87, 110, 111 Minus iii, 34, 37, 67, 71, 134
Nullif iii, 82, 135 Union 4, 34, 37, 67, 69, 74, 136
Nullifzero iii, 81, 135 Set Table 107
Numeric (X,Y) 142 Show 18, 39, 41, 44, 52, 59, 60, 61, 62,
68, 69, 70, 71, 72, 73, 74, 81, 82, 83,O 135
Macro 18 Odbc 22 Procedure 18 Order By iii, 15 Table 18 Outer Join i, 43 Trigger 18View 18
SIN( X ) 146 TITLE 4, 23, 68, 69, 70, 71, 102, 103, SINH( X ) 146 104, 110, 111, 113, 136
Smallint 51, 93, 135, 142 Transaction Mode
SQRT( X ) 146 Setting 99
String And Column Concatenation 57 Triggers
Subquery After i, 130Correlated Subquery i, 36 Before i, 129
Multiple 34 Instead Of ii, 131
Multiple Subqueries iii, 34 Sequencing 4, 132
Sum 27
U System Calendar Columns 4, 51
Calendar_Date 51 Union 4, 34, 37, 67, 69, 74, 136 Day_Of_Calendar 51 Unique Primary Index (Upi) 105 Day_Of_Month 51 Update iii, 4, 75, 76, 79, 80, 93, 95, 99, Day_Of_Week 51 100, 129, 130, 131, 132, 136, 138 Day_Of_Year 51 Uppercase 110, 136 Month_Of_Calendar 51 Upsert iii, 4, 79, 80 Month_Of_Quarter 51 User Month_Of_Year 51 Create i, 121Quarter_Of_Calendar 51 Drop 122 Quarter_Of_Year 51
Week_Of_Calendar 51 V Week_Of_Month 51
Varbyte (X) 143 Week_Of_Year 51 Varchar (X) Character 142
Weekday_Of_Month 51 Vargraphic (X) 143
Year_Of_Calendar 51 View
Create View i, 89 T Drop View ii, 90
Table Locking For Access iii, 92Alias 148 Replace View 4, 91 Alter Table i, 113 Volatile Temporary Table 4, 126 Create 105, 112
Create Table i, 105, 112 W Derived Table ii, 125
Week_Of_Calendar 51 Drop Table ii, 114 Week_Of_Month 51
Global Temporary 127 Week_Of_Year 51
Global Temporary Table ii, 127 Weekday_Of_Month 51 Rename Table 4, 115 Where4, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 19, Volatile Temporary Table 4, 126
24, 25, 26, 27, 28, 29, 30, 31, 32, 33,TAN( X ) 146 34, 35, 36, 37, 38, 39, 40, 42, 43, 45,
TANH( X ) 147 51, 52, 57, 66, 75, 76, 77, 78, 79, 80,
Temporary Table 87, 89, 91, 92, 93, 95, 97, 99, 100, Drop 128 104, 117, 125, 136 Teradata Mode 98
While / End While 149 TIME 4, 50, 110, 133, 136, 142 With 4, 102
TIMESTAMP 4, 50, 133, 136, 142 With Default 110
With..By 4, 103 Z
Zeroifnull 4, 83, 136 Y
Year_Of_Calendar 51