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: Tom.Coffing@CoffingDW.Com
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

CEO. Centered around 10 Teradata Certified Masters this dynamic and growing company teaches every Teradata classes. Tom has helped implement data warehousing in over 40 major data warehouse accounts.Teradata Certified SQL Specialist Teradata Certified Administrator . Coffing has also published over 20 data warehousing articles and has been a contributing columnist to DM Review on the subject of data warehousing.000 individuals involved in data warehousing globally. He founded CoffingDW with the same philosophy more than a decade ago. spoken in over 20 countries. provides world class Teradata consultants. He is also known as "The Speech Doctor" because of his presentation skills and sales seminars.Tom. Tom has a bachelor's degree in Speech Communications and over 25 ye ars of business and technical computer experience.Teradata Certified Implementation Teradata Certified Developer Specialist Teradata Certified Designer .Simplicity by Design Teradata Database Design . and Founder of Coffing Data Warehousing. and has provided consulting and Teradata training to over 8. He wrote a monthly column for DM Review entitled. trainer. offers a suite of software products to enhance Teradata data warehouses.authored the following eight books on Data Warehousing: • • • • • • • • Secrets of the Best Data Warehouses in the World Teradata SQL . and executive coach with an extensive background in data warehousing.Breaking the Barriers Mr. and has eight books published on Teradata. He is an internationally known consultant. "T eradata Territory". Teradata Certified Master Teradata Certified Professional . He is a nationally known speaker and gives frequent seminars on Data Warehousing.Giving Detailed Data Flight Teradata Users Guide -The Ultimate Companion Teradata Utilities .Unleash the Power Tera-Tom on Teradata Basics Tera-Tom on Teradata E-business Teradata SQL Quick Reference Guide . He has trained and consulted at so many Teradata sites that students affectionately call him Tera. Tom Coffing has taken his expert speaking and data warehouse knowledge and revolutionalized the way technical training and consultant services are delivered. facilitator.About the Author Tom Coffing Tom is President. Tom is considered by many to be the best technical and business speaker in the United States. speaker. Tom has co.

California. The last 5 years with NCR were entirely focused on Teradata and customer education. Mike retired from NCR Corporation in April 2000 with 18 years of service. His other book. This book has also become the course manual for many of the SQL classes taught by Coffing Data Warehousing.About the Author Mike Larkins Mike graduated with a Bachelors of Science degree in Management Information Systems from Chapman University in Orange. programmer.Teradata Certified SQL Specialist Teradata Certified Administrator . Mike has been working with Coffing Data Warehouse since May of 2000 teaching courses and doing consulting. and college instructor. systems analyst. Other Books: Teradata SQL Unleash the Power Teradata Certified Master Teradata Certified Professional . He earned his Teradata Masters by passing all 6 certification exams. consultant. His career has involved work with a variety of computer systems and relational databases.Teradata Certified Implementation Teradata Certified Developer Specialist Teradata Certified Designer . Of the 15 courses that he taught for NCR. His computer career spans 30 years in a variety of related positions: computer operations. SQL was his favorite. Teradata SQL Unleash the Power was a best seller at Partners 2001. operating systems support.

Teradata Users Guide -The Ultimate Companion.Giving Detailed Data Flight. Teradata Certified Master Teradata Certified Professional . Assignments included resolving critical data warehousing implementation. financial.Teradata Certified SQL Specialist Teradata Certified Administrator . Steve is a recognized expert on NCR hardware. Steve has also participated in several assignments involving consulting for two major NCR Teradata Data Warehousing Customers. application development. and database administration. Steve recently completed several assignments involving Teradata training and education. Teradata Database Administration. UNIX. along with Steve’s motivation.Breaking the Barriers . Load Utilities. These data warehousing customers represent numerous major industries across the communications. physical database design. wireless. Physical Database Design. A Teradata Certified Master and co. and database conversions. administration.author of the Teradata SQL Quick Reference Guide Simplicity by Design. home improvement and technology sectors. Teradata Database Design . airlines. SQL intermediate/advanced.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. and Teradata Utilities . and SQL. He is also renowned internationally for his knowledge and expertise in these fields as well.Teradata Certified Implementation Teradata Certified Developer Specialist Teradata Certified Designer . pharmaceuticals. enthusiasm. The education that was delivered includes Teradata basics. load utilities. Application Development. and strong business skills has provided him the ability to work successfully in all global business environments.

His wide span of knowledge provides him the ability to be flexible in terms of Teradata training and consulting. and Teradata Physical Database Design.Teradata Certified Implementation Teradata Certified Developer Specialist Teradata Certified Designer . Todd combines great field experience with excellent technical expertise to deliver outstanding Teradata classes for CoffingDW. His ability to break down the most difficult of concepts into easy to understand thoughts offers his students the best route to Teradata certification. converting.Teradata Certified SQL Specialist Teradata Certified Administrator . scrubbing. Teradata Certified Master Teradata Certified Professional . technical skills. Todd has developed leadership. led core product demonstrations. Todd has also done Teradata consulting work for the largest data warehouse sites in the world. with all 6 Teradata certifications. Todd teaches Teradata Basics. and strong work ethic. He is Teradata Certified Master. and handled SQL Query along with database optimization. enthusiasm. As a Teradata DBA and consultant. perfectionism. 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. and writing Teradata SQL. He has trained and consulted at many Fortune 100 companies with a 100% Teradata Certification pass rate from his students. loading. Combined with his motivation. He has developed a repeatable process for synchronizing the development warehouse with the production warehouse. his skills provide a great addition to the Coffing Data Warehousing team. Beginning to Advanced SQL. He was responsible for all testing of Industrial Web Machines core product releases and development. Todd installed Teradata. Todd gained experience as the lead database administrator for Industrial Web Machines.About the Author Todd Carroll Todd Carroll comes to Coffing Data Warehousing with big-time Teradata field experience. scripting. and a strong decision making background. He has experience with database design. Utilities.

Government. etc. Consulting clients love his technical aptitude and ability to finish the job in a professional. yet personable manner. and his successful quest to become a Teradata Certified Master. Robert was recognized on numerous occasions for Outstanding Performance. consultant and author with Coffing Data Warehousing Robert Hines has achieved new levels of accomplishment. Software Engineer.). His most notable accomplishments are in the arenas of training. and Implementation Specialist. DB2. Communications. SQL Specialist. Along with successfully completing Microstrategy training courses. primarily in the Data Warehousing arena.Busine ss. Software Engineer in NCR's E-Business Engineering Center of Expertise is the foundation of his Teradata knowledge and experience.About the Author Robert Hines After graduating Magna Cum Laude from Benedict College with over a 3. Robert has an uncanny ability to effectively teach non-experienced and highly experienced students at the same time while satisfying both audiences. consulting and providing professional services as a programmer to numerous industries (Utility.Teradata Certified SQL Specialist Teradata Certified Administrator . The experience at NCR with Teradata and MicroStrategy helped prepare him for his enormously successful training and consulting career with Coffing Data Warehousing. While serving NCR as a Sr. Though he has extensive SQL experience with Oracle.9 grade point average. He has trained. course developer. Load Utilities and Microstrategy. Some of the awarded accomplishments included completing SQL and Load Utility tasks critical to successful product releases and mentoring contractors and employees on SQL. along with his ability to build relationships and empower end users and IT staff through effective communication. taught and mentored hundreds of developers and business users across the country on both Teradata and Microstrategy. Students rave about his fun and exciting classes that are full of interesting ways of explaining technical concepts with clarity and simplicity. Sybase and other database programming languages. Financial. Robert's experience as a Sr. it is his accomplishments in the Teradata world that he is most proud of.Teradata Certified Implementation Teradata Certified Developer Specialist Teradata Certified Designer . Robert Hines has emerged as an outstanding IT professional and has serviced clients all over the United States and Canada. 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 . Robert served as a Project Lead on a MicroStrategy conversion project. and also achieved designations as a Teradata Certified Professional. As a trainer. E.

NOT = ALL Abort Abort/Rollback Add Column Attributes ADD_MONTHS Advanced Syntax AFTER Triggers Aggregation ALIAS using NAMED Aliasing Columns ALL ALTER Table AND AND . NOT = ALL Abort/Rollback Add Column Attributes ADD_MONTHS Function Advanced Syntax AFTER Triggers Aggregation Functions ALIAS using NAMED Aliasing Columns ALTER Table ANSI INNER Join Syntax 28 10 100 110 48 86 130 27 14 13 113 40 ANSI OUTER JOIN Syntax 43 AVERAGE Function (AVG) 28 The SQL Quick Reference Guide – Simplicity by Design i .The Quicker Reference Index A ACCESS LOCKING = ANY.Nested CASESPECIFIC CAST – ANSI CHARACTERS COALESCE Collect Statistics Column and Table Constraints Column Concatenation Column Constraints Commit Work Concatenation Constraints Correlated Subquery COUNT CREATE DATABASE CREATE GLOBAL TEMP TABLE CREATE Macro Create Table CREATE USER Create View Syntax CROSS JOIN Syntax Cumulative Sum (CSUM) 51 42 85 88 24 21 52 84 118 111 57 111 100 57 111 36 31 120 127 93 105 121 89 45 59 ANSI OUTER JOIN Syntax 43 10 ANY 28 AVERAGE (AVG) AVG = ANY.Multiples AND/OR Combined AND/OR Comparators: ANSI INNER Join 92 10 100 100 110 48 86 130 27 14 13 10 113 5 6 5 4 40 BEFORE Triggers BETWEEN BT/ET B 129 11 99 C Calendar Cartesian Product Join CASE CASE .

Secondary INNER Join ANSI INSERT INSERT / SELECT Inserting Default Values Inserting NULLs INSTEAD OF Triggers INTEGERDATE INTERSECT IS NOT NULL IS NULL 9 55 106 56 117 116 40 72 74 73 73 131 46 68 7 7 124 124 124 123 123 32 17 119 87 127 The SQL Quick Reference Guide – Simplicity by Design ii .The Quicker Reference Index D Data Definition Language Data Interrogation Date DATE Date and Time Processing Default Values DELETE Delete with a Join Delete with a Subquery Derived Tables DISTINCT DML Commands DROP DATABASE DROP Macro DROP STATISTICS DROP Table DROP TEMP TABLE DROP USER DROP Views E EXCEPT EXECUTE Macro EXISTS EXPLAIN EXTRACT Function F FALLBACK FORMAT 108 22 70 94 37 19 49 105 81 46 47 46 73 77 78 78 125 16 72 122 95 119 114 128 122 90 G Global Temporary Tables H HASHAMP HASHBAKAMP HASHBUCKET Hashing Functions HASHROW HAVING Clause HELP HELP STATISTICS Horizontal Reporting I IN and NOT IN INDEX Index – Primary INDEX Function Indexes .Join Index Indexes .

Deletes Join Indexes JOIN Outer Join Syntax Join UPDATE Joins 40 40 42 78 117 43 38 76 38 N NAMED Nested CASE NOT = ALL NOT CASESPECIFIC NOT Clause NOT IN NULLIF NULLIFZERO O 14 88 10 25 8 9 82 81 L LIKE Clause Lock Syntax LOCKING FOR ACCESS Locking Modifiers LOWER M MACROS MAVG MAX MDIFF MIN MINUS Moving Average (MAVG) Moving Difference (MDIFF) Moving Sum (MSUM) MSUM MULTILOAD UPSERT Multiple Column Primary Index Multiple Subqueries Multiple WITH.The Quicker Reference Index J Join – ANSI Join – ANSI INNER Join .Cartesian Product Join ..BYs MULTISET Table 93 61 30 62 29 71 61 62 60 60 80 106 34 104 107 12 96 92 96 26 OLAP Functions OR OR Multiples OR/AND Comparators: ORDER BY Clause Original Join Syntax OUTER JOIN Syntax P 109 55 106 Primary Index .Multi-Column 106 Permanent Journal POSITION Primary Index Q Quantifiers QUANTILE 35 63 58 5 6 4 15 38 43 The SQL Quick Reference Guide – Simplicity by Design iii .

V.INSTEAD OF Triggers .Sequencing Triggers -AFTER Triggers BEFORE TRIM U..W.Z UNION UPDATE UPDATE with a Join UPDATE with a Subquery UPPER UPSERT User Information Functions Views Volatile Temporary Tables WHERE Clause WITH WITH.Delete 78 Subquery UPDATE 76 54 SUBSTR SUBSTRING 54 Subtotals 102 103 Subtotals (WITH.BY) SUM 27 System Calendar Columns 51 IV The SQL Quick Reference Guide – Simplicity by Design ..Correlated Subquery ..Multiples ZEROIFNULL 111 125 99 46 50 50 23 102 80 99 98 98 96 129 131 132 129 129 53 69 75 76 76 26 79 20 89 126 3 102 103 104 83 15 118 57 String/Column Concatenation String Concatenation 57 Subquery 33 36 Subquery .The Quicker Reference Index R RANDOM RANK RENAME Table REPLACE Macro REPLACE Views Reporting Totals/Subtotals Rollback S SAMPLE SAMPLEID Secondary Indexes SELECT Selecting the DATE Sequencing Triggers SET Table Set Operator Commands Setting the Trans Mode SHOW Sorting Statistics 65 65 116 2 47 132 107 67 99 18 66 64 115 95 91 102 100 T Table Constraints Temporary Tables Teradata Transaction Mode (BT/ET) Time TIME TIMESTAMP TITLE Totals (WITH) TPUMP UPSERT Transaction Mode Settings Transaction Mode Types Transaction Modes Transaction Processing Triggers Triggers .BY WITH.BYs .

...................................................................21 Implied Cast – Teradata .......................................................................24 NOT CASESPECIFIC .........................................................................................................................................28 MINIMUM Function (MIN) .......................27 AVERAGE Function .......................................................................................................................................................................... 7 NOT Clause .................................................................................................................................15 DISTINCT ..........................................20 SELECT Database Command .......................................................................................................................................................................13 ALIAS using NAMED .......................................................................................................................................Table of Contents TABLE OF CONTENTS The Select Command ........................................................................17 HELP ...................................................................................................................................... 6 IS NULL Clause and IS NOT NULL Clause .........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................21 FORMAT .........................................................................................................................................................................................................................................................................................................................................................................................................12 Aliasing Columns ....................................................................................................30 The SQL Quick Reference Guide – Simplicity by Design V ...............................................................................................26 Aggregation Functions ........................................... 3 Comparators: AND/OR .................................................11 LIKE Clause .................................................................................................................................14 ORDER BY Clause ..................................................................................22 Tricking the ODBC to Format ........................................................................................................................................................20 SESSION .....................................................................................................................16 Help................... 8 IN and NOT IN ...................................................................10 BETWEEN ..........................................................................20 Account ........................ 2 The WHERE Clause ............20 Data Conversions.....................................29 MAXIMUM Function (MAX) .............................22 CASESPECIFIC ................................ Explain........................ User Information Functions ................ 4 Combining Comparators: AND/OR ........................27 SUM Function ....................................................................................................................................................................................................................................................................................................... Show..............................................................................20 Default Database Command ..........................................21 CAST – ANSI ....................................................................................................................................................................28 (AVG) ......................................................... 5 Combining Multiple AND Comparators or Multiple OR Comparators ............................................................................................................................................................................................................................ NOT = ALL ......................... 9 = ANY.........................17 SHOW .................................18 User Information Functions .........25 LOWER and UPPER ..............................................................................................................................................................................................................................................................................................................................................................................................................................................

....................................................................................................................................................................................................................................51 Character String Processing ...................................................................38 ANSI INNER Join Syntax (Newer Syntax) ........Table of Contents Joins..............................55 INDEX Function ............................................................................................................................................63 RANK Function .................................................38 COUNT Function (COUNT) ..................................................................................................................................................................................................................................................................................................................................58 Cumulative Sum Function (CSUM) ................34 Quantifiers ..............67 INTERSECT .....................................59 Moving Sum Function (MSUM) .................................................................................................................................................................................46 INTEGERDATE Formula ..........................................................................................................................................................................................................47 ADD_MONTHS Function ............................................................................................................................37 Original Join Syntax .............................42 ANSI OUTER JOIN Syntax ......................61 Moving Difference Function (MDIFF) ...............................................................................................................................................................................................................43 CROSS JOIN Syntax ...........................................................................................................................................................................................................................................................................................................................................................................................33 Multiple Subqueries .........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................36 Exists ..................53 SUBSTRING and SUBSTR Functions ......................................40 Cartesian Product Join ........................................................35 Correlated Subquery ................................................56 String and Column Concatenation .......50 System Calendar Columns ...............................................................................62 QUANTILE Function ...................................................................................52 CHARACTERS Function ..........64 SAMPLE Function and SAMPLEID ..........................................................54 POSITION and INDEX Functions ......................................................................................................................................................................65 RANDOM Function .............................................................49 TIME and TIMESTAMP .............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................48 EXTRACT Function ......45 Date and Time Processing ...........................31 HAVING Clause ...........................57 OLAP Functions ......................................................................................................................................................................................52 TRIM Function ..........60 Moving Average Function (MAVG) ........................................68 VI The SQL Quick Reference Guide – Simplicity by Design ......................................................................................................................46 Selecting the DATE ...............................................................................................................................................................32 Subquery ............................66 Set Operator Commands ................................................................

.................87 Nested CASE ......................................88 ............................................................................................80 Views..................................................81 NULLIF ....................................71 Data Manipulation Language Commands Inserting NULL and Default Values ............................................................................................................................................................................................................................................................................................................................................................90 REPLACE Views .................................................................................................................................................................................................................................................................................................................................................................................................................................89 MACROS..................................................................................................................................................................................................................................................85 Basic Syntax ................................................................................91 LOCKING FOR ACCESS ........................................70 MINUS ......................................................75 UPDATE with a Subquery ................................................................................................................................................73 INSERT / SELECT ...............................................................................................................79 UPSERT for TPUMP and MULTILOAD DATA INTERROGATION .................................................69 EXCEPT ...........................................................................................................................................86 Horizontal Reporting ............................................................................................................................77 Delete with a Join ................................................................................................94 REPLACE Macro ................................................................................................................................92 CREATE Macro ..................................................................85 Advanced Syntax ...................96 Locking Modifiers .....................................................72 INSERT ....95 DROP Macro .......................................................................................................................................................................................................96 Lock Syntax ...............................................................................76 DELETE ................................................................................................................93 Create View Syntax ........95 Transaction Processing ....................................................................................................................................................................................................................................................................................................................................................................................................................84 CASE ......................................................................82 ZEROIFNULL .................................................................................................76 UPDATE with a Join ..................................................................................................................................78 UPSERT ..........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................81 NULLIFZERO .....................83 COALESCE ..................................................................................................................89 DROP Views ..........................................................................................................................................................................................72 ..........................................................................................................................................................................................................................................................................................................................................................................................................................96 Lock Types ..........................................................................................................................................................................................................78 Delete with a Subquery ...................................................................................................Table of Contents UNION .....................................................74 UPDATE ......................................................................................................96 The SQL Quick Reference Guide – Simplicity by Design VII ......................................................................................................................93 EXECUTE Macro .................................................................

..........................................99 Commit Work ............................................................................................................................................................ 125 Volatile Temporary Tables ....................................... 117 Collect Statistics ............................................................................................................................................................................................................................................98 ........................................ 102 Subtotals (WITH...................................................................................................................... 101 Reporting Totals and Subtotals ................................................................................... 124 HASHBAKAMP ....................................................................................................................................................... 115 Secondary Indexes ............................................................................................................................................................................ 100 Abort/Rollback .....................................99 Transaction Mode Types Setting the Transaction Mode Teradata Transaction Mode (BT/ET) .......... 100 Rollback Work ................................................................................................................................................... 108 Permanent Journal ................................................................................................................................... 113 DROP Table ............................................................................. 118 HELP STATISTICS DROP STATISTICS .....................................................................................................Table of Contents Transaction Modes ............................................................................................ 101 Data Definition Language ............................................ 125 Derived Tables ............................................................................................................................................................. 112 ALTER Table .................................. 123 HASHROW ............................ 126 VIII The SQL Quick Reference Guide – Simplicity by Design ................................................................................................................................................................. 104 ROLLBACK WORK .................................................................................................................................................................. 124 Temporary Tables ............................... 102 Totals (WITH) ..................................................................................................... 114 RENAME Table ............................................................................................. 119 ... 123 HASHBUCKET ............................................................................................................................................................................................... 122 Hashing Functions .................................................................................................................................................................................................................................................................................................................................................................................................. 105 Multiple Column Primary Index .. 109 Add Column Attributes ...........Bys ................................................................................................................................................................................................. 116 Join Indexes ........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................... 103 Multiple WITH.................................................................................. 106 SET | MULTISET Table ........................................................... 111 CREATE TABLE with copying an existing table .............................................................................................................................................................................................................................................................................. 105 Create Table .............................................98 ................................................................................................................................................................... 107 FALLBACK .................................................................................................................. 121 DROP DATABASE or USER ................ ..................................................................................................................................................................................... 110 Column and Table Constraints ........................ 124 HASHAMP ........................................................................................................ 119 CREATE DATABASE ...................................................................................................................................................................BY) ......................................................................................................................... 120 CREATE USER ..................

Table of Contents

Global Temporary Tables

.................................................................................................................... 127 ....................................................................... 127

CREATE GLOBAL TEMPORARY TABLE

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 downloaded from our website at :

www.CoffingDW.Com .

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

Dept_Name FROM Department_Table. Page 2 The SQL Quick Reference Guide . you are in the wrong database. Hint . Take the extra comma out. Solution: Search through the SQL code to locate the two columns with no comma between the two. Solutions: Check the spelling of the <table -name>. Here is the Error Message: 3810: Column ‘Column1Column2’ does not exist. The SELECT * relates to columns and the WHERE clause relates to rows selected.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. “3807: Table/view/trigger ‘<table-name> does not exist.name>. SELECT {*} FROM <table. When requesting multiple columns in a table each column is separated from the next by a comma. SELECT { <column-name> } […. Or you could have an extra comma at the end of the last column selected. SELECT Customer_Number FROM Customer_Table. 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 asterisk returns every column in the table. Hint .Man Issues: A missing comma could be a problem with this syntax.name>.<column-name> ] FROM <table.Man Issues: The message. and place a comma. SELECT Dept_No .” will occur when the table being selected from does not reside on Teradata. SELECT * FROM Course_Table. Or. Experienced users often place the comma at the beginning for easy debugging.

The <data -value> in the WHERE clause does not match the data type of the <column-name>.name> WHERE { <column-name> | <expression> } <comparison> <data-value> . SELECT * FROM Employee_Table WHERE Dept_No = 400. If you want to access data as fast as possible use the Primary Index column in the WHERE clause. If a query has no WHERE clause then every row will be selected. Hint . Next.<column-name> ] FROM <table.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. The SQL Quick Reference Guide Page 3 . SELECT { * | <column-name> } […. adjust the <data -value> to match the data type. Also remember that numeric values are not in single quotes ‘ ‘.Man Issues: 3535: A character string failed conversion to a numeric value. 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>. Character data should be in single quotes. English: The above example will SELECT all columns from the Employee_Table if the employee’s department number is 400.

000. Hint . Only one of them has to be true. you can’t say WHERE DEPT_NO = 10 OR 20. English: Above we select all columns if the customer number = 11111111 AND the Order_Total is greater than 10000. only requires one of the two to be true. Daily_Sales FROM Sales_Table WHERE Sale_Date = ‘2000-09-28’ OR Sale_Date = ‘2000-10-01’. an employee could not have a SALARY of $50. You must say WHERE DEPT_NO = 10 OR DEPT_NO = 20.The SQL Reference Guide Comparators: AND/OR Many times a single comparison in a WHERE clause is not enough to specify the desired rows.value> AND | OR <column. English: Above we select two columns for any row that has a sale date of eit her September 28 2000 or October 1 2000. The OR syntax however. SELECT * FROM Order_Table WHERE Customer_Number = 11111111 AND Order_Total > 10000.name> WHERE <column-name> <comparison> <data. SELECT <column.name> [….<column-name> ] FROM <table. SELECT Product_Id. For example. For example.000 AND $75.Man 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. The AND syntax requires both comparisons to be true . Page 4 The SQL Quick Reference Guide . Both have to be true for data to come back.000. The AND/OR commands are called logical operators. You could however have an employee in department 100 AND have a salary of $50.name> <comparison> <data-value>. 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.

like the above example. First_Name FROM Student_Table WHERE ( Class_Code = ‘JR’ OR Class_Code = ‘SO’ ) AND Grade_Pt > 2.name> WHERE (<column. Hint .Simplicity by Design Combining Comparators: AND/OR SELECT <column.Man Issues: The data you expected to come back may not.name> [..<column-name> ] FROM <table. SELECT Last_Name.5.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..name> <comparison> <data-value> ) AND <column. The SQL Quick Reference Guide Page 5 .name> <comparison> <data-value> OR <column. 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.name> <comparison> <data-value> . When there is an AND/OR combination the AND is always done first by Teradata unless the OR pair is in parentheses..

0 and 4. SELECT Employee_No FROM Employee_Table WHERE Dept_No <> 400 AND Salary > 40000 AND Salary < 50000.name> <comparison> <data-value> AND | OR <column. 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.0. English: Above we select every column from the row if the Student_Id is 280023 or 333450 or 231222. Hint . a user should not search for a student with a Grade_pt of 3. This will not work because nobody can have a Grade_pt of both 3.0.name> [.name> <comparison> <data-value> SELECT * FROM Student_Course_Table WHERE Student_Id = 280023 OR Student_Id = 333450 OR Student_Id = 231222. You can place parenthesis around the SQL and it will be evaluated first. but less than $50000..value> AND | OR <column. Dealing with NOT.The SQL Reference Guide Combining Multiple AND Comparators or Multiple OR Comparators SELECT <column.Man Hint . Remember that ALL criteria must be met in order for the row to be returned in the result set.. An OR should have possibly been used. AND an OR can be confusing..<column-name> ] FROM <table.Man Be careful when using multiple AND statements. For example.0 and 4.name> WHERE <column-name> <comparison> <data. Page 6 The SQL Quick Reference Guide .

but no rows will be returned. WHERE Grade_Pt English: Above we select two columns from any row that does NOT have a NULL value for Grade_pt.name> [.<column-name> ] FROM <table -name> WHERE <column-name>IS NULL SELECT Last_Name. Hint . Change the syntax to IS NULL.. SELECT Last_Name.Man Sometimes when checking if something is = NULL you will get an error and sometimes you will not get an error. Solution: Adjust the SQL syntax from ‘=NULL’ to ‘IS NULL’ or ‘IS NOT NULL’. First_Name FROM Student_Table WHERE Grade_Pt IS NULL . The SQL Quick Reference Guide Page 7 . Therefore you can never check if something is EQUAL to NULL. First_Name FROM Student_Table IS NOT NULL .. 3731: The user must use IS NULL or IS NOT NULL to test for NULL values. English: Above we select two columns from any row that has a NULL value for Grade_pt.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. Issues: = NULL is not a valid SQL statement. You can only check if something IS NULL or IS NOT NULL. SELECT <column.. When checking for NULLS the only valid statements are IS NULL or IS NOT NULL.

Phone_Number FROM Customer_Table WHERE Customer_Name NOT= ‘ACE Consulting’.name> WHERE <column-name> NOT<comparison> <data-value> . WHERE Seats SELECT Course_Name FROM Course_Table NOT >= 20. Running this syntax without parentheses is permissible. Phone_Number FROM Customer_Table WHERE NOT ( Customer_Name = ‘ACE Consulting’ ) . . SELECT <column. SELECT Customer_Name. English: Above we SELECT two columns for all Customers except ‘ACE Consulting’. with the <comparison> after that. Page 8 The SQL Quick Reference Guide . Teradata English: Above we find all courses where there are less than 20 seats in the course. SELECT Customer_Name. Solutions: Locate the ‘NOT’ in the SQL and place it directly before the <column-name>. but not recommended. Hint .The SQL Reference Guide NOT Clause The NOT Clause will check for values that are NOT <.value>).name> FROM <table.name> FROM <table.Man Issues: Teradata returns the message: 3707: Syntax error. WHERE SELECT Course_Name FROM Course_Table NOT ( Seats >= 20 ) . Alternative Syntax: SELECT <column. expected something like an ‘IN’ keyword between the ‘NOT’ keyword and ‘<comparison>’. > or equal to a value searches for the logical opposite of the <comparison> statement. This is a problem caused by the ‘NOT’ not being properly placed in the SQL.name> WHERE NOT (<column-name> <comparison> <data.

If the criteria are in the <value . English: Above we select all columns unless the Order_Number is 123585 or 123456. English: Above we select two columns from each row where the Dept_no is 200 or 300 or 100. 300.name> [.. SELECT <column.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>. a row will be returned. Teradata actually views the IN clause as a multiple OR statement.. ‘Marketing’). Solutions: Place a ‘(‘ before the <value -list> and a ‘)’ after the final entry in the <value list>. being that no rows will be returned every time. WHERE Dept_No SELECT Dept_Name.. Hint .’. Do not place the word ‘NULL’ in the <value-list> for a ‘NOT IN’.list>. Mgr_No FROM Department_Table IN ( 200.<column-name> ] FROM <table -name> WHERE <column-name> IN | NOT IN (<value -list>) . Notice the single quotes around ‘Sales’ and ‘Marketing’. 123456 ) . SELECT * FROM Order_Table WHERE Order_Number NOT IN (123585. They are not numbers so they need single quotes. The SQL Quick Reference Guide Page 9 . WHERE Dept_Name English: Above we select all columns from the Department_Table if the department name is Sales or Marketing. SELECT * FROM Department_Table IN( ‘Sales’ .Simplicity by Design IN and NOT IN The IN comparison is an alternative to using one or more OR comparisons on the same columnin the WHERE clause of a SELECT.100 ) .

<column-name> ] FROM <table -name> WHERE <column-name> = ANY (<value -list>). or after the ‘NOT’ keyword. Be careful NOT to use NOT = ANY . Page 10 The SQL Quick Reference Guide .. WHERE Dept_No SELECT Dept_Name. Mgr_No FROM Department_Table = ANY ( 200. NOT = ALL The =ANYcommand is the logical equivalent to the command is similar to the NOT IN clause. SELECT * FROM Order_Table WHERE Order_Number NOT = ALL ( 123585.list>) .The SQL Reference Guide = ANY.name> [. 100). Issues: Missing the ‘=’ sign is a possible problem. This is because the instance a value is not equal to any one in the list. 300. The NOT = ALL English: The above example selects two columns if the Dept_No is 200 or 300 or 100. 300. IN clause . This syntax is the same as NOT IN. This is because all rows will be returned unless they Are NULL.<column-name> ] FROM <table -name> WHERE <column-name> NOT = ALL(<value . Solutions: Add the equal sign before the ‘ANY’ keyword. 123456 ) .name> [. SELECT <column.Man automatically returned. it is Hint ... This is the same syntax as WHERE Dept_No IN (200. English: The above example will SELECT all columns WHERE the Order_Number does NOT = 123585 or 123456.. 3707: Syntax Error... expected something like an ‘IN’ keyword or a ‘LIKE’ keyword between the ‘NOT’ keyword and the ‘ALL’ keyword. 100) . SELECT <column.

name> [. Grade_Pt FROM Student_Table WHERE Last_Name BETWEEN ‘Delaney’ and ‘Phillips’ . If you write WHERE AGE is BETWEEN 13 and 15 then the answer set would contain individuals whose ages are 13. SELECT * FROM Sales_Table WHERE Daily_Sales BETWEEN 25000 AND 42000 .Man BETWEEN is a command to look for ranges. First_Name. SELECT Last_Name. 14. Hint .. or 15. The SQL Quick Reference Guide Page 11 . This includes 25000 exactly and 42000 exactly. Then BETWEEN and DATE ranges work in tandem. The key item to remember is that BETWEEN is inclusive and most widely used with numericvalues. If you index a date field in a table you can use the ORDER BY VALUES syntax when creating the date index. BETWEEN works well with dates..Simplicity by Design BETWEEN The BETWEEN statement is another technique to request multiple values for a column that are all in a specific range. English: Select three columns where the Last_Name is between Delaney and Phillips..<column-name> ] FROM <table -name> WHERE <column-name>BETWEEN <low-value> AND <high-value>. This includes Delaney. English: Select all columns where the Daily_Sales is between 25000 and 42000. To see if a d ate is an index ORDERED BY VALUES run the SHOW TABLE <Tablename> command. SELECT <column. Phillips and any name alphabetically greater than Delaney and Less than Phillip s.

Hint . Issues: The LIKE statement is not returning all the rows expected to be in the result set. The wildcard characters are: Wildcard symbol What it does _ (underscore) matches any single character. SELECT * FROM Student_Table WHERE TRIM(Last_Name) LIKE ‘%h’. You can use the TRIM function with the LIKE function to find anyone whose name ended in h. but a character must be present % (percent sign) matches any single character. English: Select all columns from the rows in the Student table if Last_Name has an m as the second character. If I have a name that is CHAR(10) and a name such as Smith then the system sees the name as ‘Smith ‘.list> FROM <table -name> WHERE <column-name>LIKE ‘[<wildcard(s)>]<search-string>[<wildcard(s)>]’. a series of characters or the absence of characters SELECT Course_Name. SELECT * FROM Student_Table WHERE Last_Name LIKE ‘_m%’ .Man LIKE works on Character Data. This empty space resides in the rest of the fixed data space on the system. Course_Id FROM Course_Table WHERE Course_Name LIKE ‘%SQL’ . For example. as in the second example. a user can use the LIKE command to request rows where the last_na me starts with ‘SM’. Page 12 The SQL Quick Reference Guide . Either solution will take care of the problem.The SQL Reference Guide LIKE Clause The LIKE Command searches character data strings and can use wildcards to find data that is similar. The first solution is to place a ‘%’ at the end of the <search-string>. 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’. Notice the 5 extra spaces. SELECT <column. The second solution would be to place the <column-name> in a TRIM function as so: TRIM(<column-name>. Solutions: There are two solutions to this problem. English: Select two columns from the rows in the course table if Course_Name has SQL at the end of the string.

In giving a column an alias. Solutions: You can place double quotes around the ALIAS name and it is no longer considered a keyword in the query.name>. Also notice we are sorting by “Department Name”. For example. For example. The second column needs them because there is a space between Department and Name.name> FROM <table. there are two options: ANSI Standard: SELECT <column. SELECT Dept_No . We once again use the double quotes. Issues: A common error is using a Teradata Reserved Word for an alias. The first column does not need double quotes. AS DEPT AS “Department Name” Manager AS <alias-name> English: We have aliased three columns.name> < alias-name > <table.Dept_Name .name>. Hint . 3707: Syntax Error. The third ALIAS does not have the word AS.Simplicity by Design Aliasing Columns You create an ALIAS on a column for the purpose of giving the column a new name . The word AS is optiona l when aliasing.Man If a user desires to assign an alias with a space like “Department Name”. The SQL Quick Reference Guide Page 13 . Teradata Standard: SELECT FROM <column. expected something like a name between the {‘AS’ | ‘NAMED’} keyword and the ‘<reserved-word>’ keyword. Department_Name does not need quotes. be sure to use double quotes around the alias 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. otherwise you don’t need the quotes. if you had an ALIAS named MAX you could place double quotes around it to become “MAX”.Mgr_No FROM Department_Table ORDER BY “Department Name”.

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> FROM <table- name> ;

( NAMED <alias -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.

Hint - Man

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.

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 default for Teradata isascending order. . The

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_Total FROM 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.

Hint - Man

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 BY the 1 s t column in the table.

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 toeliminate all the duplicatesand 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.

Hint - Man

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 example, the rows returned will be any distinct combinations of First_Name and Dept_No.

Hint - Man

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.

Page 16 The SQL Quick Reference Guide

Student_Table.Course_Name. parameters passed. User Information Functions HELP The Help Function returns important informationregarding the object specified in the SQL. HELP Session. Object Choices: Database User Table Volatile Table View Macro Procedure Trigger Column Index Statistics Session HELP Database SQL_CLASS. HELP <OBJECT> <Object Name>. HELP Column Course_Table. Issues: A common problem is that an object does not exist.Simplicity by Design Help. Show. You might have misspelled the object name or are pointing to the wrong database. Explain. HELP ‘SQL Create’. not exist . Results include columns involved in the object. HELP Table SQL_CLASS. etc. HELP ‘SQL | <Function>’. HELP ‘SQL Explain’. The HELP SESSION command will tell you what Database you are currently in. the data type. Object <object-name> does Solutions: The easiest and quickest solution is to execute the HELP DATABASE <databasename> command to see what objects are in the database. The SQL Quick Reference Guide Page 17 . table and column comments.

Page 18 The SQL Quick Reference Guide .The SQL Reference Guide SHOW Teradata will return the actual DDL/Create Text for the given object in the SQL. SHOW Macro SQL_CLASS. Object Choices: Table View Macro Trigger Procedure SHOW Table Department_Table. The next choice is to simply run the HELP DATABASE <databasename> command to get a list of all the objects in the database where you believe the object is located. SHOW<OBJECT> <object name>. what indexes are defined. Hint . You can also use this to see what indexes are on a table. This is handy if a user needs to create an object identical or similar in structure. Solutions: The first item is to check the spelling of the <object-name> to ensure proper spelling. SHOW Procedure Department_Count_p. SHOW View Department_Table_v. or stored procedure with the replace command it is a great idea to do the show command and then copy the current structure to make the necessary changes. Issues: Object does not exist error code: <object-type> <object-name> does not exist. and any constraints in the table.Man The SHOW command is great if you want to see columns definitions. macro.Department_Count_m. If you have to change a view. SHOW Trigger Update_Department_t. You can also see which da tabase you are currently point to with the HELP SESSION command.

EXPLAIN SELECT * FROM Student_Course_Table.customer_number. This plan will include information on indexes being used. estimated range of rows returned.customer_number = b. EXPLAIN SELECT last_name. EXPLAIN<SQL command>. The EXPLAIN will also tell you the strategy for joins or the indexes being utilized for a particular query.Simplicity by Design EXPLAIN Returns the Optimizer’s plan of how the Teradata system will perform the given SQL request. first_name FROM Employee_Table WHERE Salary > 45000. The SQL Quick Reference Guide Page 19 . or vital tables that are frequently accessed. estimated time for query execution. Hint . Customer_Name FROM Customer_Table AS a INNER JOIN Order_Table AS b ON a.Man It is always recommended to run an EXPLAIN on any new query involving large tables. EXPLAIN SELECT Customer_Number. and information about the spool space used during the query.

Page 20 The SQL Quick Reference Guide . DATABASE SQL_CLASS.The SQL Reference Guide User Information Functions Default Database Command Moves the scope of the user from one database to <Database Name>. Select SESSION . Account Returns the account numberfor the current user you are logged in as. Select DATABASE . SELECT Database Command This command displays the database that the user is currently located. This command can eliminate the need to qualify a table in a certain database. Select ACCOUNT . SESSION Retrieves the session numberabout the current user. Database <Database Name>.

This tells the user that the <data -type> the <column-name> is being cast to is not large enough to accommodate the transformation. Hint . Once that is established. It transforms a <column-name> to another data type to easier perform calculations and reporting.name> ( <data-type> [(<length>)] FROM <table.name> . SELECT CAST(<column-name>AS <data-type>[(<length>)] ) FROM <table.Simplicity by Design Data Conversions CAST – ANSI Cast is an ANSI standard function that converts a <column-name> from one data type for another .Man Issues: When using these syntaxes a user may run into this error message: 2617: Overflow occurred computing an expression involving <table-name>. SELECT Student_id (CHAR(10)) FROM Student_Table. The actual table is unaffected. choose a proper sized data type to transform the <column-name> and change the SQL. The SQL Quick Reference Guide Page 21 .<column -name> . SELECT CAST(Student_id as CHAR(10)) FROM Student_Table. Solutions: The best solution would be to perform a HELP TABLE <table -name> to discover the actual data type of the <column-name>.name>. This allows for flexibility in creating reports and performing calculations on non-like data type columns. Implied Cast – Teradata This is a Teradata Extension for the ANSI Cast function. SELECT <column. English: The example above will SELECT the Student_id from the Student_Table and display it as a Character 10 data type. Be careful because the results may vary between the Implied Cast and ANSI Standard CAST.

Man Remember when using Queryman the FORMAT function will not be acknowledged by the ODBC driver and therefore won’t work. This will allow for the format statement to work with Queryman.string’ ) ) AS CHAR(<length>) ) FROM <table.name>.name>. SELECT CAST( (<data>(FORMAT ‘<format. 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. Refer to the following sub-section titled “Tricking the ODBC to Format”. Anytime you want the format statement to work in Queryman you can cast the result as a character. Hint . Hint . Although it will NOT cause an error in Queryman The Format will not take in Queryman.name>(FORMAT <format-scheme>) FROM <table. Order_date (FORMAT ‘YYYY-MM-DD’) FROM Order_Table. CAST(( Student_Id (FORMAT ‘X(10)’)) AS CHAR(10)) English: The example above will CAST the student_Id as a Character 10.The SQL Reference Guide FORMAT Formatting is mainly used to make the reporting of the data easier to read. By casting the results as character data the format will 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. SELECT <column. Page 22 The SQL Quick Reference Guide . This is a great tip.Man The Format statement works in BTEQ. but truncation will not work in ANSI mode. SELECT FROM Student_Table. We have found a way to get the FORMAT function to work in Queryman. SELECT Customer_Number (FORMAT ‘99999999’) . This is a key way to truncate data when using a tool like BTEQ. This trick is essential in making data format in the desired manner.

TITLE is more functional in BTEQ due to the ability to stack the Title in the column header. SELECT <column.” Teradata is saying that your title needs single quotes around it. English: The above example will TITLE the student Id as Student on the top line and Identification on the bottom. Sometime s Queryman does not always TITLE what you want. It does not perform like creating an alias.Grade_Pt FROM (TITLE ‘Student // Identification’) (TITLE ‘GPA’) Student_Table. This is how you stack and can have up to 3 stacks. The stacking feature does not work in Queryman. The SQL Quick Reference Guide Page 23 . expected something like a string between the ‘TITLE’ keyword and the word ‘Column title to appear in output’.name> FROM <table -name>. but NOT the Title. Solutions: The solution is simple: Place single quotes around the title. The Grade_Pt will have a TITLE of GPA.Simplicity by Design TITLE This syntax changes the name of a <column-name> only in the heading of the result set .Man Issues: A common error message when dealing with TITLE is. “3707: Syntax error. You can sort with the ALIAS name. <column.name> . The Title is for the title and the Alias is a new way to refer to the column. (TITLE ‘Column title to appear in output’) (TITLE ‘Level 1 // Level 2 // Level 3’) SELECT Student_id . You can give a column both a Title and an Alias. which Queryman cannot do. not as the SQL itself. TITLE is only used to Title a column. Hint .

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. Page 24 The SQL Quick Reference Guide . Hint . 3706: Syntax error: expected something between the word ‘<word1>’ and 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.<column-name>] FROM <table.name> WHERE <column-name>( CASESPECIFIC) ={‘<character-literal>’ | <column. ANSI Mode does not see ‘abc’ as the same thing as ‘ABC’.name>}. Customer_Number FROM Customer_Table WHERE Customer_Name (CASESPECIFIC) = ‘ACE Consulting’ . 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’. awareness of the difference SELECT <column..Man Issues: ‘<word2>’.name> [.The SQL Reference Guide CASESPECIFIC Forces Teradata to compare the given data values with between lower case and upper case characters. SELECT Customer_Name.

Hint .. The SQL Quick Reference Guide Page 25 . This only needs to be used while a user is inANSI Mode . SELECT Customer_Name.name> [. Solutions: Locate the <character-literal> string in the code and place single quotes around it. SELECT <column..Simplicity by Design NOT CASESPECIFIC Turns off the need to test for upper case or lower case characters.. English: The above makes Customer_Name NOT CASESPECIFIC so the comparison of Customer_Name must equal ACE Consulting.name> }. Customer_Number FROM Customer_Table WHERE Customer_Name (NOT CASESPECIFIC) = ‘ACE Consulting’ .Man Issues: ‘<word2>’. but without exact upper and lowercase characters. 3706: Syntax error: expected something between the word ‘<word1>’ and This error message usually indicates the lack of single quotes around the <character-literal> in the SQL. 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’.name> WHERE <column-name> ( NOT CASESPECIFIC) = { ‘<character-literal>’ | <column.<column-name>] FROM <table. ANSI Mode does not see ‘abc’ as the same thing as ‘ABC’.

name>) FROM <table. The WHERE clause will also convert Course_Name to UPPER Case in the comparison.name> to lower case before any testing is performed. Page 26 The SQL Quick Reference Guide .The SQL Reference Guide LOWER and UPPER The Lower Function changes all the characters in <column. SELECT FROM Department_Table. LOWER(Dept_Name) English: The above example will SELECT Dept_Name from the Department_Table and display the Dept_Name in all lowercase.name>) FROM <table. SELECT UPPER(<column. SELECT UPPER(Course_Name) FROM Course_Table WHERE Upper(Course_Name) =‘DATABASE ADMINISTRATION’ . SELECT LOWER (Course_Name) FROM Course_Table WHERE LOWER (Course_Name) = ‘database administration’ . SELECT FROM Department_Table. English: The Course_Name that is selected will be displayed in UPPER Case.name> }].name> [WHERE UPPER(<column. The Upper Function transforms all the characters in <columnname> to uppercase prior to any testing of criteria.name> [WHERE LOWER(<column.name>) = { ‘<character-literal>’ | <column. 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. UPPER (Dept_Name) English: The Dept_Name will be displayed in uppercase.name>) = { ‘<character-literal>’ | <column.name> }]. SELECT LOWER(<column.

MIN. We call these non-aggregates. Column names or numbers are admissible. Next.name>] [ORDER BY <column-name>]. SUM(Daily_Sales) . SELECT Dept_No. AVG. SUM Function A user performs this function to that final value in the result set.Simplicity by Design Aggregation Functions The focus of aggregates is to summarize the values of data in a given column.line answers for SUM.<column-name>] FROM <table. write a GROUP BY statement with all the non-aggregate columns.. 3504: Selected non-aggregate values must be part of the associated group.. SELECT GROUP BY is used when a non-aggregate column is in the Select Statement. The main thing to remember is that aggregates remove any type of detail on that column..Man Issues: The most common error with Aggregates is not using GROUP BY with nonaggregate columns. All nonaggregate columns are required to be in the GROUP BY Statement.name> and returns SELECT SUM(<column-name>) [. The SQL Quick Reference Guide Page 27 . Hint . The GROUP By statement will allow you to get aggregates for each GROUP. Solutions: Search through the SQL and find all the columns that are not involved in aggregate functions.name> [WHERE <column. Product_Id FROM Sales_Table GROUP BY 2 ORDER BY Product_Id. and COUNT. with the desired sequence of grouping.name> <comparison> <value>] [GROUP BY <column. SELECT SUM(Budget) FROM Department_Table. Aggregates produce one. MAX. SUM(Salary) FROM Employee_Table GROUP BY Dept_No . It’s important to know that all the aggregate functions ignore NULL values in the respective calculations. add up all the values in the <column.

Man Issues: The most common error with Aggregates is not using GROUP BY with nonaggregate columns. write a GROUP BY statement with all the non-aggregate columns. We call these non-aggregates. like all other aggregates. Product_Id FROM Sales_Table GROUP BY Product_Id ORDER BY Product_Id. SELECT Dept_No. The GROUP By statement will allow you to get aggregates for each GROUP. Column names or numbers are admissible. Hint . AVG(Salary)FROM Employee_Table AVG(Daily_Sales) . SELECT AVG(Budget) FROM Department_Table. This calculation.<column-name>] FROM <table. with the desired sequence of grouping.The SQL Reference Guide AVERAGE Function (AVG) Teradata returns a calculated average on the given <column. Next. Solutions: Search through the SQL and find all the columns that do are not involved in aggregate functions. GROUP BY is used when a non-aggregate column is in the Select Statement. All nonaggregate columns are required to be in the GROUP BY Statement. These are non-aggregates and so the Group By statement must be used.name>.name> <comparison> <value>] [GROUP BY <column. Also notice in some of the examples we are also looking for Dept_No or Product_Id. GROUP BY 1 .. SELECT AVG(<column-name>) [.name> [WHERE <column. 3504: Selected non-aggregate values must be part of the associated group. is not affected by NULL va lues.. SELECT English: In the above examples you see that we are looking for the Averages as our chosen aggregate.name>] [ORDER BY <column-name>]. Page 28 The SQL Quick Reference Guide ..

with the desired sequence of grouping.<column-name>] FROM <table. Hint .Man Issues: The most common error with Aggregates is not using GROUP BY with nonaggregate columns. Next.name> and returns the smallest value to the result set.. We call these non-aggregates.. SELECT MIN(Budget) FROM Department_Table. SELECT Dept_No.. GROUP BY 1 . All nonaggregate columns are required to be in the GROUP BY Statement.name> <comparison> <value>] [GROUP BY <column. GROUP BY is used when a non-aggregate column is in the Select Statement. 3504: Selected non-aggregate values must be part of the associated group. The SQL Quick Reference Guide Page 29 . SELECT MIN(<column-name>) [.name>] [ORDER BY <column-name>]. The GROUP By statement will allow you to get aggregates for each GROUP. SELECT 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. MIN(Salary) FROM Employee_Table MIN(Daily_Sales) .name> [WHERE <column.Simplicity by Design MINIMUM Function (MIN) This function searches through all the values of the <column. Solutions: Search through the SQL and find all the columns that do are not involved in aggregate functions. Column names or numbers are admissible. Notice that we can say Group By 1 meaning the first column in our select list or GROUP BY Product Id actually specifying the name. write a GROUP BY statement with all the non-aggregate columns. Product_Id FROM Sales_Table GROUP BY Product_Id ORDER BY Product_Id.

SELECT MAX(<column-name>) [.name> of the MAX function. with the desired sequence of grouping.name> [WHERE <column. SELECT MAX(Budget) FROM Department_Table.<column-name>] FROM <table... Hint . Product_Id FROM Sales_Table GROUP BY 2 ORDER BY Product_Id. MAX(Daily_Sales) . write a GROUP BY statement with all the non-aggregate columns. We call these non-aggregates.name>] [ORDER BY <column-name>]. 3504: Selected non-aggregate values must be part of the associated group.Man Issues: The most common error with Aggregates is not using GROUP BY with nonaggregate columns.name> <comparison> <value>] [GROUP BY <column. Solutions: Search through the SQL and find all the columns that do are not involved in aggregate functions. All nonaggregate columns are required to be in the GROUP BY Statement. Column names or numbers are admissible. SELECT GROUP BY is used when a non-aggregate column is in the Select Statement. SELECT Dept_No..The SQL Reference Guide MAXIMUM Function (MAX) Aggregate function that will return the l argest value in the <column. Page 30 The SQL Quick Reference Guide . MAX(Salary) FROM Employee_Table GROUP BY Dept_No . Next. The GROUP By statement will allow you to get aggregates for each GROUP.

Column names or numbers are admissible. The GROUP By statement will allow you to get aggregates for each GROUP. Product_Id FROM Sales_Table GROUP BY 2 ORDER BY Product_Id. COUNT(Daily_Sales) .name> [WHERE <column. Solutions: Search through the SQL and find all the columns that do are not involved in aggregate functions. The SQL Quick Reference Guide Page 31 . write a GROUP BY statement with all the non-aggregate columns. 3504: Selected non-aggregate values must be part of the associated group. COUNT(Salary) FROM Employee_Table GROUP BY Dept_No .Simplicity by Design COUNT Function (COUNT) This function performs a count of the number of values in the <column-name> that exist.name> <comparison> <value>] [GROUP BY <column.Man Issues: The most common error with Aggregates is not using GROUP BY with nonaggregate columns.<column-name>] FROM <table. with it counting the number of rows. SELECT GROUP BY is used when a non-aggregate column is in the Select Statement. All nonaggregate columns are required to be in the GROUP BY Statement. with the desired sequence of grouping. SELECT Dept_No. SELECT COUNT(<column-name>) [.. A COUNT(*) will be sure to include all NULLs.name>] [ORDER BY <column-name>]. Hint . SELECT COUNT(*) FROM Department_Table.. We call these non-aggregates.. Next. not the number of values in a column.

We are using the GROUP BY statement on the Dept_No and getting our aggregates for every Dept_No.. HAVING waits until the aggregate calculation is complete and then eliminates any groups who don’t meet the HAVING condition. WHERE eliminates the base rows selected for calculation. 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. The HAVING clause is the WHERE clause for aggregate groups. then HAVIN G serves as afinal filterbefore the results are returned.. Hint .<column-name>] FROM <table..name> . HAVING <limiting -constraint> SELECT Dept_No. AVG(Salary) FROM Employee_Ta ble HAVING Total_Sal > 120000 GROUP BY Dept_No. WHERE and HAVING are similar but different. English: In the above example we are selecting Dept_No (a non-aggregate) and SUM of Salary and AVG of Salary. Teradata performs the aggregate functions. If not the group is eliminated. HAVING has no effect on the base rows.Man Page 32 The SQL Quick Reference Guide .function> (<column-name>) [. SELECT <aggregate. SUM(Salary) as Total_Sal .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.

<column-name> ] [ NOT ] IN ( SELECT <column-name> […. FROM Employee_Table WHERE Hint .<column-name>] FROM <table -name> WHERE <column-name>[. SELECT Employee_No.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. Student_Id IN Student_Id FROM Student_Course_Table Solution: Make sure your bottom query is passing values to the top query that match. First_Name Dept_No IN (SELECT Dept_No FROM Department_Table . The SQL Quick Reference Guide Page 33 . SELECT <column. WHERE Dept_Name LIKE ‘Sale%’) Teradata allows a maximum of 63 subqueries in one SQL statement. SELECT * FROM Student_Table WHERE (SELECT WHERE Credits > 3). You can have multiple subqueries in a query. The main indicator of a subquery is the WHERE IN or WHERE NOT IN clause..<column-name> ] FROM <table-name> [ WHERE <column-name>[…. Last_Name. Normal Subqueries run the bottom query first which passes a list of values to the top query. Make sure you have the bolded areas a Primary Key in one table and a Foreign Key in another table. Each subquery passes a list of values to be used by the query above..... 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. <column-name> ] ). Here is an example of a correct subquery.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.name> [..

name> [ WHERE <column. 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’)) . This flexibility in SELECT Last_Name.The SQL Reference Guide Multiple Subqueries Multiple Subqueries can have as many as 63 separate subqueries Teradata is one more reason why Teradata is the Best in the World! SELECT <column.<column-name>] FROM <table -name> WHERE <column-name>[. When developing code for multiple subqueries. Hint .. <column. Then move to the second ‘(‘ and find its partner ‘)’..’.Man Issues: A missing parentheses is one of the most common errors when dealing with subqueries. Solutions: The best means of solving this issue is to start with the first ‘(‘ and find the ‘)’ that is paired with it. The last subquery is performed first and sends the result set to the subquery above it. If there is a ‘(‘ with no pair place a ‘)’ at the end of the SQL before the semi-colon.name> [. keep in mind how they are processed: from the ground up. . <column-name> ] [ NOT ] IN ( SELECT <column-name> […. expected something like an ‘EXCEPT’ keyword or an ‘UNION’ keyword or a ‘MINUS’ keyword or ‘)’ between ‘)’ and ‘. Page 34 The SQL Quick Reference Guide ... )). Always be sure that each ‘(‘ has a matching ‘)’ in the SQL.name>[….. The error for a missing parentheses may look like this: 3707: Syntax error. <column-name> ].name> [ NOT ] IN ( SELECT <column-name> [….<column-name> ] FROM <table. and continue this process until all the ‘(‘ have a paired up ‘)’.<column-name> ] FROM <table-name> [ WHERE <column-name>[…..

<column-name> ] { = | > | < | >= | <= | <> } {ANY | ALL } ( SELECT <column-name> […. SELECT Customer_Name.name> [ WHERE <column.name> [..<column-name>] FROM <table -name> WHERE <column-name>[.name>[….name> ] ).. Phone_Number FROM Customer_Table WHERE Customer_Number = ANY (SELECT Customer_Number from Order_Table) .Man The SQL Quick Reference Guide Page 35 .. The = ANY quantifier is the equivalent to IN. Hint .Simplicity by Design Quantifiers These symbols serve as replacementsfor the IN or NOT IN clause. <column. as NOT = ALL is equivalent to NOT IN... SELECT <column.<column-name> ] FROM <table.. English: The above query SELECTS two columns from the Customer_Table if the customer has placed an order in the Order_Table.

Notice the aliasing in the example.alias> ] WHERE <table1-alias>.<column-name> ] FROM <table-name1> [ AS <table1-alias>] WHERE <column-name> { = | < | > | <= | >= | <> } ( SELECT { MIN | MAX | AVG }(<column-name>) FROM <table-name2>[AS <table2. refer to Appendix E. It reads one row in the main query. Then it reads the second row.Dept_No). Page 36 The SQL Quick Reference Guide . That correlates the top and bottom queries together.The SQL Reference Guide Correlated Subquery A correlated subquery works backwards compared to regular subqueries. *For more information on Table -Aliasing. First_Name. SELECT Last_Name. Hint . then performs the subquery and returns the top row if it meets the criteria from the bottom query.<column-name> ) . Solutions: The solution is to place one of the aggregate functions in the subquery. Dept_No.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.name> [. and so forth. The last WHERE clause will compare a value from the top query with a value from the bottom query. This type of subquery performs quite efficiently in Teradata and is extremely powerful.. SELECT <column.<column-name>=<table2-alias>.Dept_No = emt.. Salary emp FROM Employee_Table as WHERE Salary = (SELECT MAX(Salary) FROM Employee_Table as emp. WHERE emt You can recognize a correlated subquery by the WHERE clause in the bottom query..

Solutions: Search for the end of the subquery which is indicated by the ‘)’ and remove the semi-colon inside the ‘)’.Man Issues: 3707: Syntax error. SELECT <column.Customer_Number = OT.alias>...’.<column-name> ] FROM <table.. .name> [. The SQL Quick Reference Guide Page 37 .. SELECT Course_Name FROM Course_Table AS Course WHERE NOT EXISTS (SELECT * FROM Student_Course_Table AS STU WHERE COURSE.Course_Id = STU.. English: The above selects the Customer_Name if a customer has placed a current order.<column.Course_Id) English: The above selects the Course_Name if no students are enrolled..name1> [AS <table1-alias>] WHERE [ NOT ] EXISTS ( SELECT <column-name> [.Simplicity by Design Exists Using this syntax allows for Teradata to perform a true -false test within the WHERE clause .Customer_Number) . SELECT Customer_Name FROM Customer_Table AS CUST WHERE EXISTS (SELECT * FROM Order_Table AS OT WHERE CUST. This error will be produced when there is an unneeded semi-colon inside the subquery.name> [AS <table2-alias>] WHERE <table1.<column-name> ] FROM <table.<column-name> = <table2-alias>. This is great SQL to use for testing queries prior to putting them into production. The system will return either one or zero rows to satisfy the test. You can use EXISTs to see if certain values exist in the database. Hint .name>) . expected something like an ‘EXCEPT’ keyword or an ‘UNION’ keyword or a ‘MINUS’ keyword or ‘)’ between ‘)’ and ‘.

SELECT STU. WHERE emp.]<column-name> = [<table2-alias>. In many cases you can look at the two tables and pick the columns that have the same name in both tables. First_Name.name> [.Course_Id = STU_COUR.]<column-name> ] [ … AND [<table1-alias>. Dept_Name.<column-name> ] FROM <table-name> [ AS <table1-alias> ] ..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. dept. Last_Name. First_Name. SELECT [<table..Course_Id English: The above example joins 3 tables together..Dept_No English: The above example SELECTS 3 columns from the Employee_Table and two columns from the Department_Table and joins them together. Hint .]<column-name>= [<table2-alias>.<table. Student_Course_Table AS STU_COUR WHERE STU.Student_Id.name>.Dept_No = dept. Course_Name FROM Student_Table AS STU. Department_Table AS dept .name>.]<column. SELECT Employee_No. AND COUR. The best technique is to make sure that the columns in the WHERE or ON clause have a Primary Key Foreign Key relationship.<table-name> [ AS <table2-alias> ] [ { WHERE [<table1-alias>.Student_Id = STU_COUR. Notice the WHERE clause joins the Student_Table with the Student_Course_Table and then the Course_Table with the Student_Course_Table. Last_Name. The most complex part of any join is the WHERE or ON clause. Course_Table AS COUR. Teradata is brilliant at performing joins.Dept_No FROM Employee_Table AS emp. Quite often they will have the same name. The Student_Course_Table is called an associative table.Man Page 38 The SQL Quick Reference Guide .]<column-name> ] [ { … AND | OR } <column-name = <data-value> ] | WHERE <column-name = <data-value> } ] .Student_Id .

There is a need to qualify one of the columns in the syntax. To eliminate this ambiguity we need to find the column that exists in two or more of the tables.Dept_No (In bold). We can do this by running a ‘SHOW TABLE <table -name>’ for each table involved in the join. 3809: Column ‘<column -name>’ is ambiguous.Dept_No. and qualify it to determine from which table you want the values. This will display all the columns of each table and allow the user to find the column that is shared between any of them. locate that column. This is caused by a column that exists in two or more of the tables involved in the join. Dept_Name FROM Employee_Table as E. After finding that column return to the original join SQL. You are probably aliasing a table and not consistently using the alias for that table throughout the query. Teradata sees tables E. The SQL Quick Reference Guide Page 39 . Department_Table as D WHERE E. and Employee_Table. Once you alias a table in the FROM clause that alias applies to the table everywhere.Dept_No or Teradata thinks we are trying to join three tables. D.Dept_No = D. SELECT Employee_Table .Simplicity by Design Issues: An ambiguous column name in the SQL exists. Since we have aliased the Employee_Table as E we needed to SELECT E. Solutions: The above query would be a problem because we are SELECTING Employee_Table.Dept_No. Solutions: Issues: You are getting back way more rows than expected . For example.

name> ] ] FROM <table-name> [AS <table1-alias>] [INNER] JOIN <table-name> [AS <table2-alias>] ON [<table1-alias>. WHERE Budget > = 500000 Notice the difference in syntax from the Original syntax. EMP.]<column-name> = [< {table1 | table2} . SELECT [<table. This Syntax makes it easier to avoid those unwanted Product Joins. Hint .. emp.]<column-name> [ … AND [<table1-alias>.. Course_Name FROM Student_Table AS STU INNER JOIN Student_Course_Table AS STU_COUR ON STU. First_Name.name> [ [.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.Course_Id SELECT Mgr_No. and the ON clause overwrites the WHERE clause.Mgr_No . First_Name FROM Employee_Table AS EMP INNER JOIN Department_Table AS DEPT ON EMP.]<column-name>=[<table2-alias>.name> = [<table2.Student_Id INNER JOIN Course_Table AS COUR .Dept_No ON SELECT STU. 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 the ON Clause instead of the WHERE clause.name>.]<column-name> ] [ [INNER] JOIN <table. Dept_Name.]<column.Course_Id = COUR. Last_Name.<table. ON STU_COUR.alias>. SELECT Employee_No.Student_Id = STU_COUR.alias>.]<column. Last_Name.. The two main changes are that INNER JOIN replaces the comma separating the tables in the FROM clause.Dept_No = dept. First_Name.]<column.name> [AS <table3-alias> ] ON [<table3. Last_Name.name>.]<column-name> .Student_Id. Dept_No FROM Employee_Table AS emp INNER JOIN Department_Table AS dept .alias>.Employee_No = DEPT.Man Page 40 The SQL Quick Reference Guide .

Dept_No FROM ON Employee_Table AS emp INNER JOIN Department_Table AS dept emp. We can do this by running a ‘SHOW TABLE <table -name>’ for each table involved in the join.Dept_No or Dept. locate that column. 3809: Column ‘<column -name>’ is ambiguous.3809: Column Dept_No is ambiguous. The SQL Quick Reference Guide Page 41 . This is caused by a column that exists in two or more of the tables involved in the join. Dept_Name. This will display all the columns of each table and allow the user to find the column that is shared between any of them. Solutions: To eliminate this ambiguity we need to find the column that exists in two or more of the tables.Dept_No Error . There is a need to qualify one of the columns in the syntax. After finding that column return to the original join SQL. English: The problem with the above query is that the Dept_No (in bold) is in both tables involved in the join.Dept_No. and qualify it to determine from which table you want the values.Dept_No = dept. Because the system does not know which Dept_No we mean we need to qualify Dept_No.Simplicity by Design Issues: An ambiguous column name in the SQL exists. SELECT Employee_No. First_Name. This could have worked had we stated either emp. Below is an example. Last_Name.

SELECT Employee_No.. 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. First_Name. Page 42 The SQL Quick Reference Guide .<table. EMP. SELECT [<table.Dept_No .name>. It is recommended to avoid this situation because 99% percent of the time this is a bad idea. The results will be garbage.name> [.<table-name> [ AS <table2-alias> ] . FROM Employee_Table AS EMP.]<column. Last_Name.The SQL Reference Guide Cartesian Product Join A Cartesian Product join contains no “WHERE” clause .<column-name> ] FROM <table-name> [ AS <table1-alias> ] .name>... Dept_Name.

]<column.]<column-name> [ WHERE <condition.Man SELECT Employee_No. There are LEFT. Customer_Number.Customer_Number . the Department_Table will be returning all of its rows.. It will join matching rows from the joining table just like an inner join.Phone_Number FROM Customer_Table AS CUST LEFT OUTER JOIN Order_Table AS ORD ON CUST.name> FROM <table.]<column. looking for matches in the Employee_Table based on the Dept_No defined by the ON statement.Dept_No = DEPT.]<column-name> = [<table-name>.test> ] . but put NULL values for all columns of the inner table if there is not a match.name>.Dept_No FROM Employee_Table AS EMP RIGHT OUTER JOIN Department_Table as DEPT ON EMP. 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. SELECT ORD.name>] ON [<table-name>..name>.alias. Last_Name. DEPT. In the Left Outer Join. Hint . the Customer_Table will be returning all of its rows. In the Right Outer Join.Man The SQL Quick Reference Guide Page 43 .name> [.Dept_No . RIGHT and FULL Outer Joins. Customer_Name .<table.. SELECT [<table.name> [AS <table1-alias-name>] {LEFT | RIGHT | FULL} [OUTER] JOIN <table -name> [AS <table2.Simplicity by Design ANSI OUTER JOIN Syntax Outer Joins return all rows from the outer table. Hint . looking for matches in the Order_Table based on the Customer_Number defined by the ON statement.Customer_Number = ORD.

After finding that column return to the original join SQL. and qualify it to determine from which table you want the values. locate that column.The SQL Reference Guide SELECT Last_Name. looking for matches in each table based on the Customer_Number defined by the ON statement.Man Issues: An ambiguous column name in the SQL exists. Solutions: To eliminate this ambiguity we need to find the column that exists in two or more of the tables. both the of its rows. There is a need to qualify one of the columns in the syntax. First_Name. We can do this by running a ‘SHOW TABLE <table -name>’ for each table involved in the join. Course_Id FROM Student_Table AS STU FULL OUTER JOIN Student_Course_Table AS STU_COUR ON STU. Hint . This will display all the columns of each table and allow the user to find the column that is shared between any of them. Page 44 The SQL Quick Reference Guide . This is caused by a column that exists in two or more of the tables involved in the join.Student_Id .Student_Id = STU_COUR. Customer_Table and the Order_Table will be returning all In the Full Outer Join. 3809: Column ‘<column -name>’ is ambiguous.

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..test> ] .]<column. Both a Product Join and a Cartesian Product Join will compare every row from a table with every row from another table.name> [[.<table.Customer_Number. The SQL Quick Reference Guide Page 45 . SELECT [<table..]<column.alias>] [WHERE <condition.Simplicity by Design CROSS JOIN Syntax Cross. CUST..Joins are the ANSI equivalent of a Product Join .name>. SELECT Customer_Name.name>. Order_Total FROM Customer_Table AS CUST CROSS JOIN Order_Table AS ORD WHERE Order_Total < 10000 .name> ] FROM <table.name> [AS <table1-alias>] CROSS JOIN <table -name> [AS <table2.

but how Teradata displays the data. Teradata stores data on disk with the formula below. 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). 2002 = 770112 1020824 INTEGERDATE Formula This is the default display format for most Teradata client utilities. The INTEGERDATE has nothing to do with how Teradata stores the data. 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.Man Page 46 The SQL Quick Reference Guide . The exception is Queryman. but is the default display format for client utilities.The SQL Reference Guide Date and Time Processing Teradata has date functionality built into the database. ((Year – 1900) * (10000)) + (Month * 100) + Day Example: January 12. The IntegerDate is NOT how Teradata stores dates on the physical disks. It is in the form of YY/MM/DD. Hint . Because Queryman uses ODBC as a standard Queryman will display the date format in ANSI format. 1977 = August 1.

Man The SQL Quick Reference Guide Page 47 .Man SELECT Current_Date. ANSI Standard. Teradata Extension. Returns result in yyyy-mm-dd format. Hint . yy/mm/dd format SELECT DATE . Hint . Returns result by default in yy-mm-dd format.Simplicity by Design Selecting the DATE These functions return the present date in .

<number-of-months>) FROM <table.The SQL Reference Guide ADD_MONTHS Function Teradata gives a user the ability to calculate a new date. Solutions: In the ADD_MONTHS function place a comma in between the <date -column> and the <number-of-months>. SELECT ADD_MONTHS(<date-column>. ADD_MONTHS(Date. The ADD_Months can utilize multiplication. Hint . English: The above examples will take the date from the column values (inside parenthesis) and add or subtract months. SELECT ADD_MONTHS(Order_Date. -2) FROM Sales_Table . For example. The calendar has intelligence built -in for the number of days in a month as well as leap year.’ between the word ‘<date -column>’ and the integer ‘<number-of-months>’. SELECT ADD_MONTHS(Sale_Date. This is a Teradata extension function. expected something like “’||’” or ‘. This date can be the future with addition or past with subtraction. This error will be returned when there is no comma between the <date -column> and the <number-ofmonths>. 3) FROM Order_Table .Man Issues: 3707: Syntax error.name> . 12*10) would bring back the date plus 10 years. Page 48 The SQL Quick Reference Guide .

EXTRACT(Day FROM order_date) SELECT EXTRACT(Hour FROM ’06:35:22’) . SELECT EXTRACT(Year FROM order_date) FROM Order_Table . MINUTE. SELECT EXTRACT(Second FROM ’06:35:22’) .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.name> . or DAY from a date or HOUR. SECOND from the time. EXTRACT(Month FROM order_date) SELECT FROM Order_Table . The SQL Quick Reference Guide Page 49 . SELECT FROM Order_Table . MONTH. SELECT EXTRACT(<date/time-segment> FROM <date/time -data>) FROM <table. SELECT EXTRACT(Minute FROM ’06:35:22’) .

Return format is ‘yyyy. Solution: Edit the SQL by placing a ‘_’ between the end of ‘current’ and the beginning of ‘time’ with no spaces. Hint . ANSI Standard.Man Issues: 3822: Cannot resolve column ‘currenttimestamp’. Solution: Edit the SQL by placing a ‘_’ between the end of ‘current’ and the beginning of ‘timestamp’ with no spaces. Specify table or view. SELECT TIME .Man Issues: 3822: Cannot resolve column ‘currenttime’. Specify table or view. Current_Timestamp returns the date and time in the ‘yyyy-mm-dd HH:MM:SS’ format. Returns time in hours:minutes:seconds. ANSI Standard Equivalent to TIME. If Teradata returns this error the underscore ( ‘_’ ) character is missing in the syntax. SELECT CURRENT_TIMESTAMP . Hint . A Teradata Extension Function. Hint .mm.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. Page 50 The SQL Quick Reference Guide .Man SELECT CURRENT_TIME . If Terada ta returns this error the underscore ( ‘_’ ) character is missing in the syntax.dd hh:mm:ss’. Returns time in hours:minutes:seconds.

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 . sequential week number within a month. Calendarview for the system table Column Name Data Type Description _ calendar_date DATE Standard Teradata date Equivalency: DATE day_of_week BYTEINT 1-7.DATE) MOD 7 day_of_month BYTEINT 1-31. 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. 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. some months have less Equivalency: DATE MOD 7 day_of_year SMALLINT 1-366.calendar . sequential week number within a year. etc Equivalency: None known week_of_month BYTEINT 0-5.101(date) weekday_of_month BYTEINT The sequence of a day within a month.Simplicity by Design System Calendar Columns The following is a list of all the columns in the sys_calendar.calendar . each quarter has 3 months Equivalency: CASE EXTRACT Month month_of_year BYTEINT 1-12. partial week starts at 0 Equivalency: None known week_of_year BYTEINT 0-53. The SQL Quick Reference Guide Page 51 . where 1 is Sunday Equivalency: (DATE .calendar. WHERE calendar_date = 1020801 SELECT quarter_of_year WHERE calendar_date = current_date FROM sys_calendar. second Sunday=2. first Sunday=1. 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.

value> ] . Teradata will return an error message that looks like this: 3580: Illegal use of CHARACTERS. Customer_Name FROM Customer_Table WHERE Customer_Number IS NOT NULL ORDER BY 1 . If this column is not of a character data type it is necessary to choose a different column to run the CHARACTERS function on. Dept_Name Characters(Dept_Name) ___________ ___________________ Sales 5 SELECT CHAR(TRIM(Customer_Name)) . FROM Department_Table . Solutions: The first step is to execute the ‘SHOW TABLE <table -name>’ syntax for the table where the column in question resides. Check the data type. This function is most often used with VARCHAR strings.name> [ WHERE CHARACTERS( <column-name> ) <comparison> <data.The SQL Reference Guide Character String Processing CHARACTERS Function Counts the number of characters in a string. or OCTET_LENGTH functions. Issues: A column may not be a character data type. When using the Characters function on fixed length columns it should be combined with the TRIM function. Page 52 The SQL Quick Reference Guide . If used with CHARACTER strings it will return the length of the column because it counts the spaces. This is done because Customer_Name is a fixedlength character data type and not a varchar. 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. SELECT Dept_Name. English: The above example will TRIM the leading and trailing spaces from the Customer_Name first and then count the number of characters. CHARACTERS(Dept_Name) English: The above example selects Dept_Name and the number of Characters in the Dept_Name for all rows in the Department Table. MCHARACTERS. SELECT CHARACTERS( <column-name> ) FROM <table.

TRIM(LEADING FROM Last_Name) . SELECT TRIM(TRAILING FROM Course_Name) FROM Course_Table . SELECT FROM Employee_Table . The default for TRIM is BOTH.name> . The SQL Quick Reference Guide Page 53 .Simplicity by Design TRIM Function TRIM removes the extra spaces from the front. LEADING. First_Name SELECT FROM Student_Table . SELECT TRIM( {TRAILING | LEADING | BOTH } FROM <column-name> ) FROM <table. English: The above examples will either TRIM the TRAILING. This will default to BOTH. back. or on both ends of a fixed length character string. TRIM(BOTH FROM First_Name) SELECT TRIM(Customer_Name) FROM Customer_Table . Notice in the last example we don’t specify LEADING or TRAILING. or BOTH TRAILING and LEADING spaces from fixed-length character columns.

otherwise an error will occur .name>.location> [ FOR <length> ] ) FROM <table. This error will come back if single quotes are missing. The <length> specified must be positive a number. 2 . SELECT SUBSTR(‘Teradata’. Issues: String literals must have single quotes around them. <length> ] ) FROM <table. Page 54 The SQL Quick Reference Guide . 5 ) . This error will occur when the Solutions: To remove this problem. 3 . <length> in the SQL is a negative number. 4) FROM Course_Table .The SQL Reference Guide SUBSTRING and SUBSTR Functions Both of these functions serve the purpose of returning a desired section of a character string. SELECT SUBSTRING(‘Teradata’ FROM 2 FOR 5) . SELECT SUBSTRING( <column-name>FROM <start. SELECT SUBSTRING(Course_Name FROM 3 FOR 4) FROM Course_Table . <start-location> [ . simply choose a non-negative number to place in the <length> parameter.name> . Specify table or view. A user chooses the starting position and then how many characters to pull out of the string.name>. SELECT SUBSTR(Course_Name. English: The last example will return a result of: erada SELECT SUBSTR ( <column. Solutions: The solution is to locate the <string-literal> and place single quotes around it. English: The last example will return a result of: erada Issues: 2662: SUBSTR: string subscript out of bounds. 3822: Cannot resolve column ‘<string-literal>’.

An example would be SELECT SUBSTRING(‘Teradata’. FROM Start Position for End Position). It is recommended to use the ANSI standard function. An example would be: SELECT SUBSTRING(‘Teradata Class’.Simplicity by Design POSITION and INDEX Functions Teradata will return the actual place number of where the <character. English: The last example would return the position of a in Teradata which would be 4. That number would actually be 9.Man POSITION is often used with the SUBSTRING function. This returns the word ‘Class’. Hint . Think about the SUBSTRING syntax: SELECT SUBSTRING(Column. POSITION(‘ ‘ in ‘Teradata Class’) + 1. SELECT POSITION(‘e’ IN Course_Name) . Course_Name FROM Course_Table . The SQL Quick Reference Guide Page 55 . Teradata will return a ‘4’ when running the second example query.name> ) FROM <table. which is POSITION in this case. 5) The above would take the literal ‘Teradata Class’ and find the position of the first ‘ ‘. 5 for 4) which returns the string ‘data’.string> first occurs in the values of <column-name>. FROM 10 for 5). SELECT POSITION( <character-string> IN <column.name> . So the actual SUBSTRING would actually be converted to: SELECT SUBSTRING(‘Teradata Class’. Then the system would add one to it making it 10. POSITION can be substituted inside the SUBSTRING for Start Position or End Position. SELECT POSITION(‘a’ IN ‘Teradata’) .

The SQL Reference Guide INDEX Function Teradata will return the actual place number of where the <character. When choosing to use an ANSI Standard function or the Teradata Extension Equivalent.Man Issues: String literals must have single quotes around them. INDEX(Course_Name . SELECT INDEX( <column. Hint . <character. Specify table or view.name> . SELECT FROM Course_Table .string> ) FROM <table. Equivalent Teradata Extension to the ANSI Standard POSITION function. it is recommended to use the ANSI Standard Function. Page 56 The SQL Quick Reference Guide . Solution: Place single quotes around the literal in question. ‘e’) SELECT INDEX(‘Teradata’ . This error will come back if single quotes are missing: 3822: Cannot resolve column ‘<string-literal>’.string> first occurs in the values of <column-name>.name> . ‘a’) .

Man The SQL Quick Reference Guide Page 57 .name> . SELECT ‘<character-data>’ || ‘<character-data>’AS <alias> FROM <table. If the value in Class_Code was ‘FR’ then the result set would be: ‘FR’ Class. Hint . In both examples above the queries are selecting only one column because the columns are concatenated. SELECT First_Name || Last_Name AS Full_Name FROM Employee_Table WHERE Salary <= 40000 . Flexible in terms of mixing column data with literal strings. SELECT FROM Student_Table . Class_Code || ‘ Class’ AS Class English: The last example above will take the value in Class_Code and concatenate the value with the word ‘ Class’.Simplicity by Design String and Column Concatenation Concatenation is a very powerful feature that allows a user to combine two or more columnsin the result set to make reporting easier to read. Using concatenation with a string literal is permissible as well.

Once the data is sorted by Order_Date Teradata will do a cumulative sum on Order_Total. Then it calculates the OLAP requested only after the data is sorted. but before the calculation takes place Teradata will SORT the data by Order_Date. OLAP is different than aggregates. Order_Total. Read on and you will understand. While aggregates only return one line of aggregate data OLAP functions can have detail data mixed with OLAP functions. It will also perform an OLAP function on the Order_Total. Page 58 The SQL Quick Reference Guide . OLAP can be thought of very easily if you follow this logic. Order_Date) English: The above query will SELECT the Order_Number and Order_Total from the Order_Table. The Order_Date (in bold) is the Sort Key. Each OLAP function will have a built in sort key. There are a few major points that need to be discussed that encompass all of the OLAP tools. but they are tools built into Teradata to give programmers the ability to analyze business trends and mine data into very granular reports. NEVER use the ORDER BY statement with OLAP because all sorts are done inside the Parenthesis of the OLAP function. SELECT Order_Number. The OLAP query actually sorts the data by the OLAP function inside the parenthesis first. not only are a Teradata Extension. OLAP sorts the data first by the sort key or keys inside the OLAP parenthesis and then and only then does the OLAP calculations. FROM Order_Table . Below is an example of a Cumulative SUM OLAP query. Remember. CSUM(Order_Total.The SQL Reference Guide OLAP Functions OLAP Functions.

be sure to include that same column as a <sort. which is called a major sort.column. Last_Name. Order_Total.<relative.] ] SELECT Order_Number.number> … . The CSUM column in the result set will show the running calculation through the rows that are arranged according to the first <sort. Solutions: It is essential to select at least one sort-key. GROUP BY will reset the Cumulative Sum calculation. Remember that when using the GROUP BY clause.name> [.key>..Man The GROUP BY clause resets the Cumulative Sum total.key>. Order_Date) FROM Order_Table . In the second example the CSUM will be reset for every Department Number in the Employee Table. CSUM(Salary.Simplicity by Design Cumulative Sum Function (CSUM) CSUM performs a cumulative sum on all the rows in the given <column-name>. <sort -key> [ASC | DESC] [..name> [GROUP BY <column. It would be best to run a ‘SHOW TABLE <table -name>’ to get a list of the columns to choose from. FROM Employee_Table GROUP BY Dept_No . Then place the desired column in the <sort-key> part of the CSUM syntax. SELECT Dept_No. SELECT CSUM( <column-name>. 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 ‘)’. The <sort -key> default for ordering is ASCENDING. Salary.. The SQL Quick Reference Guide Page 59 .... <sort -key> [ASC | DESC] … ) FROM <table. Dept_No) Hint . CSUM(Order_Total.

Order_Total. 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 ‘)’.<relative -column. SELECT MSUM( <column-name>. This <width> serves as a sliding window of which rows to include in the calculation. Sale_Date.number>] ] .. Product_Id) FROM Sales_Table GROUP BY Product_Id . English: The example above will first sort the data by Product_Id. Order_Date) FROM Order_Table .name> [GROUP BY<column-name> [. Then it will perform a moving sum on Order_Total for every 3 rows. <sort-key> [ASC | DESC] [.. English: The example above will first sort the data by Order_Date. Then it will perform a moving sum on Daily_Sales for every 2 rows. <sort -key> [ASC | DESC] ) FROM <table. SELECT Order_Number.. SELECT Product_Id.. MSUM(Order_Total.. MSUM(Daily_Sales . It would be best to run a ‘SHOW TABLE <table -name>’ to get a list of the columns to choose from. 3. 2 .The SQL Reference Guide Moving Sum Function (MSUM) MSUM adds up the rows in the given <column-name> with a certain <width>based on the moving window. Page 60 The SQL Quick Reference Guide . which is called a major sort. Sale_Date. Then place the desired column in the <sort-key> part of the CSUM syntax. <width>. Solutions: It is essential to select at least one sort-key..

Solutions: It is essential to select at least one sort-key. English: The example above will first sort the data by Order_Date. <sort -key> [ASC | DESC] ) FROM <table. SELECT MAVG( <column-name>.. SELECT Product_Id.Simplicity by Design Moving Average Function (MAVG) Serves as a function tocalculate an average based on the moving <width> .. which is called a major sort. Sale_Date) FROM Sales_Table GROUP BY Product_Id . Sale_Date.<relative -column. 3. <sort -key> [ASC | DESC]) [..name> [GROUP BY<column-name> [. SELECT Order_Number. Then it will perform a moving average on Daily_Sales for every 2 rows. It would be best to run a ‘SHOW TABLE <table -name>’ to get a list of the columns to choose from. 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 ‘)’. English: The example above will first sort the data by Sale_Date... Then it will perform a moving average on Order_Total for every 3 rows.. Order_Total.number> ] ] . Order_Date) FROM Order_Table . MAVG(Order_Total. 2 . Then place the desired column in the <sort-key> part of the CSUM syntax. The SQL Quick Reference Guide Page 61 . <width>. MAVG(Daily_Sales .

<relative -column. 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 ‘)’. 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. Then place the desired column in the <sort-key> part of the CSUM syntax. SELECT Product_Id. <sort-key> [ASC | DESC] ) [. Order_Date) FROM Order_Table ... <sort -key> [ASC | DESC] ) FROM <table.. It would be best to run a ‘SHOW TABLE <table -name>’ to get a list of the columns to choose from.The SQL Reference Guide Moving Difference Function (MDIFF) The MDIFF functio n behaves a little differently than other OLAP functions. which is called a major sort. Page 62 The SQL Quick Reference Guide . SELECT Order_Number. <width>. 2 . Then it will perform a moving difference on Order_Total for every 3 rows.. Order_Total. MDIFF(Order_Total.. English: The example above will first sort the data by Order_Date.number>] ] . MDIFF(Daily_Sales . English: The example above will first sort the data by Sale_Date. Sale_Date) FROM Sales_Table GROUP BY Product_Id . Solutions: It is essential to select at least one sort-key.. SELECT MDIFF(<column-name>. Sale_Date.name> [GROUP BY<column-name> [. 3. Then it will perform a moving difference on Daily_Sales for every 2 rows.

Daily_Sales.name>. Then it will perform a quantile function on salaries in quantiles of 4. Salary.Simplicity by Design QUANTILE Function This function will divide the result set into a certain <column. Sale_Date ASC) as “Percentile” FROM Sales_Table QUALIFY “Percentile” < 5 .name> . number of <partitions> based on the SELECT QUANTILE (<partitions>. [<sort -key> [DESC | ASC]]) FROM <table. English: The example above will first sort the data by Dept_No in DESC order. QUANTILE(4. QUANTILE(100. [QUALIFY QUANTILE (<column-name>) {< | > | = | <= | >=} <number-of-rows>] SELECT Employee_No. <column-name> . English: The example above will first sort the data by Sale_Date in ASC order. In other words each salary will be assigned a number from 0-3. Dept_No . Dept_No DESC) FROM Employee_Table .Man The SQL Quick Reference Guide Page 63 . Hint . The QUALIFY function is the equivalent to the WHERE and HAVING clauses. Last_Name. 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. It is used when doing QUANTILE Functions. Daily_Sales. SELECT Product_Id.

The query is actually returning the top four selling products.name> [. .<relative.column.The SQL Reference Guide RANK Function Returns the rows of the involved table in ranked a order determined by the <column-name>. English: The above example will RANK the Daily_Sales in DESC order. Daily_Sales and Rank of Daily_Sales ordered by RANK of Daily_Sales if the rank is less than 5. Page 64 The SQL Quick Reference Guide ... SELECT Product_Id. RANK(Daily_Sales DESC) as Ranking FROM Sales_Table QUALIFY Ranking < 5 .The default order for RANK is DESCENDING or DESC.number> ] ] [ { ASC | DESC } ] [QUALIFY RANK(<column-name>) {< | <=} <number-of-rows> [DESC | ASC] ]. English: The above example will RANK the salaries in asc order. The query will return the Employee_Id. Daily_Sales. Last_Name. and Salary Rank in ascending order by Salary Rank. Last_Name. SELECT RANK( <column-name> [DESC | ASC] ) FROM <table. FROM Employee_Table SELECT Employee_No. Dept_No. Dept_No RANK(Salary ASC) GROUP BY Dept_No . The query will return the Product_Id.name> [GROUP BY <column..

English: A Sample of 25% rows. One sample is for 800 rows. This issue appears only when dealing with percentages..<number-of-rows> | <percentage> ] SELECT Customer_Name. This will take care of the error.SAMPLEID ] FROM <table. 5473: SAMPLE Clause has invalid set of arguments.. Phone_Number FROM Customer_Table SAMPLE 3 .. Daily_Sales. 4 . English: Two samples of 4 rows. and the second sample being 300 rows. FROM Sales_Table SAMPLE 4 . When requesting a concrete number of rows to be returned in a sample. The sample size is determined by either a number of rows. SELECT Course_Name FROM Course_Table SAMPLE . The second sample will only have 200 rows returned because in SAMPLE there are no repeats in the same SQL statement!! SAMPLEID Hint . The SQL Quick Reference Guide Page 65 .33.name> SAMPLE { <number-of-rows> | <percentage> } .. SELECT Sale_Date. English: A Sample of 3 rows.Man Issues: More than 100% of result set wanted for Sample or multiple samples.name> | * } [.<column-name> ] [. or percentage of rows. SAMPLEID shows the user from which sample a certain row is in.. SELECT { <column. Suppose a user decides to take two samples from a 1000 row table. For example if you are currently attempting to get three samples of .. Solutions: The key is to adjust the sampling percentages to a proper total. the actual number of rows in the table should be taken into account.50 each.Simplicity by Design SAMPLE Function and SAMPLEID SAMPLE returns a random sample of the result set of the given SQL statement . [. adjust the percentages to .25 .

The SQL Reference Guide RANDOM Function Returns a random number between the<low-literal-value> and the <high-literal-value>. English: Randomly Select 2% of the rows from the table. 150) . SELECT RANDOM( <low. Page 66 The SQL Quick Reference Guide . <high.100) = 2 . SELECT RANDOM(10. SELECT * FROM Employee_Table WHERE RANDOM(1. English: SELECT a random number between 10 and 150.literal-value>.literal-value> ).

Each SELECT statement involved must contain the same number of columns as the others. The First Select statement formatsthe results and defines aliases and titles for column output. EXCEPT/MINUS. 4.Simplicity by Design Set Operator Commands The SET Operators are UNION. 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. refer to “Teradata SQL: Unleash the Power”. Here is an example: SELECT Employee_No from Employee_Table INTERSECT SELECT Mgr_No from Department_Table. UNION. 2. Chapter 11. EXCEPT/MINUS. 3. All corresponding columns must be of the same domain. EXCEPT and MINUS are the same commands. When using multiple set operators in one statement the order of operations is as follows: INTERSECT.Man The SQL Quick Reference Guide Page 67 . For a more detailed list of guidelines on using Set Operators. The Last SELECT contains the ORDER BY clause for the entire SQL statement. This order holds true unless parentheses are used to manipulate the order. The SET operators will run two queries at once and combine the result sets together. Hint . which means that their da ta types and ranges of values must match. INTERSECT.

<column-name> … ] FROM <table -name> INTERSECT [ ALL ] SELECT <column.name> [. Solutions: The best way to find matching data types is to run ‘SHOW TABLE <table -name>’ for both tables you would like to intersect. These are the columns you may use in the intersect. INTERSECT ALL is not a valid function for Teradata Versions earlier than Version 2 Release 4. No duplicate rows will be returned in the result set unless the ALL keyword is used to include duplicate rows (when they exist). Page 68 The SQL Quick Reference Guide . SELECT Customer_Number AS Customers_with_Orders FROM Customer_Table INTERSECT SELECT Customer_Number FROM Order_Table ORDER BY 1 DESC.name> [. SELECT <column.<column-name> … ] FROM <table -name> [ORDER BY <column-name>] . English: The above query returns all Customer_Numbers who have Orders in the Order_Table eliminating any duplicates. English: The above query returns all Student_Ids who have enrolled in courses without eliminating any duplicates. Hint .Man Issues: The columns in the two select statements do not match up in terms of data types. SELECT Student_Id FROM Student_Table INTERSECT ALL SELECT Student_Id (TITLE ‘Students_With_Courses’) FROM Student_Course_Table. Search through the DDL and locate the columns that match up properly.The SQL Reference Guide INTERSECT The INTERSECT operator matches like values from two sets of rows similar to an INNER JOIN. 3654: Corresponding select-list expressions are incompatible.

Issues: The columns in the two select statements do not match up in terms of data types. No duplicate rows will be returned in the answer set unless the ALL keyword is used to include any existing duplicate rows. English: The above query returns all Student_Ids from both tables eliminating any duplicates. The SQL Quick Reference Guide Page 69 .Simplicity by Design UNION UNION is a function that stacks one result set on top of the second result respectively. These are the columns you may use in the union. SELECT Student_Id (TITLE ‘All Students – No Duplicates’) FROM Student_Table UNION ALL SELECT Student_Id FROM Student_Course_Table. 3654: Corresponding select-list expressions are incompatible. Search through the DDL and locate the columns that match up properly. English: The above query returns all Student_Ids from both tables and does not eliminate any duplicates. Solutions: The best way to find matching data types is to run ‘SHOW TABLE <table -name>’ for both tables you would like to intersect.<column-name> … ] FROM <table -name> UNION [ ALL ] SELECT <column.<column-name> … ] FROM <table -name> [ORDER BY <column-name>].name> [.name> [. SELECT Student_Id (TITLE ‘All Students – No Duplicates’) FROM Student_Table UNION SELECT Student_Id FROM Student_Course_Table. SELECT <column.

SELECT Student_Id (TITLE 'Students w/o Courses . No data in the Student_Course_Table can ever be in the answer set. SEL Student_Id (TITLE 'Students w/o Courses – Dups incl. Page 70 The SQL Quick Reference Guide .<column-name> … ] FROM <table -name> EXCEPT [ALL] SELECT <column.name> [. English: The above query returns all Student_Ids from the top query (Student_Table) only. Issues: The columns in the two select statements do not match up in terms of data types. Search through the DDL and locate the columns that match up properly. It will then eliminate any Student_Id from the top spool if they are in the Student_Course_Table. Solutions: The best way to find matching data types is to run ‘SHOW TABLE <table -name>’ for both tables you would like to intersect. 3654: Corresponding select-list expressions are incompatible. These are the columns you may use in the except. English: The above query returns all Student_Ids from the top query (Student_Table) only.name> [. It will then eliminate any Student_Id from the top spool if they are in the Student_Course_Table. SELECT <column. All duplicates in the top query only are eliminated. No duplicate rows will be returned in the answer set unless the ALL keyword is used to include any existing duplicate rows.No Dups') FROM Student_Table EXCEPT SELECT Student_Id FROM Student_Course_Table.<column-name> … ] FROM <table -name> [ORDER BY <column-name>] . All duplicates in the top query are NOT eliminated.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.') FROM Student_Table EXCEPT ALL SEL Student_Id FROM 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. No data in the Student_Course_Table can ever be in the answer set. 3654: Corresponding select-list expressions are incompatible.name> [. No data in the Student_Course_Table can ever be in the answer set. It will then eliminate any Student_Id from the top spool if they are in the Student_Course_Table. Solutions: The best way to find matching data types is to run ‘SHOW TABLE <table -name>’ for both tables you would like to intersect.No Dups') FROM Student_Table MINUS SELECT Student_Id FROM Student_Course_Table. SELECT Student_Id (TITLE 'Students w/o Courses . English: The above query returns all Student_Ids from the top query (Student_Table) only. SELECT Student_Id (TITLE 'Students w/o Courses . English: The above query returns all Student_Ids from the top query (Student_Table) only. The SQL Quick Reference Guide Page 71 .') FROM Student_Table MINUS ALL SELECT Student_Id FROM Student_Course_Table ORDER BY 1 DESC. SELECT <column.Simplicity by Design MINUS The MINUS operator is the ANSI equivalent of its Teradata counterpart EXCEPT . Issues: The columns in the two select statements do not match up in terms of data types.name> [. It will then eliminate any Student_Id from the top spool if they are in the Student_Course_Table. It returns rows from the first result set that do not have matches in the second result set. All duplicates in the top query are NOT eliminated. These are the columns you may use in the minus. No duplicate rows will be returned in the answer set unless the ALL keyword is used to include any existing duplicate rows. Search through the DDL and locate the columns that match up properly.<column-name> … ] FROM <table -name> MINUS [ ALL ] SELECT <column.<column-name> … ] FROM <table -name> [ORDER BY <column-name>].Dups incl.

and what data types they are. 3. Hint .). Issues: Too many values are being inserted in the target table. The command must take in account for every column in the table whether it is with actual data or nulls. 'Smith'. Last_Name='Paul'. 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. .00 ). 'SR'. INSERT INTO Student_Table VALUES ( 999333.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. NULL). INSERT INTO Student_table (First_Name. Take notice of the two ways in which NULL values are inserted (NULL or . Last_Name. Page 72 The SQL Quick Reference Guide . 3706: Syntax error. INSERT INTO Student_table (First_Name='Russel'.Man When using the INSERT command. English: The above examples use multiple ways to INSERT data into the Student_Table. inserting column values in the proper order is essential. 'Jones'. 'Jerry'. The order of values inserted must correspond to the order that the columns are defined in the table unless you name the columns. …] ) . Column name list shorter than value list. INSERT [ INTO ] <table. Student_Id=999111).name> VALUES ( <literal-data-value1> [ . INSERT INTO Student_Table VALUES ( 999444. 999111). There are too many arguments in the Insert statement for the table to handle. 'Jean'. Student_Id) VALUES ( 'Russel'. <literal-data-value2> [. . One you know this information you can edit the SQL to adhere to the structure of the table. 'Paul'. Since the column names are specified in the last two syntax examples in the column order is arbitrary.

Column name list shorter than value list. NULL. 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. INSERT INTO Student_Table VALUES (NULL. The SQL Quick Reference Guide Page 73 . . any default values defined for columns will be inserted in place of nulls. NULL. Issues: The values that are being inserted do not match up properly with the columns in the target table. NULL. . and what data types they are.Simplicity by Design Inserting NULL and Default Values These three statements are ways to insert a row of nulls into the Student table. ) . NULL. The third statement works in Teradata Version 2 Release 3 and l ater. When using this statement. . One you know this information you can edit the SQL to adhere to the structure of the table. INSERT INTO Student_Table VALUES (. 3706: Syntax error. INSERT INTO Student_Table DEFAULT VALUES . . NULL) .

Man Page 74 The SQL Quick Reference Guide . It is very flexible in addition to being great for performance. ) FROM Employee_Table. The above query does an INSERT SELECT into an empty table.name> [ . The first solution would be to look in the SELECT table DDL. . but this is normally not recommended.<column2. First_name. First_name. First_name. This error comes up when there are too many columns in the SELECT table for the target table to handle. The second solution would be to alter the structure of the target table. INSERT INTO New_Employee_Table (Dept_No. SELECT INSERT INTO New_Employee_Table SELECT ( Employee_No. INSERT INTO New_Employee_Table * FROM Employee_Table. Employee_No FROM Employee_Table. Last_name.name> . Because the target table was empty there is no need to take before image pictures with the Transient Journal. Last_name.name> SELECT <column1.The SQL Reference Guide INSERT / SELECT The INSERT/SELECT statement serves as a very fast way to move data from one table to another.name> [ . Hint . …] ] FROM <table2. Employee_No) SELECT Dept_No. Solutions: There are two solutions for this issue. 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. Issues: 3813: The positional assignment list has too many values. INSERT [ INTO ] <table1. INSERT INTO Employee_Table_USA SELECT * FROM Employee_Table_West UNION SELECT * FROM Employee_Table_East. This is a clever trick. with a ‘SHOW TABLE <table -name>’ then adjust the SELECT statement to choose only the columns that match with the target table. Last_name.

UPDATE Employee_Table SET Salary = Salary * 1. The ALL command is completely optional.value> [ .Class_Code = 'JR' WHERE Student_Id = 999333. English: The above query examples are updating.1 All.test> … ] [ OR <condition. Hint . UPDATE Student_table SET Grade_Pt = 2. UPDATE<table -name> [ AS <alias-name> ] [ FROM <table2-name> [AS <alias2-name> ] ] SET <column.test> … ] [ALL] . but the last example gives everyone in the Employee_Table a 10% raise. The top two examples are updating only one row. <column-name> = <expression-or-data-value> … ] [ WHERE <condition.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.Man The SQL Quick Reference Guide Page 75 .data.test> ] [ AND <condition.50 .name> = <expression-or. UPDATE Student_table SET Grade_Pt = Grade_Pt + 1. Teradata would have updated every row in the table for the last example.0 WHERE Last_Name = 'Jones' AND First_Name = 'Jerry' AND Class_Code = 'JR'.

…]] FROM <table. <column.Dept_No = dept. it could be very beneficial to use this syntax. UPDATE<table -name1> [ AS <alias. AND Budget > 500000 Page 76 The SQL Quick Reference Guide .name> [ AS <alias-name> ] [ WHERE <condition.name2> [ .The SQL Reference Guide UPDATE with a Subquery Using a subquery is a very advanced means of updating rows.data. UPDATE Employee_Table SET Salary = Salary * 1.value> [ . <column-name> = <expression-or-data-value> … ] WHERE<column.name> [ . …]] IN ( SELECT <column.name> [.test> … ] ) [ ALL ] .<column.Dept_No .name> = <expression-or.test> ] [ ALL ].]<column-name> [ AND <condition. UPDATE<table -name> [ AS <alias.10 WHERE Employee_Table.name1> ] [ FROM <table -name2> [ AS <alias-name2> ] ] SET <column. UPDATE Employee_Table FROM Department_Table dept SET Sala ry = Salary * 1.value> WHERE[<table -name1>.test> ] [ OR <condition.name> = <expression-or.name2> [ .name> ] [ FROM <table -name2> [AS <alias-name2> ] ] SET <column.10 WHERE Dept_No IN (SELECT Dept_No FROM Department_Table WHERE Budget > 500000) .]<column-name> = [<table -name1>. UPDATE with a Join When a programmer understands his or her data well enough.data.

name> [ AS <alias-name> ] [ WHERE condition ] [ ALL ].0 . The SQL Quick Reference Guide Page 77 . Solutions: Check the spelling of the <table -name>. Issues: The table having rows deleted does not exist. DELETE FROM Student_Table WHERE Grade_Pt < 1.Simplicity by Design DELETE Unlike most databases Teradata has the ability to quickly delete rows from a given table. 3807: Table/view/trigger ‘Student’ does not exist. DELETE FROM Student_Table ALL . 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. then recreate that table. DELETE [ FROM ] <table. It is recommended to delete all rows from a table rather than drop it .

name> [ AS <alias.name2> [ AS <alias.Man Delete with a Subquery DELETE<table . Page 78 The SQL Quick Reference Guide .name> [.name2> [.<column-name> [ AND <condition> ] [ OR <condition> ] [ ALL ].name1> [ FROM <table.name> [ .<column.Dept_No .name>=<table -name1>.name> [ AS <alias-name> ] [ WHERE condition … ] ) [ ALL ]. you may wish to delete rows from a table based on values in another table . …] ] IN ( SELECT <column. Hint .The SQL Reference Guide Delete with a Join On occasion.Dept_No . AND Budget < 400000 DELETE Employee_Table WHERE Employee_Table. …] FROM <table.name> ] ] WHERE<table -name1>.name> ] WHERE<column.Dept_No = Department_Table. <column. DELETE Employee_Table FROM Department_Table AS dept WHERE Employee_Table. DELETE<table . DELETE FROM Employee_Table WHERE Dept_No IN (SELECT Dept_No FROM Department_Table WHERE Budget < 500000) .name2> [. The Delete command can be used with a join or subquery operation to accomplish this task.<column. AND Budget < 400000 Keep in mind when omitting the optional FROM clause an alias cannot be used.Dept_No = dept.

Simplicity by Design UPSERT UPSERT combines UPDATE and INSERT into a single command. locate the word ‘INSERT’ and place ‘ELSE’ before it.name1>. this functionality is present in Queryman and BTEQ as well. If the row does not exist. if Teradata does not find the row in the table it will INSERT the record into the table.1 TPUMP and MULTILOAD could only use this syntax.test> ] ELSE INSERT INTO <table-name> VALUES ( <value -list> ) . English: In the above example we are attempting to UPDATE the Student_Table.<column-name> = <expression> … ] WHERE [<table -name1>. If the row already exists.]<column-name> = [<table .]<column. In Teradata V2R4. however.Man Issues: Missing the ‘ELSE’ before the INSERT statement. book by Larkins and Coffing. then the row will be inserted. 3706: Syntax error: expected something between an integer and the ‘INSERT’ keyword. UPDATE Student_Table SET Grade_Pt = 4. If the UPDATE works the query is done. The SQL Quick Reference Guide Page 79 .0 ) . refer to “Teradata SQL: Unleash the Power”. For a more information on using UPSERT.1 and later.'JR'.4.test> ] [ OR <condition. In Teradata versions prior to V2R4. Hint .'Jasmine'.0 WHERE Last_Name = 'Jones' AND First_Name = 'Jasmine' AND Class_Code = 'JR' AND Student_Id = 555555 ELSE INSERT INTO Student_Table VALUES ( 555555. Chapter 12.'Jones'. then the Update will occur.name> [ AND <condition. UPDATE<table -name> SET <column.name> = <expression> [ . Solutions: In the SQL request.

'JR'. . UPDATE Student_Table SET Grade_Pt = 4. Larkins.The SQL Reference Guide UPSERT for TPUMP and MULTILOAD This UPSERT syntax is to be used in TPUMP and MULTILOAD only .DML LABEL <label-name> DO INSERT FOR MISSING UPDATE ROWS. UPDATE<table -name> SET <column.0 ) .]<column.name> VALUES ( <value.list> ) .]<column-name> = [<table . For more information see the “Teradata Utilities – Breaking the Barriers” by Coffing. Volters and Wilmes.4. Hint . Often users don’t think they need this in Multiload and they do.name> [ AND <condition.'Jasmine'.name1>.Man Page 80 The SQL Quick Reference Guide . INSERTINTO <table.<column-name> = <expression> … ] WHERE [<table -name1>.test> ] . : In the above example you see the statement: Do INSERT for Missing UPDATE rows. Teradata will not recognize the command without the Label and DO INSERT code.name> = <expression> [ . .test> ] [ OR <condition. Jones. This is a required statement and not just a comment.DML LABEL UPSERT1 DO INSERT FOR MISSING UPDATE ROWS.0 WHERE Last_Name = 'Jones' AND First_Name = 'Jasmine' AND Class_Code = 'JR' AND Student_Id = 555555 INSERT INTO Student_Table VALUES ( 555555.'Jones'.

SELECT Last_Name .4.Grade_Pt . SELECT Class_code . Executing a ‘SHOW TABLE <table -name>’ or a ‘HELP TABLE <table -name>’ command will display the information you need to make an educated decision. 2621: Bad character in format or data of Student_table. The SQL Quick Reference Guide Page 81 . equal to zero .Simplicity by Design DATA INTERROGATION NULLIFZERO This Teradata extension returns a NULL value when the column value is This function is helpful with eliminating any division by zeros.<Aggregate>( NULLIFZERO(<column-name> ) ) FROM <table -name> GROUP BY 1. Solutions: The only answer to this problem would be to choose another column that is of numeric data type.Man Issues: The user is attempting to use this function on a non-numeric column. SELECT NULLIFZERO( <column-name> ) . The second example illustrates a good use of the NULLIFZERO Function by eliminating division by zero errors.First_Name . Grade_pt / ( NULLIFZERO(Grade_Pt) * 2 ) AS "Calc" FROM Student_Table ORDER BY 3.Class_Code . Hint .Class_code. NULLIFZERO(Grade_pt) AS "Class AVG" FROM Student_table.

The SQL Reference Guide

NULLIF
An ANSI Statement that compares two values and equal. returns a NULL when the values are

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') FROM Student_Table ORDER BY 1;

Class

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): Hint - Man SELECT COALESCE(HomePhone, WorkPhone,

‘No Phone’);

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

Basic Syntax This is the simplest syntax of all the styles of case statements. Hint . which give the user the choice of how much data interrogation can be performed on the rows. any arguments that do not match any of the criteria will return a NULL value to the result set.Man The SQL Quick Reference Guide Page 85 . the ELSE clause is optional. Last_Name .name> WHEN <value1> THEN <true -result1> WHEN <value2> THEN <true -result2> … [ ELSE <false-result> ] END .Simplicity by Design CASE The CASE statement is a flexible SQL function that provides for multiple levels of testing data. Only tested is this format. If you choose not to use the else. There are a few different styles. CASE Class_Code WHEN 'FR' THEN 'Freshman' WHEN 'SO' THEN 'Sophomore' WHEN 'JR' THEN 'Junior' WHEN 'SR' THEN 'Senior' ELSE 'Not Classified' END "Classification" FROM Student_Table . one column can be SELECT First_Name . CASE <column. In a case statement.

SELECT First_Name || ' ' || Last_Name .result2> … [ ELSE <false-result> ] END . 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. Both syntaxes allow for an alternative result when all values/conditions evaluated are false. Hint .test2> THEN <true. which can test more CASE WHEN <condition. SELECT First_Name || ' ' || Last_Name .Salary . various conditions .Man Page 86 The SQL Quick Reference Guide . Then the Class_Code will be inte rrogated and the proper literal will be placed in the report.result1> WHEN <condition.The SQL Reference Guide Advanced Syntax This advanced syntax returns results based on than one columnif desired.test1> THEN <true. 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. Knowledge of your data and business rules is critical to properly utilize the CASE statement. The alias is called “Classification”. English: The above query example will concatenate the First_Name and Last_Name together with a space in between.

If there were four departments then there would be four rows in the answer set. The above query delivers a one -line answer set. Normally a query such as this will be performed showing the Dept_No and AVG(Salary) and grouping by Dept_No.50 The SQL Quick Reference Guide Page 87 .AVG(CASE Dept_No WHEN 400 THEN Salary ELSE 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.AVG(CASE Dept_No WHEN 300 THEN Salary ELSE NULL END) AS "Dept 300 AVG SAL" .AVG(CASE Dept_No WHEN 200 THEN Salary ELSE NULL END) AS "Dept 200 AVG SAL" . This style of Case Statement is called Horizontal Reporting.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. SELECT AVG(CASE Dept_No WHEN 100 THEN Salary ELSE NULL END) AS "Dept 100 AVG SAL" . 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.00 80000. The output would look something like this: Dept 100 AVG SAL Dept 200 AVG SAL ________________ _________________ 50000. The result set would produce a one line total for each department.00 60000.00 Dept 300 AVG SAL Dept 400 AVG SAL _________________ _________________ 55000.

For more details refer to “Teradata SQL: Unleash the Power”.Man Issues: Possibly missing parentheses in the SQL. expected something like ‘)’ between the ‘END’ keyword and the ‘END’ keyword . 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. Chapter 13. ' || First_Name . SELECT TRIM(Last_name) || '.5 THEN 'Satisfactory' ELSE 'Honor Roll' END) ELSE 'Senior ' || (CASE WHEN Grade_pt < 2 THEN 'Unacceptable' WHEN Grade_pt < 3.The SQL Reference Guide Nested CASE Each nested CASE statement is enclosed in parentheses and has a corresponding END statement .5 THEN 'Satisfactory' ELSE 'Honor Roll' END) END AS "Grade Status" FROM Student_Table ORDER BY Class_Code.5 THEN 'Satisfactory' ELSE 'Honor Roll' END) WHEN 'JR' THEN 'Junior ' || (CASE WHEN Grade_pt < 2 THEN 'Failing' WHEN Grade_pt < 3. Last_Name. This allows for further testing of a value that passes the first level of the nested case statement. Hint .5 THEN 'Satisfactory' ELSE 'Honor Roll' END) WHEN 'SO' THEN 'Sophomore ' || (CASE WHEN Grade_pt < 2 THEN 'Unacceptable' WHEN Grade_pt < 3. Then move to the second ‘(‘ and find its partner ‘)’. 3707: Syntax error. Solutions: The best means of solving this issue is to start with the first ‘(‘ and find the ‘)’ that is paired with it.CASE Class_code WHEN 'FR' THEN 'Freshman ' || (CASE WHEN Grade_pt < 2 THEN 'Unacceptable' WHEN Grade_pt < 3. Page 88 The SQL Quick Reference Guide .

First_Name FROM Student_Table STU INNER JOIN Student_Course_Table STU_COUR ON STU. First_Name. or joining multiple tables together to make reporting an easier task.name> [( <alias.Student_Id = STU_COUR.name> [ WHERE <conditional-tests> ] [ WITH CHECK OPTION] . CREATE VIEW Employee_V AS SELECT Employee_No.Student_Id. Create View Syntax Views allow a user to manipulate the columns returned with the reporting format desired. Hours) AS SELECT Course_Name. Most Enterprises use views as a means of protecting the raw data from any accidental corruption by users.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.Student_Id WHERE Course_Id = 400 WITH CHECK OPTION . CREATE VIEW <view.name> ] […. 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.name> ] ] FROM <table.name>. CREATE VIEW Course_Credits_V (CourseName. Views are used as a means to customize the way users can access a certain table by deriving columns. The SQL Quick Reference Guide Page 89 . <column-name> [AS <alias. CREATE VIEW Roster_400_V AS SELECT STU. Last_Name. Credits FROM Course_Table . … ) ] AS SELECT <column. restricting columns. There are many ways that can be answered.name> [AS <alias. Dept_No FROM Employee_Table . <alias-name>. which is very useful. Last_Name .

A misspelling of some sort could cause this error. Hint . Then put the proper table name in the view create text. which is a Teradata specific feature.]<view. DROP VIEW Employee_V . DROP Views The DROP View syntax completely removes a view from the Data Dictionary.The SQL Reference Guide The “Create View” Syntax can be replaced by “CV”. The next step is to run a ‘HELP DATABASE <database-name>’ command to locate the table desired to have a view on. or the table you are looking for could not be in that database. DROP VIEW Course_Credits_V . 3807: Table/view/trigger ‘<table-name>’ does not exist. DROP VIEW[<database.Man Issues: Table does not exist from which the view is pulling from. a user may only insert or modify rows that are compliant to “Course_Id = 400” due to the WITH CHECK OPTION statement. Solutions: The first thing to do is search for the table name and ensure it is properly spelled.name<. In the fourth example. Page 90 The SQL Quick Reference Guide .name> .

. 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. The SQL Quick Reference Guide Page 91 .name>. First_Name FROM Student_Table STU INNER JOIN Student_Course_Table STU_COUR ON STU. This is safer and more efficient then trying to retype the entire view in again.Simplicity by Design REPLACE Views Use the word REPLACE to change a view. Hint .Man A clever technique to replacing a view is to run the SHOW VIEW <ViewName> command.Student_Id = STU_COUR.name> AS SELECT <column.]<view.<column-name> ] FROM <table -name> [ WHERE <conditional-tests> ] [ WITH CHECK OPTION ] .Student_Id WHERE Course_Id = 400 WITH CHECK OPTION . REPLACE VIEW Sales_Low_V AS SELECT * FROM Sales_Table WHERE Daily_Sales <= 40000 .name> [.. REPLACE VIEW Roster_400_V AS SELECT Last_Name.. REPLACE VIEW[<database.

name>.]<view-name> AS LOCKING <table-name> FOR ACCESS SELECT <column. Access Locks provide compatibility with all other lock types except for an Exclusive Lock.The SQL Reference Guide LOCKING FOR ACCESS Using an Access Lock is like a “Dirty Read” . or “Tera-Tom on Teradata Basics” by Jones and Coffing. For more information on Lock Types. Only do this for queries where the answer does not have to be exact. CREATE VIEW Course_Credits_V (CourseName.. 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.Man Teradata places locks for users automatically.. refer to “Teradata SQL: Unleash the Power” by Larkins and Coffing. Credits FROM Course_Table . { CREATE | REPLACE } VIEW [<database. Hours) AS LOCKING Course_Table FOR ACCESS SELECT Course_Name. The above queries tell Teradata to put an ACCESS lock on the table so they won’t wait on a WRITE Lock.name> [. Dept_No FROM Employee_Table . Last_Name . First_Name. Hint . English: The above examples are explicitly telling Teradata to put an ACCESS Lock on the tables being read instead of the default READ Lock. CREATE VIEW Employee_V AS LOCKING Employee_Table FOR ACCESS SELECT Employee_No. Chapter 16.<column-name> ] FROM <table -name> [ WHERE <conditional-tests> ] [ WITH CHECK OPTION ] . Hint ..Man Page 92 The SQL Quick Reference Guide . CREATE VIEW Sales_Low_V AS LOCKING Sales_Table FOR ACCESS SELECT * FROM Sales_Table WHERE Daily_Sales <= 35000 .

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
( UPDATE Employee_Table SET Salary = Salary * 1.10 ; ) ;

AS

REPLACE MACRO Remove_Sales_Date_M ( DELETE FROM Sales_Table
WHERE Sale_Date = Current_Date – 60 ; ) ;

AS

REPLACE MACRO Order_M AS ( SELECT * FROM Order_Table WHERE Order_Total > 10000 ; ) ;

Hint - Man

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.

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

‘Teradata SQL: Unleash the Power’ book by Larkins and Coffing. Write A data block is being modified.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.locking> [NOWAIT] LOCKING Order_Table for READ SELECT * FROM Order_Table . Read Data is retrieved from a disk. 1000234. Causes object to be inaccessible. Locks at the Database or Table Level. ‘Shipping’. Page 96 The SQL Quick Reference Guide . Hint . NOWAIT serves the purpose of ignoringany lock that is on that specific row. refer to Chapter 16. <DEFAULT for all users> Access A “Dirty Read”. and performing the SQL immediately. 450000) .Man Lock Syntax The defaultlevel of locking for this syntax is Row Level . making it temporarily unavailable. For more details on Locks and Lock compatibility. LOCKING[<table -name>] FOR <desired. with no changes made. LOCKING Department_Table for WRITE NOWAIT INSERT INTO Department_Table (700. Allows a user to access data that is currently locked with a Write Lock.

name> FOR <desired-locking> LOCKING DATABASE Sql_Class FOR EXCLUSIVE MODIFY DATABASE Sql_Class AS Permanent = 5500000 BYTES . The SQL Quick Reference Guide Page 97 . LOCKING DATABASE<database.Simplicity by Design LOCKING ROW FOR<desired. LOCKING VIEW<view-name> FOR <desired-locking> LOCKING VIEW Employee_V FOR READ SELECT * FROM Employee_V . ‘Shipping’.locking> LOCKING Department_Table for WRITE NOWAIT INSERT INTO Department_Table (700.locking> LOCKING ROW FOR ACCESS SELECT * FROM Customer_Table WHERE Customer_Name = ‘ACE Consulting’ . 450000) . 1000234. LOCKING TABLE<table -name> FOR <desired.

This is perfectly acceptable. A transaction can also be explicit with a BEGIN TRANSACTION (BT) command and an END TRANSACTION (ET) command. One big key to remember is that users can utilize either mode and all SQL commands work in either mode. Character literal values must be coded using the correct case in order for the search engine to determine a match. The difference between the two modes is represented in the table below. An ‘A’ is different than an ‘a’ and data would not be returned. Character literal values can be coded in the SQL as lower case or upper case. Any attempt to return less than all the data stored in a column will cause the SQL to fail with an error (3996). Transaction Mode Types TERADATA Mode ANSI Mode Data comparison is not case specific . The presence of the ET command will cause all succes sfully completed SQL work to be committed and make it permanent. Certain SQL commands covered in the chapter allow the user to request less characters be returned than the number of characters stored in a column. Teradata mode is called BTET. Forbids truncation of display data. The CREATE TABLE will default to: MULTISET table (duplicate rows allowed) Case specific character data columns Page 98 The SQL Quick Reference Guide . which stands for Begin Transaction End Transaction. All transactions are explicit only and at the end of a transaction a COMMIT WORK command is required in order to commit all successfully completed work and make it permanent. The CREATE TABLE will default to: SET table (no duplicate rows allowed) Non-case specific character data columns Data comparison is case specific . Allows truncation of displayed data.The SQL Reference Guide Transaction Modes Teradata offers two types of Transaction Modes in ANSI or Teradata mode. A transaction is implicit by nature – each SQL statement is a stand-alone transaction and the work committed upon a successful completion. The search engine would view an ‘A’ the same as an ‘a’ and the data would be returned.

If you are already logged in and would like to change modes you must logoff.Man Teradata Transaction Mode (BT/ET) BT/ET allows for establishing a manual transactionwhile in Teradata mode . you must set the Transaction mode BEFORE logging onto the Teradata system. which is normally the default when a user logs in. Hint .if errorcode > 0 then . In BTEQ error checking is available. BT stands for Begin Transaction. . BT .Dept_No AND E. When setting the transaction mode in BTEQ. For more information refer to Chapter 16 “Teradata SQL: Unleash the Power” book by Larkins and Coffing. Normally the BT/ET Statement is used in BTEQ. BT .SET SESSION TR ANSACTION BTET . .quit 12 UPDATE Department_Table FROM Employee_Table AS E SET Budget = Budget + (Salary * . UPDATE Employee_Table SET Salary = Salary * 1. This syntax is only to be used in BTEQ.Employee_No = 1232578 . set the mode. ET stands for End Transaction.statement> [… <SQL. This syntax is only to be used in BTEQ. The syntax places the user session into ANSI Mode .15 WHERE Employee_No = 1232578 .SET SESSION TRANSACTION ANSI . The above example is BTEQ Specific. and then log back on.Man The SQL Quick Reference Guide Page 99 . which is a Case Sensitive mode that requires the user to COMMIT WORK after transactions.Dept_No = Department_Table. ET .Simplicity by Design Setting the Transaction Mode This syntax sets the mode to Teradata Mode .015) WHERE E. . <SQL. Hint .statement>] ET .

if errorcode > 0 then .Dept_No = Department_Table.quit 12 UPDATE Department_Table FROM Employee_Table AS E SET Budget = Budget + (Salary * .015) WHERE E.The SQL Reference Guide Commit Work The Commit Work syntax is used only in ANSI Transaction Mode . ABORT. BT . 1423546. COMMIT WORK . a user must be running BTEQ . Abort/Rollback These statements are used only in Teradata mode in the middle of a BT/ET Transaction. Or ROLLBACK.SET SESSION TRANSACTION ANSI’ command. Solutions: If there is a need to be in ANSI mode. 250000) . This will put you in ANSI mode.Dept_No AND E. SELECT * FROM Department_Table . ABORT . therefore commit work is not needed. 3706: Syntax error: COMMIT WORK not allowed for a DBC/SQL session. ‘Administration’.Employee_No = 1232578 . Issues: User is in Teradata mode. It ensures that all transactions prior to the statement have been properly processed. . Before logging onto the Teradata system enter the ‘. INSERT INTO Department_Table (800. (Alternative: ROLLBACK . ) Page 100 The SQL Quick Reference Guide .15 WHERE Employee_No = 1232578 . An alternative for this is simply logging off to end the session before the ET in the Transaction. UPDATE Employee_Table SET Salary = Salary * 1. COMMIT WORK . If there is no need for ANSI mode simply remove ‘COMMIT WORK’ or use the BT/ET SQL syntax.

SELECT * FROM Department_Table . ‘Administration’. Use ABORT instead. 250000) . Hint . The example is written under the assumption the user is in ANSI Transaction Mode. The SQL Quick Reference Guide Page 101 .Simplicity by Design Rollback Work This syntax is used to roll back a transaction while using ANSI Transaction Mode . ROLLBACK WORK . 1423546. therefore this syntax is not valid. INSERT INTO Department_Table (800.Man Issues: User is in Teradata Mode. ROLLBACK WORK.

<column-name> ] FROM <table. . Liar: “And the truth shall set you free!!!” Using WITH and WITH. Dept_No. This syntax can NOT be used in Queryman. First_Name. Salary FROM Employee_Table WITH AVG(Salary) . In quoting Jim Carrey from the move Liar. Dept_Name. At the end of the report a grand total for SUM(Budget) will be given. Totals (WITH) Using the WITH provides the user the ability to aggregate functions may be applied.<aggregate-function>( <column-name> ) [ (TITLE ‘<title-string>:’) ] ] SELECT Dept_No. the whole truth. English: The above example will select detail lines for Dept_No. Hint . Total a given <column-name> .[…. First_Name.. One big thing to remember is that these are to be used in BTEQ rather than Queryman. and Salary. Page 102 The SQL Quick Reference Guide . so you must use BTEQ for this command. and nothing but the truth and result in detailed reports that are logical and easy to read..name> WITH <aggregate-function>( <column-name> ) [ (TITLE ‘<title-string>:’) ] [. and Budget. All SELECT <column.name> . At the end of the report a grand total for AVG(Salary) and SUM(Salary) will be given. Solutions: Place an aggregate function of your choice in the WITH statement.The SQL Reference Guide Reporting Totals and Subtotals Managers are always asking for detailed reports and information on performances broken down into various sections. 3504: Selected non-aggregate values must be part of the associated group..Man Issues: An aggregate function must be used in a WITH statement. Budget FROM Department_Table WITH SUM(Budget) (TITLE ‘Total Budget’) . Dept_No. . Dept_Name. SELECT Last_Name.BY will break down the truth.. SUM(Salary) English: The above example will select detail lines for Last_Name.

.<aggregate-function>( <column-name> ) ] . SELECT <column..Simplicity by Design Subtotals (WITH. Solutions: The way to fix this problem is to place the aggregate of choice after the ‘WITH’ in the request statement..name> .name> WITH SUM( <column-name> ) [. It will also produce a SUM(Budget) subtotal for each Dept.BY) WITH.. Dept_Name..BY statement.<column. This syntax is not available in Queryman.BY allows forsubtotalsbased on the BY <column-name> clause. English: The above query will produce detail lines for Dept_No.. Budget FROM Department_Table WITH SUM(Budget) (TITLE ‘Total Budget’) BY Dept_No . The SQL Quick Reference Guide Page 103 . Dept_Name.. 3504: Selected non-aggregate values must be part of the associated group.name> FROM <table... BTEQ is the recommended tool to use when creating reports with totals and subtotals. Hint .<aggregate-function>( <column-name> ) ] BY <column-name> [ (TITLE ‘<title-string>:’) ] [ …WITH SUM( <column-name> ) [. but is supported in BTEQ. and Budget. BY <column-name> [ (TITLE ‘<title-string>:’) ] ] SELECT Dept_No.Man Issues: An aggregate function must be used in a WITH.

. 2000) ORDER BY Sale_Date . English: The above query will produce detail lines for Product_Id.. There will be a Grand_Total of SUM(Daily_Sales) at the end of the report.The SQL Reference Guide Multiple WITH. Sale_Date. and Daily_Sales.BY functions can be very powerful. This allows the user to create complex reportsthat include both grand totals and subtotals. SELECT Product_Id.Bys Using a combina tion of the WITH and WITH. 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. Then another subtotal break of SUM(Daily_Sales) will be produced by Product within month. Page 104 The SQL Quick Reference Guide . Sale_Date. It will then produce subtotals of SUM(Daily_Sales) By Month.

Using the <database-name> to identify the table is known as qualifying.]<table -name> ( <column-name> <data..Phone_Number CHAR(8) ) UNIQUE PRIMARY INDEX (Vendor_Id) . CREATE TABLE[<database. DROP or ALTER you are using Data Definition Language.Man *Detailed information on Data Types can be found in Appendix C. You are defining objects or the way objects look or function.VENDOR_TABLE ( Vendor_Id INTEGER .<column-name> <data.. CREATE TABLE SQL_CLASS. Hint . Teradata will assign by default a Non-Unique Primary Index on the first columnif a Primary Index is not defined in the Create Table statement.name>.. The SQL Quick Reference Guide Page 105 .Vendor_Name VARCHAR(20) .type> ] ) [UNIQUE] PRIMARY INDEX [<index-name>] (<column-name>) . which is discussed in Appendix E.type> [. However. Create Table Teradata is extremely flexible and allows the user to create a table without declaring a Primary Index.Simplicity by Design Data Definition Language If you use the keywords CREATE.

expected something like an 'UNIQUE' keyword between the word '<column-name>' and '..type> [. then assign it a data type accordingly.. 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.name> [.. The error is caused by not assigning a data type to a column that is being defined.VENDOR_TABLE ( Vendor_Id INTEGER ..Vendor_Name VARCHAR(20) .<column-name> <data. it is recommended to use single column Primary Indexes whenever possible.Phone_Number CHAR(8) ) UNIQUE PRIMARY INDEX VNDRIDX (Vendor_Id. CREATE TABLE SQL_CLASS..'.]<table -name> ( <column-name> <data. Vendor_Name) .<column-name>]) .type> ] ) [UNIQUE] PRIMARY INDEX [<index-name>](<column. Issues: 3707: Syntax error. CREATE TABLE [<database. Page 106 The SQL Quick Reference Guide .name>.The SQL Reference Guide Multiple Column Primary Index Although multiple column Primary Indexes are allowed.

CREATE [SET | MULTISET]TABLE [<database. CREATE SET TABLE SQL_CLASS.VENDOR_TABLE ( Vendor_Id INTEGER . Vendor_Name) .type> ] ) [UNIQUE] PRIMARY INDEX [<index-name>](<column.Simplicity by Design SET | MULTISET Table MULTISET Tables allow for ..Vendor_Name VARCHAR(20) . Vendor_Name) . CREATE MULTISET TABLE SQL_CLASS.Phone_Number CHAR(8) ) UNIQUE PRIMARY INDEX VNDRIDX(Vendor_Id..Set table because SET tables must always compare rows for duplicates.type> [.name>[….]<table -name> ( <column-name> <data. A SET table will throw out any rows that are complete duplicates. The default for ANSI Mode is MULTISET. Solutions: The only solution to this is to remove the space in the ‘MULTISET’ phrase.name>]) .Man Issues: A common error could be caused by having a spa ce in ‘MULTISET’. If you don’t care which type you have it is better to have a Multi.<column-name> <data. MULTISET tables are quite useful when using Teradata for accounting purposes. This is the error returned by Teradata: 3706: Syntax error: Expected GLOBAL TEMPORARY..VENDOR_TABLE ( Vendor_Id INTEGER .Phone_Number CHAR(8) ) UNIQUE PRIMARY INDEX VNDRIDX(Vendor_Id.<column. The SQL Quick Reference Guide Page 107 .Vendor_Name VARCHAR(20) . The default for multiple instances of the same row Teradata Mode is SET.name>. Hint .

.<column.The SQL Reference Guide FALLBACK FALLBACK is a Table specific Teradata feature to protect against default is NO FALLBACK..name>]) . FALLBACK ] ( <column-name> <data. ( Vendor_Id INTEGER . You can also add or drop FALLBACK at any time.Man Issues: A missing comma between the <table -name> and FALLBACK. AMP failure ..type> [. no tables.<column-name> <data.Phone_Number CHAR(8) ) UNIQUE PRIMARY INDEX (Vendor_Id) . Page 108 The SQL Quick Reference Guide . The CREATE [SET | MULTISET] TABLE [<database-name>.VENDOR_TABLE. Hint .type> ] ) [UNIQUE] PRIMARY INDEX [<index-name>](<column.]<table .Vendor_Name VARCHAR(20) . Solutions: Simply place a comma before the ‘FALLBACK’ keyword.name>[…. or some tables.name> [. CREATE SET TABLE SQL_CLASS. 3706: Syntax error: expected something between the word ‘VENDOR_TABLE2’ and the ‘FALLBACK’ keyword. FALLBACK You can FALLBACK protect all tables.

Vendor_Name VARCHAR(20) . FALLBACK .. CREATE [SET | MULTISET] TABLE [<database-name>. The AFTER Journaltakes a picture of the affected rows after any changes are made.VENDOR_TABLE. [DUAL ] AFTER JOURNAL ] ( <column-name> <data. FALLBACK . DUAL AFTER JOURNAL ( Vendor_Id INTEGER . so be sure to purge the Journalafter a full system backup.]<table . Vendor_Name) . BEFORE JOURNAL ( Vendor_Id INTEGER . CREATE SET TABLE SQL_CLASS. AFTER JOURNAL ( Vendor_Id INTEGER . FALLBACK ] [. Vendor_Name) . This will be used in conjunction with Full System Backups. [DUAL ] BEFORE JOURNAL ] [.type> ] ) [UNIQUE] PRIMARY INDEX [<index-name>](<column. DUAL BEFORE/DUAL AFTER. Vendor_Name) .Man The SQL Quick Reference Guide Page 109 .type> [. CREATE SET TABLE SQL_CLASS. Hint .name> [.Phone_Number CHAR(8) ) UNIQUE PRIMARY INDEX VNDRIDX(Vendor_Id.Phone_Number CHAR(8) ) UNIQUE PRIMARY INDEX VNDRIDX(Vendor_Id.Phone_Number CHAR(8) ) UNIQUE PRIMARY INDEX VNDRIDX(Vendor_Id.<column-name> <data. All the pictures are stored on disk.VENDOR_TABLE.Simplicity by Design Permanent Journal There are three variances for the Permanent Journal: BEFORE.name>[…. The DUAL BEFORE or DUAL AFTER Journal takes two pictures before the rows are changed and saves them on two different AMPs.Vendor_Name VARCHAR(20) ..Vendor_Name VARCHAR(20) . If a crash occurs the DBA can go to the last Full System Backup and then add the After Journal. The DUAL AFTER Jounal takes two pictures after that rows are changed and stores them on two different AMPs . FALLBACK .name>]) . CREATE SET TABLE SQL_CLASS. DUAL BEFORE JOURNAL.. The BEFORE Journal takes a picture of the affected rows before any changes are made.VENDOR_TABLE. The most common journal is the AFTER JOURNAL. AFTER.<column.

i.VENDOR_TABLE. [DUAL ] BEFORE JOURNAL ] [. 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 space COMPRESS <value> Compress specified value to take no disk space.Vendor_Name VARCHAR(20) TITLE ‘Vendor Name’ .. Page 110 The SQL Quick Reference Guide .name> [.. FALLBACK .name>[….Phone_Number CHAR(8) DEFAULT NULL ) UNIQUE PRIMARY INDEX (Vendor_Id) .<column-name> <data.type> ][<column-level-attribute>]) [UNIQUE] PRIMARY INDEX [<index-name>](<column.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 name WITH DEFAULT Default numeric values to zero. CHARACTER SET Establishes the computer internal storage rules and how it should be interpreted.<column..e. The value is stored one time in the table header. The following is a list of all the column level attributes.name>]) . [DUAL ] AFTER JOURNAL ] ( <column-name> <data.The SQL Reference Guide Add Column Attributes CREATE [SET | MULTISET] TABLE [<database-name>.type>[<column-level-attribute>] [. FALLBACK ] [. BEFORE JOURNAL ( Vendor_Id INTEGER NOT NULL . 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 column DEFAULT NULL Use null as the default value for the column CREATE SET TABLE SQL_CLASS.]<table . Hint .

name>]) [<column-level-constraint>] [… .Phone_Number CHAR(8) DEFAULT NULL ).. FALLBACK . 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.name>[…. REFERENCES Requests a referential integrity check.name> [. You must have the NOT NULL constraint also defined when defining a UNIQUE constraint. Chapter 18.type> [<column-level-attribute>] [<column-level-constraint>] [. UNIQUE UNIQUE enforces uniqueness on a column. The SQL Quick Reference Guide Page 111 .attribute>] [<column-level-constraint>]) [UNIQUE] PRIMARY INDEX [<index-name>](<column. [DUAL ] AFTER JOURNAL ] ( <column-name> <data. BEFORE JOURNAL ( Vendor_Id INTEGER NOT NULL CONSTRAINT UNIQUE_1 UNIQUE .Simplicity by Design Column and Table Constraints CREATE [SET | MULTISET] TABLE [<database-name>..type>][<column-level.VENDOR_TABLE. [DUAL ] BEFORE JOURNAL ] [. For more information and examples refer to “Teradata SQL: Unleash the Power”.<column.Vendor_Name VARCHAR(20) TITLE ‘Vendor Name’ .Man This chart is used to determine the level constraints can be named: Used as Column Level Used as Table Level Constraint 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. FALLBACK ] [. Hint .<column-name> <data. CHECK Allows range or value constraints to be placed on the column.]<table . You must have the NOT NULL constraint also defined when defining a PRIMARY KEY.<column-level-constraint>]..

but the data is not copied. For more information and examples refer to “Teradata SQL: Unleash the Power” book by Larkins and Coffing.Employee_Table2 AS ( SELECT * FROM Employee_Table ) WITH NO DATA UNIQUE PRIMARY INDEX(Employee_Id) .Man Page 112 The SQL Quick Reference Guide . The default for CREATE TABLE [<database.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. Hint . CREATE TABLE SQL_CLASS. 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.]<table -name> { <SELECT-statement>} WITH { DATA | NO DATA } [ [ UNIQUE ] PRIMARY INDEX (<column-list>) ] . AS CREATE TABLE SQL_CLASS. Chapter 18. The data from the Employee_Table is also copied into the Employee_Table2 table. The new table is completely empty of data. “Create Table AS” statement.The SQL Reference Guide CREATE TABLE with copying an existing table The Teradata Lingo for this syntax is the this statement isNO DATA .name>.

ALTER TABLE SQL_CLASS. If column changes are required.A . To solve both causes run ‘HELP DATABASE <database-name>’ to do research about the table you are looking to alter. Solutions: There are two possible causes and they are a misspelled <table -name> or you may be looking in the wrong database.]<table.attributes> ] [ WITH JOURNAL TABLE = <table. In the first example VENPK is a <table-level-constraint> defined in the example section of Column and Table Constraints. but adding or dropping columns are permissible. ALTER TABLE[<database-name>. 3807: Table/view/trigger ‘Course_Table2’ does not exist. DROP VENPK . Vendor_Table NO BEFORE JOURNAL.created with the column name changes included. . then the table must be dropped and re. AFTER JOURNAL ADD Vendor_Desc VARCHAR(65).Man Issues: The table being altered does not exist.Course_Table ADD Prerequisites VARCHAR(150) TITLE ‘Prereqs’ ADD CONSTRAINT COURSE_Unique UNIQUE(Course_Name) .name> [. Hint . <table. ALTER TABLE SQL_CLASS.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> ] .Simplicity by Design ALTER Table ALTER TABLE is used to modify a Table or column level attribute and constraint user may not change column names.level. The SQL Quick Reference Guide Page 113 .

Vendor_Table . Teradata is capable of deleting all rows of a table very quickly. 3807: Table/view/trigger ‘Course_Table2’ does not Solutions: There are two possible causes are a misspelled <table-name> or you may be looking in the wrong database.]<table -name> DROP TABLE SQL_CLASS.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. It is recommended to delete all rows rather than drop a table and recreating it. Page 114 The SQL Quick Reference Guide . The DELETE Syntax is addressed in the Data Manipulation Section of the book. Hint .Man Issues: The table being dropped does not exist. It is recommended to delete all rows rather than drop a table and recreating it. unlike other databases. To solve both causes run ‘HELP DATABASE <database-name>’ to do research about the table you are looking to alter. However. .name>. DROP TABLE[<data-base. exist.

To solve both causes run ‘HELP DATABASE <database-name>’ to do research about the table you are looking to alter.]<table.]<table . 3807: Table/view/trigger ‘Course_Table2’ does not exist.name> TO[database-name>.Dept_Table . Hint .Man Issues: The table being renamed does not exist. RENAME TABLE SQL_CLASS. RENAME TABLE [database-name>. The SQL Quick Reference Guide Page 115 . If there is a need to have a table with the same structure in a separate database.Simplicity by Design RENAME Table When renaming a table. Solutions: There are two possible causes are a misspelled <table -name> or you may be looking in the wrong database. use the CREATE TABLE AS syntax which can be located in the Data Definition Language section of this book. the <database.Department_Table TO SQL_CLASS.name> cannot be changed.name> .

Student_Course_Table . DROP INDEX { <index.name> | (<column. Refer to the “Teradata Users Guide” by T. We have given the index a name called Full_Name_Idx. CREATE [UNIQUE] INDEX [ <index-name> ] (<column-list>) [ORDER BY VALUES [ (<column-list>) ] ] on [database.Last_Name) ON SQL_CLASS.Coffing. but not a Full Table Scan (FTS). CREATE INDEX (Course_Id) ORDER BY VALUES ON SQL_CLASS. English: Above we have created a Multi-Key Non-Unique Secondary Index (NUSI) on First_Name and Last_Name combined.Coffing. Value Ordered NUSIs are limited to numeric values that are no larger than 4 bytes long.Course_Table .]<table-name> [ALL] . L. CREATE UNIQUE INDEX (Course_Name) ON SQL_CLASS. Also. English: Above we have created a Value -Ordered NUSI on Course_Id. English: Above we have created a Unique Secondary Index (USI) on Course_Name.Employee_Table .Hines for further information on Secondary Index selection and Performance Optimization. the index name is optional.Coffing. DROP INDEX Crs_Nm_Indx . CREATE INDEX Full_Name_Idx(First_Name. Page 116 The SQL Quick Reference Guide .Man A Non-Unique Secondary Index (NUSI) is an All-AMP operation. Hint . C.Wilmes and R.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. Hint .list>) } . S.The SQL Reference Guide Secondary Indexes Secondary Indexes are used in Teradata as another method to accessing data .

STU.]<join-index.name>) [index <column-name> ORDER by HASH | VALUES] .name>] [ORDER BY <column-name>] PRIMARY INDEX(<column.expression] [EXTRACT year | month from date.Man Teradata Versions V2R4.Course_ID.Course_ID = COUR.condition>] [GROUP BY <column.Student_Table_Indx .Last_name . DROP JOIN INDEX SQL_CLASS.]<table.Course_Roster NO FALLBACK AS SELECT STU. The SQL Quick Reference Guide Page 117 .STU_COUR.1.index-name> [[NO] FALLBACK] AS SELECT [<columns>] [SUM numeric -expression] [COUNT column.expression] FROM [<database-name(s)>.COUR.Student_ID FROM Student_table STU INNER JOIN Student_Course_Table STU_COUR ON STU.COUR.Simplicity by Design Join Indexes Join Indexes provide the means of improving performanceon any type of recurring query that involves joins and/or aggregate functions. The Teradata optimizer will decide whether a query can run faster on the base tables or with the Join Index table.Course_name . Hint .names>] [WHERE <search.Class_code . DROP JOIN INDEX [<database-name>.First_name .name>.]<join. CREATE JOIN INDEX SQL_CLASS. This is extremely beneficial when you create a single table join index on larger tables that are being utilized in joins with smaller tables.STU. single table join indexes do not require all the columns to be listed in order for Teradata to utilize the join index.2xx and later allows for single table join indexes to be created.Student_ID INNER JOIN Course_Table COUR ON STU_COUR.Credits . CREATE JOIN INDEX [<database-name>. The Join Index table will be kept current by Teradata if the base tables change. A Join Index pre-joins tables and physically keeps them on disks. which provides a significant performance enhancement and greatly flexibility. Partial covering of the join index is supported.Student_ID = STU_COUR. In addition.

Man Page 118 The SQL Quick Reference Guide . columns used in the WHERE clause on queries or joins. Always collect statistics at the column level even if a column is an index.The SQL Reference Guide Collect Statistics This is a very important part of optimizing and maintainingthe Teradata System.name> | <join-index. Hint . index(Last_Name. COLLECT STATISTICS ON Employee_Table .Man Collecting Statistics causes a Full Table Scan (FTS) and should be done during off hours. COLLECT STATISTICS ON[ TEMPORARY ] <table . You can collect statistics at the column or index level.name> [ { COLUMN <column-name> | INDEX(<column. 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. COLLECT STATISTICS ON Employee_Table English: Above we refresh statistics on all columns and indexes that have current statistics. When a query is run the Parsing Engine (PE) optimizer will check if statistics were run on the table. English: Above we collect statistics on the column Last_Name in the Employee_Table. You don’t collect on every index and column in a table. Collect Statistics for all NonUnique Secondary Indexes.list>) } ] . Refresh statistics when a table adds or deletes data and this changes the table by more than 10%. The exception to this rule is on Multi-Column indexes. and on Primary indexes of all small tables. COLLECT STATISTICS ON Employee_Table column Last_Name . Hint . First_Name) English: Above we collect statistics on the multi-column index of Last_Name and First_Name.

list>) } ] . no longer keep DROP STATISTICS ON [ TEMPORARY ] <table-name> | <join. DROP STATISTICS DROP STATISTICS is recommended when the decision has been made to statistics on the given <table -name>. The SQL Quick Reference Guide Page 119 .index-name> [ { COLUMN <column-name> | INDEX(<column. DROP STATISTICS ON Student_Table INDEX (Last_Name) . HELPSTATISTICS <table-name> . DROP STATISTICS ON SQL_CLASS. HELP STATISTICS Student_Table . Information returned contains the time and date statistics of when last time statistics were collected.Department_Table .Simplicity by Design HELP STATISTICS HELP STATISTICS is used to discover what columns and indexes have statistics run on them.

.Journal_Table . . remember to have enough disk space in the system to have 20% in Spool Reserve. 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. It’s a good idea to research the impact on the system when creating large databases. Triggers. . Hint . . 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. { 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>. Views. . and Stored Procedures. A Database and a User are almost the same in Teradata because both can have Perm and Spool space. . When defining the upper limit for Perm space.The SQL Reference Guide CREATE DATABASE You create a database to normally hold objects such as Tables. Macros.<table-name> ] .Man Page 120 The SQL Quick Reference Guide . .

{ CREATE | MODIFY } USER <user-name> FROM <parent-database-name> AS PERM[ANENT] = <num-of-bytes> PASSWORD = { <password> | NULL } [ .SPOOL = <num-of-bytes> . A user in Teradata can hold objects such as Tables. .COLLATION = <collation-sequence> . .[NO] FALLBACK .Man The SQL Quick Reference Guide Page 121 .<table-name> ] . A Database and a User are almost the same in Teradata because both can have Perm and Spool space.’ SPOOL = 10000000 TEMPORARY = 5000000 DEFAULT DATABASE = SQL_CLASS COLLATION = HOST ACCOUNT = ‘carrolltg’ NO FALLBACK NO BEFORE JOURNAL NO AFTER JOURNAL . which allow them to hold objects. . . . Triggers.TEMPORARY = <num-of-bytes> . Views. Teradata views a User as a Database with a password.DEFAULT DATABASE = <database-name> .Simplicity by Design CREATE USER You create a USER so that user can logon to Teradata and run queries. and behave exactly like a database.[NO | DUAL] BEFORE JOURNAL . CREATE USER SQL26 FROM SQL00 AS PERM = 1000000 PASSWORD = SQL26 STARTUP = ‘SET SESSION ANSI. A User may store all objects in its PERM space.[NO | DUAL | LOCAL | NOT LOCAL] AFTER JOURNAL . Hint . . .STARTUP = <string> . Macros. .DEFAULT JOURNAL TABLE = <database-name>. The only difference between a user and a database is that a user has a password and can logon and run queries. . and Stored Procedures. .ACCOUNT = <acctid> .

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> . Page 122 The SQL Quick Reference Guide . DROP DATABASE SQL_CLASS . DROP USER SQL00 .

<data.column-value> [. HASHROW The HASHROW function returns an 8.Man The SQL Quick Reference Guide Page 123 . Hint . Even data distribution can be very important to Teradata because Teradata processes data in parallel. which represents the result of putting the <data-column-value> into Teradata’s Hash Formula.. SELECT HASHROW (Dept_No) from Department_Table .. SELECT HASHROW( [ <data.value> … ] ] ) .column. HASHROW (Student_Id))) A great demonstration of how to use this function powerfully is in the second example. SELECT COUNT(*) / COUNT(DISTINCT( AS AVG_ROW_CNT FROM Student_Table .Simplicity by Design Hashing Functions Hashing functions allow users to see how data is distributed across the AMPs..digit Hexidecimal number.

SELECT HASHAMP( <hash-bucket> ) .bit Row Hash value. 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.hash-value> ] ) . SELECT HASHBAKAMP (HASHBUCKET(HASHROW(Student_Id))) FROM Student_Table . Group by Bucket Issues: A 32-bit row hash value was not plugged into the function. SELECT HASHAMP (HASHBUCKET(HASHROW(Student_Id))) FROM Student_Table . SELECT HASHBAKAMP ( <hash-bucket> ) . The input into this function is the 32. SELECT COUNT(*). which can be produced using the HASHROW function. The result will be between 0 and 65536. type for the HASHBUCKET function is invalid. HASHBUCKET (HASHROW(Student_Id)) AS Bucket FROM Student_Table . HASHBAKAMP HASHBAKAMP identifies the FALLBACK AMP for a given hash bucket number. SELECT HASHBUCKET( [ <row.The SQL Reference Guide HASHBUCKET This function produces the 16-bit binary Hash Bucket from the Data Distribution Hash Map. Page 124 The SQL Quick Reference Guide . The correct application is using HASHBUCKET and HASHROW together. 3794: The argument HASHAMP HASHAMP returns the identification number for the AMP in which the hash bucket number points to. Just as HASHAMP a correct application is with HASHBUCKET and HASHROW.

. . “Teradata SQL: Unleash the Power” by Larkins and Coffing. The SQL Quick Reference Guide Page 125 .name> [.Simplicity by Design Temporary Tables Teradata allows users to create Temporary tables with great ease. <column. F_Name. the derived table no longer exists. SELECT <column. Each is described below..0 ) DT (L_Name. Dept_Name.’ Solutions: The only way to fix this is to place a ‘DT’ at the end of the derived table declaration. CC FROM (SELECT Last_Name. Class_Code FROM Student_Table WHERE Grade_Pt >= 3.Man Issues: The derived table has not been given a name. expected something like a name between ‘)’ and ‘. 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.<column-name> ] FROM <table-name> ) <Derived-table-name> [ ( <alias-name> […. First_Name. CC) SELECT Dept_No. F_Name. 3707: Syntax error.<alias-name> ] ) SELECT * FROM (SELECT MIN(SALARY) FROM Employee_Table) DT (Min_Sal) . SELECT L_Name. Department_Table ORDER BY Dept_No . For more detailed information and examples refer to Chapter 19. Volatile. There are three types of Temporary tables in Derived. . Hint . AVG_Budget FROM (SELECT AVG(Budget) FROM Department_Table) DT (AVG_Budget).name> ] FROM ( SELECT <column-name> [ AS <alias-name> ] [ … . Once the result set is returned to the user. The space to material the rows comes from the users SPOOL space.. and Global Temporary tables.

2) DECIMAL(7.Max_Sale . In theory. A user may log onto the Teradata system.type> [ . When you logoff the table is deleted.MAX(Daily_Sales) .SUM(Daily_Sales) . INSERT into the table the information from the specific month and then run your queries. Now that the Volatile Table has been created.2) DECIMAL(7. or to have the rows deleted upon a comp lete transaction. they should run 12 times faster than if you queried the yearly table.Sum_Sale .The SQL Reference Guide Volatile Temporary Tables Volatile Temporary Table. or Volatile Table. A great idea is to create a Volatile table.AVG(Daily_Sales) . The “ON COMMIT” clause gives two options to the user: whether to keep the rows in the table after a transaction. The LOG option allows a Volatile Table to use the Transient Journal during transactions. CREATE ( Sale_Date . LOG DATE DECIMAL(9. the table must be populated with an INSERT/SELECT statement like the following: INSERT INTO Sales_Report_vt SELECT Sale_Date .Min_Sale ) VOLATILE TABLE Sales_Report_vt. The default value is ON COMMIT DELETE ROWS.2) ON COMMIT PRESERVE ROWS . { LOG | NO LOG} ] ( <column-name> <data. The space comes from the users spool space.2) DECIMAL(7.MIN(Daily_Sales) FROM Sales_Table GROUP BY Sale_Date. Hint . <column-name> <data. create a Volatile Table and use it until logging off.Avg_Sale . so users beware! CREATE VOLATILETABLE <table -name> [ .Man Imagine you have to get monthly information from a yearly table. <column-name> <data.type> ] ) [ [ UNIQUE ] PRIMARY INDEX (<column-list>) ] [ ON COMMIT { PRESERVE | DELETE } ROWS ] .type> [ . is available throughout the user session . Page 126 The SQL Quick Reference Guide .

Avg_Sale DECIMAL(7. or Global Tables are a new breed of temporary table that is very powerful. The SQL Quick Reference Guide Page 127 . <column-name> <data.2) .2) .2) . The LOG option allows a Temp Table to use the Transient Journal during transactions. If a user desires to remove the table definition from the Data Dictionary the user must implement a DROP TABLE command.SUM(Daily_Sales) .Simplicity by Design Global Temporary Tables CREATE GLOBAL TEMPORARY TABLE Global Temporary Tables.2) ) PRIMARY INDEX(Sale_Date) ON COMMIT PRESERVE ROWS .MIN(Daily_Sales) FROM Sales_Table GROUP BY Sale_Date . CREATE GLOBAL TEMPORARY TABLE <table -name> ( <column-name> <data. each user may put different data into their own copy of the table definition. [ { LOG | NO LOG} ] CREATE GLOBAL TEMPORARY TABLE Sales_Report_gt.Min_Sale DECIMAL(7. LOG ( Sale_Date DATE .type> ] [ [ UNIQUE ] PRIMARY INDEX (<column-list>) ] [ ON COMMIT { PRESERVE | DELETE } ROWS ] . Hint .Sum_Sale DECIMAL(9. However. The definition of the table is stored in the Data Dictionary and that allows for multiple users to have access to the table definition.type> [ .Max_Sale DECIMAL(7.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 .AVG(Daily_Sales) .MAX(Daily_Sales) .

The SQL Reference Guide DROP TEMPORARY TABLE This syntax removes any temporary table . However it Temporary table definitionfrom the Data Dictionary. Issues: The temporary table does not exist in the user session. will not drop the Global DROP TEMPORARYTABLE Sales_Report_vt . 3807: Table/view/trigger ‘<table-name>’ does not exist. Page 128 The SQL Quick Reference Guide . DROP TEMPORARYTABLE <table -name> .

The SQL Quick Reference Guide Page 129 . Solutions: Fixing this problem is as simple as deciding whether to use the ‘FOR EACH ROW’ or the ‘FOR EACH STATEMENT’. Both are mutually exclusive. 5423: This trigger contains an invalid REFERENCING clause. ‘999-9999’). and then adding in the statement after the ‘BEFORE INSERT ON <table -name>’ command. ‘Customer Name’.Simplicity by Design Triggers When dealing with triggers. A Row Trigger fires off for each row that is affected by the triggering statement.Man Issues: There is not a FOR EACH ROW or FOR EACH STATEMENT clause present in the code. A Statement Trigger fires off only once per triggering statement. beforethe specific CREATE TRIGGER <Trigger-name> BEFORE <TRIGGERING ACTION > {INSERT | UPDATE | DELETE | INSERT/SELECT} [ OF (<column-name>. A good example would be when inserting a new order into the Order_Table.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 } . a trigger could be created to ensure the Customer who is making the order exists in the Customer_Table. The above example illustrates this scenario. meaning that a created trigger can either be a Row Trigger type or a Statement Trigger type but not both. BEFORE Triggers In this scenario. … ) ] ON <subject. If not.). the <TRIGGERED ACTION> is being performed <TRIGGERING ACTION>. ) CREATE TRIGGER CUST_ORD_TRIG BEFORE INSERT ON Order_Table REFERENCING NEW AS ord_row FOR EACH ROW WHEN (ord_row. Hint .customer_number. Triggers are most widely used as a means for Referential Integrity.customer_number NOT IN (SELECT customer_number FROM Customer_Table)) (INSERT INTO Customer_Table VALUES (ord_row. then insert a row into the Customer_Table BEFORE inserting a row into the Order_Table. a user must understand the difference between the two types of triggers: Row Triggers and Statement Triggers.

Hint .) .10 ) (INSERT INTO Salary_Fraud VALUES (after_row.name> AFTER <TRIGGERING ACTION > {INSERT | UPDATE | DELETE | INSERT/SELECT} [ OF (<column.salary.image> NEW_TABLE AS <after. A good application would be a table that is updated if any employee’s salary is raised more than 10%. … ) ] ON <subject. CREATE TRIGGER <Trigger.employee_no.salary. ) . before_row. 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.salary > .Man Page 130 The SQL Quick Reference Guide . causes the <TRIGGERED ACTION> to fire afterthe <TRIGGERING ACTION> is performed. The above example reflects this scenario.salary – before_row) / before_row. DATE) .image> { FOR EACH STATEMENT | FOR EACH ROW } [ WHEN ( optional condition ) ] ( <TRIGGERED ACTION> { INSERT | INSERT/SELECT | UPDATE | DELETE | ABORT/ROLLBACK | EXEC } . after_row.name>.The SQL Reference Guide AFTER Triggers The AFTER Trigger. CREATE TRIGGER Salary_Fraud_Trig AFTER UPDATE OF (salary) ON Employee_Table before_row REFERENCING OLD AS NEW AS after_row FOR EACH ROW WHEN ((after_row.table> REFERENCING OLD_TABLE AS <before. This would be useful to detect any type of salary fraud within the company.

Simplicity by Design INSTEAD OF Triggers This style of trigger is fairly direct. The example of this scenario follows. Hint . It tells Teradata to do the <TRIGGERED ACTION> place of the <TRIGGERING ACTION>. ) . Then at a later time the new rows can be placed into the Student _Table.Man A Database Administrator may want to keep track of and maintain any new rows added into the Student_Table. … ) ] ON <subject.name>. What this means is that the “INSTEAD OF Trigger”. ) . in CREATE TRIGGER New_Student_Trig INSTEAD OF Student_Table INSERT ON REFERENCING NEW AS newstu FOR EACH STATEMENT (INSERT INTO New_Student_Table Select * from newstu.table> REFERENCING OLD_TABLE AS <before.image> { FOR EACH STATEMENT | FOR EACH ROW } [ WHEN ( optional condition ) ] ( <TRIGGERED ACTION> { INSERT | INSERT/SELECT | UPDATE | DELETE | ABORT/ROLLBACK | EXEC } . CREATE TRIGGER <Trigger.image> NEW_TABLE AS <after. will place any new rows inserted into the Student_Table in a separate table.name> INSTEAD OF <TRIGGERING ACTION > {INSERT | UPDATE | DELETE | INSERT/SELECT} [ OF (<column. The SQL Quick Reference Guide Page 131 .

… ) ] ON <subject.name>. ) . ). Issues: 5432: A trigger Order value must be within a range of 0 to 32767. Ordering triggers is important. ORDER 100 CREATE TRIGGER GPA_Fraud_Trig BEFORE UPDATE ON Student_Table ORDER 150 REFERENCING NEW AS new_row OLD AS old_row FOR EACH ROW WHEN(new_row. A User may number their triggers (1 through 32.table> REFERENCING OLD_TABLE AS <before. Order 1 triggers will be kicked off before Order 2 triggers. etc .Student_Id.name> {BEFORE | AFTER | INSTEAD OF} [ ORDER <sequence -number> ] <TRIGGERING ACTION > {INSERT | UPDATE | DELETE | INSERT/SELECT} [ OF (<column.image> FOR EACH STATEMENT [ WHEN ( optional condition ) ] ( <TRIGGERED ACTION> { INSERT | INSERT/SELECT | UPDATE | DELETE | ABORT/ROLLBACK | EXEC } .Grade_pt <> old_row. CREATE TRIGGER <Trigger. old_row.Grade_pt) .Grade_pt) (INSERT INTO Save_GPA_Table VALUES (old_row. Solutions: Locate the ‘ORDER’ statement and replace the <sequence-number> with a number between 0 and 32767.Student_Id.Grade_pt). This is to allow the Database Administrator flexibility to place a preference on one trigger over another one.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.Grade_pt <> old_row.Grade_pt) (INSERT INTO GPA_Fraud_Table VALUES (old_row. CREATE TRIGGER Save_GPA_Trig BEFORE UPDATE ON Student_Table REFERENCING NEW AS new_row OLD AS old_row FOR EACH ROW WHEN (new_row. ). Page 132 The SQL Quick Reference Guide .767). old_row. but you need to keep the range in mind. new_row.image> NEW_TABLE AS <after.Grade_pt.

DDATABASE DATABLOCKSIZE DATE DATEFORM DAY DEC DECIMAL DECLARE DEFAULT DEL DELETE DESC DIAGNOSTIC DISABLED DISTINCT DO DOUBLE DROP DUAL DUMP . These are words that need to be avoided when creating database objects.1 reserved words.CCALL CASE CASESPECIFIC CAST CD CHAR CHARACTER CHARACTERS CHARACTER_LENGTH CHARS CHAR2HEXINT CHAR_LENGTH CHECK CHECKPOINT CLUSTER CM COALESCE COLLATION COLLECTCOLUMN COMMENT COMMIT COMPRESS CONSTRAINT CONTINUE CONVERT_TABLE_HEADER CORR OLAP COUNT COVAR_POP CREATE CROSS CS CSUM CT CURRENT CURRENT_DATE CURRENT_TIME CURRENT_TIMESTAMP CURSOR CV . they will need to be enclosed in double quotes (“).EEACH ECHO ELSE ELSEIF ENABLED END EQ ERROR ERRORFILES ERRORTABLES ESCAPE ET EXCEPT EXEC EXECUTE EXISTS EXIT EXP EXPLAIN EXTRACT The SQL Quick Reference Guide Page 133 .AABORT ABORTSESSION ABS ACCESS_LOCK ACCOUNT ADD ADD_MONTHS AFTER ALL ALTER AMP AND ANSIDATE ANY AS ASC AT ATOMI C AVE AVERAGE AVG . If they are used for anything other than their reserved meaning. .Simplicity by Design APPENDIX A: Current Reserved Words The following list indicates all of the Teradata release V2R4.BBEFORE BEGIN BETWEEN BOTH BT BUT BY BYTE BYTEINT BYTES .

LLE LEADING LEAVE LEFT LIKE LN LOADING LOCAL LOCK LOCKING LOG LOGGING LOGON LONG LOOP LOWER LT -MMACRO 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 .The SQL Reference Guide Current Reserved Words (continued) .JJOIN JOURNAL .GGCOUNT OLAP GE GIVE GRAPHIC GROUP GSUM GRANT GT .FFALLBACK FASTEXPORT FLOAT FOR FOREIGN FORMAT FREESPACE FROM FULL .KKEY KURTOSIS .IIF IMMEDIATE IN INCONSISTENT INDEX INITIATE INNER INOUT INS INSERT INSTEAD INT INTEGER INTEGERDATE INTERSECT INTERVAL INTO IS ITERATE .HHANDLER HASH HASHAMP HASHBAKAMP HASHBUCKET HASHROW HAVING HELP HOUR .

QQUALIFY QUANTILE .PPASSWORD PERCENT PERM PERMANENT POSITION PRECISION PRESERVE PRIMARY PRIVILEGES PROCEDURE PROTECTION PUBLIC .NNAMED NATURAL NE NEW NEW_TABLE NO NOT NOWAIT NULL NULLIF NULLIFZERO NUMERIC .Simplicity by Design Current Reserved Words (continued) .RRANDOM RANK REAL REFERENCES REFERENCING 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 .OOCTET_LENGTH OF OFF OLD OLD_TABLE ON OPTION OR ORDER OUT OUTER OVER OVERLAPS OVERRIDE .SSAMPLE 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 .

YYEAR .WWHEN WORK WHERE WHILE WITH .VVALUE VALUES VARBYTE VARCHAR VARGRAPHIC VARYING VAR_ POP VAR_SAMP VIEW VOLATILE .UUC UNDEFINED UNDO UNION UNIQUE UPD UPDATE UPPER UPPERCASE USER USING .The SQL Reference Guide Current Reserved Words (continued) .TTABLE TBL_CS TEMPORARY TERMINATE THEN TIME TIMESTAMP TIMEZONE_HOUR TIMEZONE_MINUTE TITLE TO TRAILING TRANSACTION TRANSLATE TRANSLATE_CHK TRIGGER TRIM TYPE .ZZEROIFNULL ZONE A Page 136 The SQL Quick Reference Guide .

GGO GOTO .WWAIT The SQL Quick Reference Guide Page 137 .IINDICATOR .DDESCRIPTOR .PPRIVATE .AALIAS AUTHORIZATION .Simplicity by Design Future Reserved Words The following words are reserved for the future: .

define what a user can and cannot do with a particular object. These statements control the ownership and access by users to the database objects. often referred to as privileges.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 .return to disk from an archive • EXECUTE .make a new object • DROP .transfers ownership of a database or user Privileges Access rights.run a macro or stored procedure • REFERENCES .read rows from a table or view • UPDATE .remove an object • CHECKPOINT .table or column level access • INDEX . 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 .mark rows as valid • DUMP .backup or archive to the checkpoint • RESTORE . The privileges are defined in the following categories: • CREATE .build new rows in a table or view • SELECT .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).remove rows from a table or view • INSERT .secondary index operations • DELETE .

The ALL causes the privilege(s) to cascade downward to all dependents of the user specified. It is not a good idea to use PUBLIC in Teradata due to the larger number of users.]<object-name> TO [ ALL ] { <user-name> […. The GRANT syntax to provide MONITOR operations: GRANT <monitor-privilege> […. The monitor privileges: • MONRESOURCE • MONSESSION • ABORTSESSION • SETRESRATE • SETSESSRATE The SQL Quick Reference Guide Page 139 . The GRANT syntax for SQL privileges: GRANT [ { ALL | ALL BUT } ] <privilege> [….Man The GRANT syntax forLOGON : GRANT LOGON { ALL | <host-id> [….<user-name> ] | PUBLIC } [ WITH GRANT OPTION ] . Hint .<privilege>] ON [ PROCEDURE ] [<database-name>.<database-name> ] | AS DEFAULT } [ WITH NULL PASSWORD ] .<monitor_privilege>] MONITOR [ {PRIVILEGES | BUT NOT <monitor-privilege> [….<user-name> ] | PUBLIC } [ WITH GRANT OPTION ] . All granted privileges are stored in the Data Dictionary.Simplicity by Design GRANT Statement Compatibility: ANSI The GRANT statement is used to explicitly provide one or more privileges to one or more users.<monitor-privilege>]} ] TO [ ALL ] { <user-name> [….<host-id>] } TO { <database-name> [….

<database-name> ] | AS DEFAULT } . The REVOKE syntax to provide MONITOR operations: REVOKE [GRANT OPTION FOR ] <monitor-privilege> [….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.<monitor-privilege>] MONITOR [ {PRIVILEGES | BUT NOT <monitor-privilege> […. THE REVOKE syntax for SQL privileges: REVOKE [GRANT OPTION FOR ] [ { ALL | ALL BUT } ] <privilege> [….Man The REVOKE syntax forLOGON: REVOKE LOGON { ALL | <host-id> [….<monitor-privilege>]} ] { TO | FROM } [ ALL ] { <user-name> [….<privilege>] ON [ PROCEDURE ] [<database-name>.<host-id>] } { { TO | FROM } { <database-name> [….<user-name> ] | PUBLIC } .<user-name> ] | PUBLIC } . Hint . The ALL causes the privilege(s) to cascade downward to all dependents of the user specified. It is not a good idea to use PUBLIC in Teradata due to the larger number of users. All granted privileges are stored in the Data Dictionary. The monitor privileges: • MONRESOURCE • MONSESSION • ABORTSESSION • SETRESRATE • SETSESSRATE Page 140 The SQL Quick Reference Guide .]<object-name> { TO | FROM } [ ALL ] { <user-name> [….

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. The SQL Quick Reference Guide Page 141 . The GIVE syntax: GIVE { <database-name> | <user-name> } TO { <database-name> | <user-name> } . This transfer reallocates all space and privileges with it.

1 byte of storage per maximum. i.147. and Seconds 2.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. total 18 digits on either side of the Smallest value DEC(18. Minute. Hour. Month.647 -32. Data Type Description Data Value Range INTEGER Signed whole number -2.Y) Synonym for DECIMAL Same as DECIMAL Same as DECIMAL FLOAT Floating Point Format <value>x103 0 7 to <value>x10 308 (IEEE) REAL Stored internally as FLOAT PRECISION Stored internally as FLOAT DOUBLE PRECISION Stored internally as FLOAT CHARACTER (X) Fixed length character 1 to 64. The system only VARYING (X) character.483.648 to SMALLINT Signed smaller whole number DECIMAL (X.000 characters as a CHARACTER string. 100 for Year 2000) TIME Identifies a field as a TIME value with Hour. years from 1900.767 Page 142 The SQL Quick Reference Guide .0) Where: X=1 thru 18.18) number of digits in the decimal point number And Y=0 thru 18 digits to the right of the decimal NUMERIC (X.147. Minutes and Seconds TIMESTAMP Identifies a field as a TIMESTAMP value with Year.e.000 characters long. plus 2 bytes to stores the characters presented CHAR VARYING (X) record length of actual data to it. CHAR (X) string.Y) Signed decimal number Largest value DEC(18. 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.483. 1 byte of storage per pads to length with space Where: X=1 thru 64000 character.768 to 32. VARCHAR (X) Variable length character 1 to 64. Day.

000 characters (maximum data length) The system only stores the characters provided. 9 Decimal digit. It provides for more predictable result sets. The SQL Quick Reference Guide Page 143 . All leading zeroes are shown if the format mask is longer than the data value. Primarily used on imported data without actual decimal point.e.000 bytes Where: X=1 thru 64000 VARBYTE (X) Variable length binary 1 to 64. 99999 or 9(5). E or e Exponential. G or g Graphic data. Each X represents one character.000 KANJI Where: X=1 thru 32000 bytes (2 bytes per character) characters VARGRAPHIC (X) Variable length string of 161 to 32.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. the user should use BTEQ.000 characters as a Where: X=1 thru 32000 bit bytes maximum.e.Man Basic Numeric and Character Data Formatting Symbols Symbol Mask character and how used X or x Character data. not trailing spaces. Can repeat value – i. These symbols allow the user to control the way data can be inserted into a row and displayed in the result set. Can repeat value – i. unless you trick it. GGGGG or G(5). Holds place for numeric digit for a display 0 through 9. Be sure to keep in mind that the ODBC will ignore formatting. To see true formatting. Can repeat value – i. V or v Implied decimal point.000 bytes Where: X=1 thru 64000 LONG VARCHAR Variable length string 64. The system only stores characters provided. Format Symbols Forma tting symbols are very powerful.e. Aligns the end of the mantissa and the beginning of the exponent.) GRAPHIC (X) Fixed length string of 16-bit 1 to 32. XXXXX or X(5). Aligns data on a decimal value.KANJI or Katakana) character. Hint . Each G represents one logical (double byte .

With the proper keyboard. . when significant. Also used for: phone numbers.9999’) AS Z_press (FORMAT ‘$$$$. Inserted where appears in format mask. Period. Used primarily for display of percentage – i.99 Z or z Zero-suppressed decimal digit.53 .991001 SELECT ‘ABCDE’ (FORMAT ‘XxX’) AS Fmt_Shorter (FORMAT ‘999-999-9999’) AS Fmt_Phone (FORMAT ‘ZZZZZZ9. Pound and Yen. . Used primarily for dates and negative numeric values.The SQL Reference Guide Advanced Numeric and Character Formatting Symbols Symbol Mask character and how used $ Fixed or floating dollar sign. Also used for: dates and comma in some currencies. Insert a space where appears in format mask. % Percent character. and social security (USA). Used primarily to make large numbers easier to read.Dash character. Inserted where appears in format mask. Used primarily for dates. Primary use to align decimal point position.2014859999 . 99% vs. / Slash character.1021.e.99’) AS Fmt_Pay . All leading zeroes (insignificant) are shown as space since their presence does not change the value of the number being displayed. . Inserted where appears in format mask. additional currency signs are available: Cent. Comma. Inserted where appears in format mask. . Inserts a $ or leaves spaces and moves (floats) over to the first character of a currency value. zip codes. Holds place for numeric digit displays 1 through 9 and 0. B or b Blank data. Page 144 The SQL Quick Reference Guide . .$$$.

Date Formatting Symbols Symbol Mask character and how used (not case specific) M or m Month. When ‘MMM’ is specified. The SQL Quick Reference Guide Page 145 . D or d Day. However. Allows day to be displayed any where in the date display. the numeric (01-12) value is available. When ‘MM’ is specified. Y or y Year. The normal th century with the 19YY ‘YY’ has been used for many years for the 20 st century.991001(date) (FORMAT ‘YYYY-mm-dd’) AS Fmt_ANSI . the three character (JAN-DEC) value is available. the three-digit day of the year (001-366) value is available. When ‘DDD’ is specified.9991001(date) (FORMAT ‘yy/mm/dd’) AS Fmt_Teradata . Allows day to be displayed any where in the date display. a user may also format Dates. Allows month to be displayed any where in the date display. the numeric (01-31) value is available. since we have moved into the 21 recommended that the ‘YYYY’ be used. it is assumed. When ‘DD’ is specified. SELECT 991001(date) (FORMAT ‘Yyddd’) AS Fmt_Julian .Simplicity by Design In addition to have the abilit y to format Numeric and Character Data Types.

The values of x must be between -1 and 1. trigonometric and hyperbolic math functions: Operator Operation performed Modulo returns the remainder from a division (1 mod 2 derives MOD x ABS( x ) EXP( x) LOG( x ) LN( x ) SQRT( x ) COS( x ) SIN( x ) TAN( x) ACOS( x) ASIN( x) ATAN( x ) ATAN2 (x. inclusive. etc can be used to shift the decimal of any number to the left by the number of zeroes in the MOD operator. As such. ( SQRT(10) derives the value 3. inclusive where x is any valid number expression that expresses an angle in radians. 0 times with a remainder of 1. The returned angle is in the range ?/2 to ??/2 radians. If both x and y are 0. inclusive. Returns the arccosine of x. The returned angle is in the range 0 to ??radians. The ratio is the length of the side opposite to the angle divided by the length of the hypotenuse. The ratio is the length of the side adjacent to the angle divided by the length of the hypotenuse. The returned angle is between ? and ?? radians.The SQL Reference Guide APPENDIX D: Mathematical Functions This is a chart of those Teradata arithmetic. inclusive. A positive result represents a counterclockwise angle from the x-axis where a negative result represents a clockwise angle. Returns the hyperbolic sine of ( x) where x is any real number. the absolute value of a negative number is the same number as a positive x. The ATAN2(x.y) equals ATAN(y/x).y) coordinates.y). 2 goes into 1. The result lies in the range -1 to 1. excluding ? . Returns the arcsine of ( 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. 2 mod 10 derives 2. Returns the hyperbolic cosine of ( x) where x is any real number. The returned angle is in the range ?/2 to ??/2 radians.16227766016838E000) Takes an angle in radians (x ) and returns the ratio of two sides of a right triangle. MOD 100. except that x can be 0 in ATAN2(x. ( LOG(10) derives the value 1. ( LN(10) derives the value 2. as the remainder of division. 10 goes into 2. Takes an angle in radians (x ) and returns the ratio of two sides of a right triangle. Then. MOD 2 returns 0 for even numbers and 1 for odd. MOD always returns 0 thru x-1. Page 146 The SQL Quick Reference Guide .20264657948067E004 ) Logarithm calculus function. ( EXP(10) derives 2. MOD 1000. Takes an angle in radians (x ) and returns the ratio of two sides of a right triangle. The arctangent is the angle whose tangent is arg.0000000000000E000 ) Natural logarithm. inclusive where x is any valid number expression that expresses an angle in radians.y) and x cannot be 0 in ATAN(y/x) since this will result in a divide by zero error. (ABS(10-12) = 2) Exponentiation. Absolute value. The values of x must be between -1 and 1. inclusive. The arctangent is the angle from the x-axis to a line contained the origin(0.y ) COSH( x ) SINH( x ) 1. The arccosine is the angle whose cosine is x where x is the cosine of the returned angle. an error is returned. MOD 7 can be used to determine the day of the week.0) and a point with coordinates (x. inclusive. The arcsine is the angle whose sine is x where x is the sine of the returned angle. Returns the arctangent of ( x) . 0 times with a remainder of 2). The result lies in the range -1 to 1. and MOD 10. Returns the arctangent of the specified (x.30258509299405E000 ) Square root. e raised to a power.

SELECT Student_Table. Returns the inverse hyperbolic tangent of ( x) .level reference: <table -name>. The inverse hyperbolic tangent is the value whose hyperbolic tangent is a number so that x is any real number between 1 and -1.Student_Id FROM Student_Table INNER JOIN Student_Course_Table ON Student_Table. 1.level reference: <database.Dept_No FROM Employee_Table .name> 2. Returns the inverse hyperbolic sine of ( x) .name>.<table .<column. 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.name>.Simplicity by Design TANH( x ) ACOSH( x) ASINH( x) ATANH( x) Returns the hyperbolic tangent of ( x) where arg is any real number. Qualifying Column Names 3. The SQL Quick Reference Guide Page 147 . excluding 1 and -1). Returns the inverse hyperbolic cosine of ( x) .<table . SELECT * FROM SQL_CLASS. The inverse hyperbolic cosine is the value whose hyperbolic cosine is a number so that x is any real number equal to. The inverse hyperbolic sine is the value whose hyperbolic sine is a number so that x is any real number.name> 2.Student_Id .<column-name> SELECT SQL_CLASS.name>.level reference: <database.Employee_Table .Employee_Table.Student_Id = Student_Course_Table. or greater than.

as CUST .list> FROM <table.Customer_Name FROM Customer_Table as CUST .name> AS <table-alias-name> . SELECT STU. SELECT * FROM Customer_Table SELECT CUST.Customer_Name FROM Customer_Table CUST . SELECT CUST.Student_Id . SELECT * FROM Customer_Table CUST .Student_Id. SELECT <column. Page 148 The SQL Quick Reference Guide .The SQL Reference Guide Creating an Alias for a Table Once an alias is established for a table. asSTU_COUR Alternative Syntax: SELECT <column.name><table-alias-name> .Student_Id = STU_COUR. the alias must be used or the real table will also be included in the query and possibly cause a product join. STU_COUR.list> FROM <table.Course_Id FROM Student_Table as STU INNER JOIN Student_Course_Table ON STU.

]<procedure-name> ( [ <parameter. for each ro w returned from Teradata. This appendix is a focus on the Create Syntax.Man The following is a list of all the SPL features that Teradata supports: BEGIN / END Establishes the range of the <procedure-body>. please refer to “Teradata SQL: Unleash the Power”.name>. and all the possible Stored Procedure Language (SPL) options. CREATE PROCEDURE [<database. if statements. flexible. LOOP / END LOOP Defines the length of the loop. Hint . and easy to write. SET Establishes a value to a variable in the procedure.Simplicity by Design APPENDIX F: Stored Procedure Syntax Stored Procedures are a relatively new concept for Teradata. DECLARE Introduces local variables or handlers to the procedure. WHILE / END WHILE Loop with a conditional test before the code in the loop. PRINT Used for testing and debugging of a procedure. Detailed information is included on each SPL feature. ITERATE Terminates the remaining steps in any loop. Chapter 21. For further information about Stored Procedures and SPL. IF / END IF Provides a conditional test for a given variable.list> ] ) <procedure. LEAVE Used to exit a loop prematurely. they are quite powerful. returning back to corresponding Label. CALL Executes one procedure from the procedure being run. This is the simplest syntax for a stored procedure with <procedure-body> including loops. FOR / END FOR Serves as a FOR Loop. The SQL Quick Reference Guide Page 149 .body> . and other SPL choices. Despite being new. and the whole concept of Stored Procedures.

126. 100 ABS(X ) 146 ACOS( X ) 146 ACOSH( X ) 147 Add_Months i. 113 And/Or 4. 127. 129. 129. 111. 136. 93. 121 After Triggers i.Index of Contents A Abort i. 88. 86. 130. 83. 5 Ansi Mode 25. 88. 135. 51. 129. 126. 121 View i. 127. 36 COS( X) 146 COSH( X ) 146 Count (Count) 31 Create Database i. 97. 121 Before Triggers i. 76. 113. 127. 95. 130. 133 Byte (X) 143 Byteint 51. 110. 138 Upsert iii. 100. 42. 136 Current_Time 50. 93. 133. 81. 100. 13 Alter Table i. 99. 131. 133 Compress Null 110 Correlated Subquery i. 84. 4. 45 Current Reserved Words 134. 80 Data Types Byte (X) 143 Byteint 51. 74. 79. 133. 72. 110. 51. 84. 132. 135 Zeroifnull 4. 11. 95. 138 Insert ii. 110. 130. 134. 107 AS i. 110. 75. 47. 13. 86. 87. 120. 144. 89 Cross Join i. 129 Begin / End 149 Between i. 98. 142 Graphic (X) 143 . 145 ASIN( X) 146 ASINH( X) 147 ATAN( X) 146 ATAN2 ( X. 138 Insert / Select ii. 80. 4. 78. 133. 133. 85. 113. 133 Casespecific i. 100 Compress 110. 132. 143 Character (X) 142 Date ii. 95. 96. 24. 80. 45 Case i. 133 Nullif iii. 135 Nullifzero iii. 79. 131. 118 Commit Work i. 99. 74 Update iii. 120. 111. 132. 51. 77. 136 Data Manipulation Delete ii. 48 After Journal 109. 93 Table i. 142 Decimal (X. 73. 131. 86. 25. 133 Current_Timestamp 50. 133 Coalesce i. 112 User i. 4. 82. 93.Y) 142 Double Precision 142 Float 134. 133 D Data Control Language (Dcl) 138 Data Interrogation Case i. 105. 101. 85. 130. 79. 149 Cartesian Product Join i. 133 Collect Statistics i. 143 C Calendar_Date 51 Call 133.Y ) 146 ATANH(X ) 147 Average (Avg) i B Befor e Journal 109. 130 Aliasing Columns i. 87. 126. 133 Character (X) 142 Character Set 110 Characters 52 Coalesce i. 120 Global Temporary Table 127 Macro i.

117. 111. 110. 90 Drop Statistics ii. 110. 142 Timestamp 4. 142 Long Varchar 143 Numeric (X. 136. 142 Real 135. 133. 135. 142 Time 4. 144.Integer 51. 134.Y) 142 Precision 135. 123 Index 55 Moving Average (Mavg) 61 Moving Difference (Mdiff) 62 Moving Sum (Msum) 60 Position 55 Quantile 63 Random 66 Rank 64 Substring And Substr 54 Trim 53 Future Reserved Words 137 G Give 141 Global Temporary Table ii. 111 Default Time 110 Default User 110 Default Value 110 Delete ii. 77. 95. 121. 67. 110. 130. 70. 142 Integerdate 46 Date Functions Add_Months i. 93. 111. 106. 71. 142 Smallint 51. 110. 107. 19. 131. 51. 22. 123. 127. 16. 4. 126. 120 Drop 122 Give 141 Grant 139 Revoke 140 DATE ii. 142 Varbyte (X) 143 Varchar (X) Character 142 Vargraphic (X) 143 Database Create i. 133 Extract ii. 95 Table ii. 108. 34. 129. 133. 134 Float 134.Y) 142 Declare 133. 105. 78. 94 Exists 37 EXP(X ) 146 Explain ii. 110. 133. 93. 132. 49 F Fallback ii. 114 Temporary Table 128 User 122 View ii. 109. 125 Distinct ii. 124. 133. 50. 127. 124. 120. 145 Format Symbols 142. 48 Extract ii. 134 . 108. 93. 119 Dual After Journal 109 Dual Before Journa l 109 E Except ii. 138 Derived Table ii. 142 For / End For 149 Format ii. 133 Execute Macro ii. 136. 134. 37. 109. 49 Day_Of_Calendar 51 Day_Of_Month 51 Day_Of_Week 51 Day_Of_Year 51 Decimal (X. 47. 143 Function Characters 52 Cumulative Sum (Csum) 59 Hashing ii. 130. 133 Double Precision 142 Drop Database 122 Macro ii. 126. 50. 149 Default Date 110 Default Null 110. 127 Create 127 Grant 139 Graphic (X) 143 H Hashamp ii.

18. 83. 124. 134. 111. 134 Having ii. 105. 116 Unique Primary Index 105 Inner Join 40 Insert ii. 45 Cross Join i. 93. 123. 134 Hashing ii. 93. 95 Execute Macro ii. 126. 127. 149 EXP(X ) 146 For / End For 149 . 105. 72. 45 Inner Join 40 Outer Join i. 134. 108. 38 Cartesian Product Join i. 132. 109. 129. 100. 106. 149 COS( X) 146 COSH( X ) 146 Declare 133. 80. 131 Integer 51. 32 Help 2. 124. 79. 21. 67. 82. 90. 73. 94 Replace Macro 4. 134 Hashbucket ii. 81. 138 Insert / Select ii. 97. 3.Hashbakamp ii. 17.Y ) 146 ATANH(X ) 147 Begin / End 149 Call 133. 9 Index Function 55 Indexes Non. 72. 124. 114. 134 Is Null 7 Iterate 134. 119. 130. 96 Table 97 View 97 Locking Modifiers 96 LOG(X) 146 Long Varchar 143 Loop / End Loop 149 Lower And Upper 26 M Macro Create Macro i. 87 I If / End If 149 In ii. 149 Like iii. 74. 107. 117 L Leave 134. 106. 43 Join Index iii.Unique Primary Index (NUPI) 105 Primary Index iii. 110. 131. 42.Unique Primary Index 105 Non. 96. 142 Integerdate 46 Intersect ii. 149 J Join iii. 95. 124 Secondary 116 Secondary Index 4. 101. 113. 12 LN( X) 146 Locking Database 97 Modifiers iii. 115. 95 Math Functions ABS(X ) 146 ACOS( X ) 146 ACOSH( X ) 147 ASIN( X) 146 ASINH( X) 147 ATAN( X) 146 ATAN2 ( X. 68. 123 Hashrow ii. 134 Column 17 Database 17 Index 17 Macro 17 Procedure 17 Session 17 Statistics 17 Table 17 Trigger 17 User 17 View 17 Volatile Table 17 Horizontal Reporting ii. 77. 93 Drop Macro ii. 74 Instead Of Triggers ii. 73.

149 Leave 134. 116 Select 2. 96. 12. 135 Macro 18 Procedure 18 Table 18 Trigger 18 View 18 . 3. 134 Union 4. 108.If / End If 149 Iterate 134. 34. 67. 68. 79. 135 Numeric (X. 67. 99. 109. 95. 60. 52. 9 Not Null ii. 135. 111. 110. 51. 101. 69. 7. 87. 25 Not In ii. 43 P Permanent Journal iii. 106. 75. 34. 76. 105. 74. 66. 37. 72. 124 Print 149 Privileges 138 Q Qualifying Column Names 147 Quantifiers iii. 88 Non. 75. 76. 4. 81. 92. 6. 80. 93. 59.Unique Primary Index (NUPI) 105 Not iii. 142 Primary Index iii. 109. 107. 98. 149 LN( X) 146 LOG(X) 146 Loop / End Loop 149 MOD X146 Print 149 Set 4. 100. 82. 71. 95. iii. 70. 52. 136 Set Table 107 Show 18. 33. 99. 71. 19. 15 Outer Join i. 101 Rollback Work 101 S Secondary Index 4. 91 Revoke 140 Rollback i. 134 Minus iii. 67. 135 Nullifzero iii. 134 MOD X146 Month_Of_Calendar 51 Month_Of_Quarter 51 Month_Of_Year 51 Multiple Subquery iii. 80. 133 Intersect ii. 35 Quarter_Of_Calendar 51 Quarter_Of_Year 51 R Real 135. 91. 39. 14. 11. 62. 149 SIN(X ) 146 SINH( X) 146 SQRT(X) 146 TAN(X) 146 TANH( X) 147 While / End While 149 Maximum (Max) 30 Minimum (Min) 29 Minus iii. 121. 109 Position Function 55 Precision 135. 73. 95. 68. 111 Nullif iii. 10. 98. 107. 61. 135 Nested CASE iii. 34. 67. 95 Replace View 4. 115 Replace Macro 4. 112. 41. 110. 110. 37. 142 Rename Table 4.Y) 142 O Odbc 22 Order By iii. 67.Unique Primary Index (Nupi) 105 Non. 100. 67. 97. 44. 100. 108. 100. 149 Set Operators Except ii. 34. 70. 69. 132 Set 4. 83. 74. 67. 8 Not Casespecific iii. 37. 82. 79. 148 Sequencing Triggers 4. 135. 81. 37. 37. 9. 13. 110. 74. 111. 4. 121. 71. 34 Multiset Table 107 N Named i. 71.

125 Drop Table ii. 113. 50. 103. 76. 37. 80. 131 Sequencing 4. 33. 36 Multiple 34 Multiple Subqueries iii. 4. 51. 93. 136. 38. 97. 131. 110. 104. 92. 133. 40. 45. 95. 104. 115 Volatile Temporary Table 4. 136 While / End While 149 With 4. 27. 105. 136 Unique Primary Index (Upi) 105 Update iii. 31. 136. 80 User Create i. 126 W Week_Of_Calendar 51 Week_Of_Month 51 Week_Of_Year 51 Weekday_Of_Month 51 Where4. 43. 142 TIMESTAMP 4. 4. 133. 93. 19. 91 Volatile Temporary Table 4. 34. 3. 135. 66. 28. 99. 23. 35. 130. 71. 50. 100. 113 Create 105. 78. 12. 52. 142 SQRT(X) 146 String And Column Concatenation 57 Subquery Correlated Subquery i. 142 TITLE 4. 132. 34. 70. 77. 8. 36. 127 Rename Table 4. 93. 75. 26. 100. 138 Uppercase 110. 112 Create Table i. 76. 68. 114 Global Temporary 127 Global Temporary Table ii. 79. 89. 136. 125. 87. 90 Locking For Access iii. 42. 74. 117. 32. 110. 67. 130 Before i. 112 Derived Table ii. 75. 11. 30. 69. 99. 129. 92 Replace View 4. 34 Sum 27 System Calendar Columns 4. 136 Transaction Mode Setting 99 Triggers After i. 126 TAN(X) 146 TANH( X) 147 Temporary Table Drop 128 Teradata Mode 98 TIME 4. 4. 111. 136 Upsert iii. 129 Instead Of ii. 80. 7. 37. 9. 79. 89 Drop View ii. 25. 102 With Default 110 . 132 U Union 4. 91. 69. 10. 121 Drop 122 V Varbyte (X) 143 Varchar (X) Character 142 Vargraphic (X) 143 View Create View i. 95. 29.SIN(X ) 146 SINH( X) 146 Smallint 51. 79. 57. 24. 6. 5. 102. 51 Calendar_Date 51 Day_Of_Calendar 51 Day_Of_Month 51 Day_Of_Week 51 Day_Of_Year 51 Month_Of_Calendar 51 Month_Of_Quarter 51 Month_Of_Year 51 Quarter_Of_Calendar 51 Quarter_Of_Year 51 Week_Of_Calendar 51 Week_Of_Month 51 Week_Of_Year 51 Weekday_Of_Month 51 Year_Of_Calendar 51 T Table Alias 148 Alter Table i. 39.

With. 83.. 103 Y Year_Of_Calendar 51 Z Zeroifnull 4. 136 .By 4.

Sign up to vote on this title
UsefulNot useful