SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata...

195
SQL as a Second Language John HR Schuster Version 2.2c, 04/02/2019

Transcript of SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata...

Page 1: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

SQL as a Second LanguageJohn HR Schuster

Version 2.2c, 04/02/2019

jschust2
Rectangle
jschust2
Rectangle
jschust2
Rectangle
Page 2: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Table of Contents1. Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  1

1.1. Chinook Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  2

1.1.1. Chinook Business Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  2

1.2. Database Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  3

1.3. SQL Query Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  3

1.4. Consideration. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  3

2. Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  5

3. Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  8

3.1. Add Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  9

3.2. Help Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  12

3.3. tableCounts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  20

3.4. dbObjects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  23

3.5. tableColumns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  25

3.6. findColumn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  28

3.7. Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  29

3.8. Date Formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  33

3.9. System Calendar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  34

3.10. joinQuery Part A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  44

3.11. joinQuery Part B . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  45

3.12. joinQuery Part C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  46

3.13. Join Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  48

3.13.1. Inner Join . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  48

3.13.2. Outer Join . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  48

3.14. Subquery Filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  59

3.15. derivedTable 1 - Part A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  64

3.16. derived Table 1 -Part B . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  67

3.17. derivedTable 1 - Part C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  70

3.18. derivedTable 2 - Part A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  75

3.19. derivedTable 2 - Part B . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  78

3.20. derivedTable 2 - Part C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  81

3.21. derivedTable 2 - Part D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  84

3.22. Create View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  88

3.22.1. Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  88

3.23. Date Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  94

3.24. Ranking. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  97

3.25. Rollup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  101

3.26. Cube. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  105

3.27. Cube Basic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  110

Page 3: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.28. Cube Slice Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  114

3.29. Cube Create . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  118

3.30. Cube Insert. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  120

3.31. Cube Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  122

3.32. Parameter Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  132

3.33. Parameter Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  136

3.34. Volatile Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  143

3.35. Copy Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  152

4. Python Teradata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  159

4.1. Verifying Python. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  159

4.2. Install Teradata Python Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  160

4.3. Hello World . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  161

4.4. Get Cube . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  163

5. REST Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  166

5.1. REST Request . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  167

5.2. REST Response . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  168

6. Power-BI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  171

6.1. Get Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  171

6.2. Server Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  173

6.3. Login . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  174

6.4. Navigation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  174

6.5. Select Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  175

6.6. Edit queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  177

7. Tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  181

7.1. Aggregate Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  181

7.2. Column Alias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  181

7.3. Dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  181

7.4. DDL queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  181

7.5. Derived Tables (Sub-Queries) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  181

7.6. Formatting / Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  182

7.7. Join . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  182

7.8. Naming practice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  182

7.9. OLAP Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  182

7.10. Order By . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  182

7.11. Parameter fields (Prompts) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  183

7.12. Select columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  183

7.13. Table Alias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  183

7.14. Teradata Specific . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  184

7.15. Union. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  184

7.16. Where . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  184

8. Contact Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  185

Page 4: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

9. Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  186

9.1. Related Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  186

9.2. Teradata links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  186

9.3. Chinook database creation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  186

9.4. Column Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  186

10. Document History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  189

10.1. Documentation Maintenance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  190

11. Format filler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  190

11.1. Format Filler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  190

11.2. Format Filler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  190

11.3. Format Filler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  190

11.4. Format Filler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  190

11.5. Format Filler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  190

11.6. Format Filler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  191

11.7. Format Filler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  191

Page 5: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

SQL as a Second Language (SASL) was a course that I taught many moons ago. Itis being revisited now to help answer some SQL questions brought up by thosewhose are taking their Teradata SQL Skills to the next level.

A PDF version of this web site is available at this Link

The Web version of the document is available at this link

The GitHub version of this document is available at this link

1. IntroductionThis SQL As a Second Language version will use the Teradata SQL syntax.

Examples

A teacher, a really good teacher, is never a giver of truth; he is a guide, apointer to truth

— Bruce Lee

1

Page 6: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

1.1. Chinook DatabaseThe learning database will be the Chinook database on music record sales.

The learning database will be on the DRBC Teradata server and it’s name is DCH_Training.

To access the learning database please send a message to the author with your DRBC user name.

Reference: https://github.com/lerocha/chinook-database

Figure 1. Chinook Database Diagram

1.1.1. Chinook Business Rules

1. Each Artist has 1 or more Albums

2. Each Album has just 1 Artist

3. Each Album has 1 or more Tracks

4. Each Track has just 1 Genre

5. Each Track has just 1 Media Type

6. Tracks have playtime measured in milliseconds

7. Tracks have disk space measured in bytes

8. Each Employee has just 1 Manager, who is also an Employee

9. Each Customer has 1 or more Invoices

10. Each Customer has just 1 support rep who is an Employee

11. Each Invoice has 1 or more Invoice Lines

12. Each Invoice Line is related to just 1 Track

13. Invoices span 2014 - 2018

2

Page 7: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

14. Each Playlist has 1 or more Tracks

15. Not all Genre have Tracks

16. Not all Employees who are support reps have customers

The Chinook database will be known as the DCH_Training located on the DRBC server.

1.2. Database ObjectsIn this document the term Database Object is used to indicate one of the following Teradatadatabase elements.

• Table (All types)

• View

• Stored Procedure

• Macro

The reason for the term Database Object is to eliminate the confusion that can occur when objectschange. (IE: A view you created is materialized into a table, a query you wrote is changed into astore procedure)

1.3. SQL Query ToolsThere are a variety of SQL tools that can be used to develop and utilize the Teradata database.

• Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package

• Teradata Studio - Available as a separate download

• Database 5 Pro - Intuitive multiple database manager, portable (Authors preference)

• DBeaver - Free, open source, multi-platform universal database tool

Many of the screen captures will be done using Database 5 Pro.

1.4. ConsiderationConsideration should be given to those who helped teach me about Teradata and Teradata SQL. Youwill see various quotes that were Words of Wisdom from them through out this guide.

While the definitions and examples in this guide may not be the best or the most exact they werewritten this way to help facilitate learning. There are many correct solutions to getting a set ofresults from any database. Some may be more efficient and others may be easier to understand.The goal should be to get a good set of "Basics" and build them up by asking questions andexperimenting.

As new versions of the Teradata Database are being released there may be some of the queries inthe Learning Guide that need to be adjusted. This guide was originally written for Teradata Version

3

Page 8: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

16.10 .

The author makes no claim to being good at spelling or grammar. The author is good at math, datascience and engineering. Please provide any corrections or suggestion to the author.

4

Page 9: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

2. QuestionsTo ask a New question to be added to this list, please email it [email protected].

How can I add another database to the Database Explorer panel of SQL-Assistant?

View this query Add Database

I’m not allowed to use the help database command, is there some other way to get informationon the tables and columns of a database?

View this query Help Database

How can I get a count of the number of rows in some of the tables of a database?

View this query tableCounts

How can a get a list of the objects (Tables, View, Procedures) for a specific database?

View This query dbObjects

How can I find out the columns and metadata about a specific object (Table, View)?

View this query tableColumns

How can I find where a specific column exist in a database?

View this query findColumn

I would like to know when to use what numeric data type (i.e. smallint, integer, bigint,numeric(x,y), and decimal(x,y))?

View this query Numbers

How can I format a date column so it returns MM/YYYY without changing it to a string?

View this query [dateFormat]

How do I Join two tables together?

View this query joinQuery Part B

How do I restrict the results by a column that contains some string?

View this query joinQuery Part C

How do I select or restrict a date column by month, day or year?

View this query Date Filters

How do I sort the results by multiple columns?

View this query joinQuery Part C

How do I use a sub-query to collect information?

View this query derivedTable 1 - Part A

How do I use a sub-query to reduce or filter information?

View this query [derivedTable2A]

5

Page 10: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

How can I use a subquery to be used as a filter in a main query with aggregates?

View this query Subquery Filter

When do I use the having clause?

View this query [derivedTable2PartD]

When is it a good idea to use a view?

Visit this query Create View

When do I use a inner join versus an outer join?

Visit this query Join Types

How and why would I use the System Calendar?

Visit this query System Calendar

How do a do a Running Total (Cumulative Sum)?

View this query Date Filters

How can a do a ranking of the results?

View this query Ranking

How can I get totals rolled up by different groupings?

View this query Rollup

How can I use a Cube to get analytical information?

View this query Cube

How can I use Case to do logical IF statements?

View this query Cube Slice Type

How can I best use "Prompts" in SQL Assistant?

View this query Parameter Fields

How can I create a set of responses for Prompts and use them in a query?

View this query Parameter Table

I don’t have Perm Space how can I create a table with data for my queries?

View this query Volatile Table

How can a make a copy of a table?

View this query Copy Table

How can I use Python with Teradata?

View this section Python Teradata

What is REST, can I use it with Teradata?

View this section REST Services

6

Page 11: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

What is Poweer-BI and how can I get started to use it with Teradata? View this section Power-BI

7

Page 12: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3. QueriesThe queries in this document are not presented in any particular order.

These queries were constructed to answer specific questions from the students.

Whenever possible the actual SQL query statement is shown and can be downloaded. These queriescan be the starting point for learning how to perform some function.

There are numbered call-outs on the SQL queries which are defined at the end of the query. Thesecall-outs are used to help highlight techniques or direct attention to subject matter.

The results of each query are shown and may vary slightly from the edition of the Chinookdatabase you are using.

If the query does not contain an order by clause then the results come back in arandom order. TThis is normal for the Teradata database.

8

Page 13: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.1. Add DatabaseThe Database Explorer panel of Teradata SQL-Assistant doesn’t show all databases. To add adatabase to the Database Explorer panel follow these steps.

Figure 2. Initial database Explorer list

1. Right-Click on the ODBC name (ie: DRBC) this will change depending on which Teradata serveryou are connected to.

2. Click on the Add Database selection

9

Page 14: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Figure 3. Add database dialog

1. Type the name of the database you want added (ie: DCH_Training)

2. Click on the OK button

10

Page 15: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Figure 4. Database Added

1. The new database is added to the Database Explorer panel. By clicking on the (+) next to thedatabase name the window will expand to show a list of database object categories.

2. By clicking on the (+) symbol next to an object it will expand to show it’s components.

Back to [top].

11

Page 16: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.2. Help DatabaseIn some organizations the Help Database in not available or allowed for all databases. This queryprovides a list of all the tables and columns of a specific database.

Some database are very large and this query could take a long time to run andreturn a very large result set. Try to use the help database and help table beforeusing this query.

The results from this query could be exported to a CSV file and used in Excel orother Windows application for looking at the information about the tables andcolumns.

SQL Example

/*

=== replace `Help Database`

In some installations the `Help Database` is not allowed.This query provides a list of all the database objects in the database you entered.

==== Topics

* Column Alias, rename a column* Order by, also known as sorting* Where, results filter or restriction* Teradata Specific syntax*/

select  DatabaseName  ,TableName  ,ColumnName  ,ColumnFormat  ,ColumnType  ,ColumnLength  ,Nullable  ,CreateTimeStamp as createdDate ①  ,LastAccessTimeStamp as lastAccessed ①from dbc.columnsXwhere DatabaseName = 'DCH_Training' ②order by  DatabaseName  ,TableName  ,ColumnID ③

12

Page 17: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

① Column alias

② Where clause to view tables and columns from just DCH_Training database

③ The ColumnID is used to make the results appear in the same order as the Create Table (akaNatural order). You could replace ColumnID with ColumnName to get a list ordered by thecolumn name.

SQL Download link click here

Table 1. Results

DatabaseName

TableName

ColumnName

ColumnFormat

ColumnType

ColumnLength

Nullable createdDate

lastAccessed

DCH_TRAINING

Album AlbumId -(10)9 I 4 N 2019-01-1110:31:51

2019-02-0409:15:17

DCH_TRAINING

Album AlbumTitle

X(160) CV 160 N 2019-01-1110:31:51

2019-02-0409:15:17

DCH_TRAINING

Album ArtistId -(10)9 I 4 N 2019-01-1110:31:51

2019-02-0409:15:17

DCH_TRAINING

Artist ArtistId -(10)9 I 4 N 2019-01-1110:47:12

2019-02-0409:15:17

DCH_TRAINING

Artist Name X(120) CV 120 Y 2019-01-1110:47:12

2019-02-0409:15:17

DCH_TRAINING

CountrySaleYearGene_Cube

CubeID -(10)9 I 4 N 2019-01-1610:59:34

2019-01-1610:59:44

DCH_TRAINING

CountrySaleYearGene_Cube

Country X(40) CV 40 Y 2019-01-1610:59:34

2019-01-1612:54:17

DCH_TRAINING

CountrySaleYearGene_Cube

SaleYear -(10)9 I 4 Y 2019-01-1610:59:34

2019-01-1612:54:17

DCH_TRAINING

CountrySaleYearGene_Cube

GenreName

X(120) CV 120 Y 2019-01-1610:59:34

2019-01-1612:54:17

DCH_TRAINING

CountrySaleYearGene_Cube

TrackCount

-(10)9 I 4 Y 2019-01-1610:59:34

2019-01-1612:54:17

DCH_TRAINING

CountrySaleYearGene_Cube

SaleTotal ---------.99 D 8 Y 2019-01-1610:59:34

2019-01-1612:54:17

13

Page 18: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

DatabaseName

TableName

ColumnName

ColumnFormat

ColumnType

ColumnLength

Nullable createdDate

lastAccessed

DCH_TRAINING

CountrySaleYearGene_Cube

SliceType X(20) CV 20 Y 2019-01-1610:59:34

2019-01-1612:54:17

DCH_TRAINING

Customer CustomerId

-(10)9 I 4 N 2019-01-1110:47:38

2019-01-1110:47:51

DCH_TRAINING

Customer FirstName

X(40) CV 40 N 2019-01-1110:47:38

2019-01-1110:47:51

DCH_TRAINING

Customer LastName X(20) CV 20 N 2019-01-1110:47:38

2019-01-1110:47:51

DCH_TRAINING

Customer Company X(80) CV 80 Y 2019-01-1110:47:38

2019-01-1110:47:51

DCH_TRAINING

Customer Address X(70) CV 70 Y 2019-01-1110:47:38

2019-01-1110:47:51

DCH_TRAINING

Customer City X(40) CV 40 Y 2019-01-1110:47:38

2019-01-1110:47:51

DCH_TRAINING

Customer State X(40) CV 40 Y 2019-01-1110:47:38

2019-01-1110:47:51

DCH_TRAINING

Customer Country X(40) CV 40 Y 2019-01-1110:47:38

2019-01-1110:47:51

DCH_TRAINING

Customer PostalCode

X(10) CV 10 Y 2019-01-1110:47:38

2019-01-1110:47:51

DCH_TRAINING

Customer Phone X(24) CV 24 Y 2019-01-1110:47:38

2019-01-1110:47:51

DCH_TRAINING

Customer Fax X(24) CV 24 Y 2019-01-1110:47:38

2019-01-1110:47:51

DCH_TRAINING

Customer Email X(60) CV 60 N 2019-01-1110:47:38

2019-01-1110:47:51

DCH_TRAINING

Customer SupportRepId

-(10)9 I 4 Y 2019-01-1110:47:38

2019-01-1110:47:51

14

Page 19: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

DatabaseName

TableName

ColumnName

ColumnFormat

ColumnType

ColumnLength

Nullable createdDate

lastAccessed

DCH_TRAINING

Employee EmployeeId

-(10)9 I 4 N 2019-01-1110:53:55

2019-01-1111:03:20

DCH_TRAINING

Employee LastName X(20) CV 20 N 2019-01-1110:53:55

2019-01-1111:03:20

DCH_TRAINING

Employee FirstName

X(20) CV 20 N 2019-01-1110:53:55

2019-01-1111:03:20

DCH_TRAINING

Employee EmployeeTitle

X(30) CV 30 Y 2019-01-1110:53:55

2019-01-1111:03:20

DCH_TRAINING

Employee ReportsTo

-(10)9 I 4 Y 2019-01-1110:53:55

2019-01-1111:03:20

DCH_TRAINING

Employee BirthDate yyyy-mm-dd

DA 4 Y 2019-01-1110:53:55

2019-01-1111:03:20

DCH_TRAINING

Employee HireDate yyyy-mm-dd

DA 4 Y 2019-01-1110:53:55

2019-01-1111:03:20

DCH_TRAINING

Employee Address X(70) CV 70 Y 2019-01-1110:53:55

2019-01-1111:03:20

DCH_TRAINING

Employee City X(40) CV 40 Y 2019-01-1110:53:55

2019-01-1111:03:20

DCH_TRAINING

Employee State X(40) CV 40 Y 2019-01-1110:53:55

2019-01-1111:03:20

DCH_TRAINING

Employee Country X(40) CV 40 Y 2019-01-1110:53:55

2019-01-1111:03:20

DCH_TRAINING

Employee PostalCode

X(10) CV 10 Y 2019-01-1110:53:55

2019-01-1111:03:20

DCH_TRAINING

Employee Phone X(24) CV 24 Y 2019-01-1110:53:55

2019-01-1111:03:20

DCH_TRAINING

Employee Fax X(24) CV 24 Y 2019-01-1110:53:55

2019-01-1111:03:20

15

Page 20: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

DatabaseName

TableName

ColumnName

ColumnFormat

ColumnType

ColumnLength

Nullable createdDate

lastAccessed

DCH_TRAINING

Employee Email X(60) CV 60 Y 2019-01-1110:53:55

2019-01-1111:03:20

DCH_TRAINING

Genre GenreId -(10)9 I 4 N 2019-01-1111:03:59

2019-01-3021:40:29

DCH_TRAINING

Genre Name X(120) CV 120 Y 2019-01-1111:03:59

2019-01-3021:40:29

DCH_TRAINING

Invoice InvoiceId -(10)9 I 4 N 2019-01-1111:12:12

2019-01-2511:44:46

DCH_TRAINING

Invoice CustomerId

-(10)9 I 4 N 2019-01-1111:12:12

2019-01-1610:53:09

DCH_TRAINING

Invoice InvoiceDate

yyyy-mm-dd

DA 4 N 2019-01-1111:12:12

2019-01-2511:44:46

DCH_TRAINING

Invoice BillingAddress

X(70) CV 70 Y 2019-01-1111:12:12

2019-01-1115:32:31

DCH_TRAINING

Invoice BillingCity

X(40) CV 40 Y 2019-01-1111:12:12

2019-01-1115:32:31

DCH_TRAINING

Invoice BillingState

X(40) CV 40 Y 2019-01-1111:12:12

2019-01-1115:32:31

DCH_TRAINING

Invoice BillingCountry

X(40) CV 40 Y 2019-01-1111:12:12

2019-01-1612:08:25

DCH_TRAINING

Invoice BillingPostalCode

X(10) CV 10 Y 2019-01-1111:12:12

2019-01-1115:32:31

DCH_TRAINING

Invoice Total ---------.99 D 8 N 2019-01-1111:12:12

2019-01-2511:44:46

DCH_TRAINING

InvoiceLine

InvoiceLineId

-(10)9 I 4 N 2019-01-1111:12:55

2019-01-1610:56:04

DCH_TRAINING

InvoiceLine

InvoiceId -(10)9 I 4 N 2019-01-1111:12:55

2019-01-2511:44:46

16

Page 21: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

DatabaseName

TableName

ColumnName

ColumnFormat

ColumnType

ColumnLength

Nullable createdDate

lastAccessed

DCH_TRAINING

InvoiceLine

TrackId -(10)9 I 4 N 2019-01-1111:12:55

2019-01-2511:44:46

DCH_TRAINING

InvoiceLine

UnitPrice ---------.99 D 8 N 2019-01-1111:12:55

2019-01-1111:13:29

DCH_TRAINING

InvoiceLine

Quantity -(10)9 I 4 N 2019-01-1111:12:55

2019-01-1111:13:29

DCH_TRAINING

MediaType

MediaTypeId

-(10)9 I 4 N 2019-01-1111:14:01

2019-01-2809:32:03

DCH_TRAINING

MediaType

Name X(120) CV 120 Y 2019-01-1111:14:01

2019-01-1111:14:06

DCH_TRAINING

Playlist PlaylistId -(10)9 I 4 N 2019-01-1111:14:28

2019-01-1111:14:36

DCH_TRAINING

Playlist Name X(120) CV 120 Y 2019-01-1111:14:28

2019-01-1111:14:36

DCH_TRAINING

PlaylistTrack

PlaylistId -(10)9 I 4 N 2019-01-1111:14:47

2019-01-1111:16:21

DCH_TRAINING

PlaylistTrack

TrackId -(10)9 I 4 N 2019-01-1111:14:47

2019-01-1111:16:21

DCH_TRAINING

Track TrackId -(10)9 I 4 N 2019-01-1111:16:55

2019-02-0409:15:17

DCH_TRAINING

Track Name X(200) CV 200 N 2019-01-1111:16:55

2019-02-0409:15:17

DCH_TRAINING

Track AlbumId -(10)9 I 4 Y 2019-01-1111:16:55

2019-02-0409:15:17

DCH_TRAINING

Track MediaTypeId

-(10)9 I 4 N 2019-01-1111:16:55

2019-01-2809:32:03

DCH_TRAINING

Track GenreId -(10)9 I 4 Y 2019-01-1111:16:55

2019-01-3021:24:22

17

Page 22: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

DatabaseName

TableName

ColumnName

ColumnFormat

ColumnType

ColumnLength

Nullable createdDate

lastAccessed

DCH_TRAINING

Track Composer X(220) CV 220 Y 2019-01-1111:16:55

2019-02-0409:15:17

DCH_TRAINING

Track Milliseconds

-(10)9 I 4 N 2019-01-1111:16:55

2019-01-1610:50:00

DCH_TRAINING

Track SizeBytes -(10)9 I 4 Y 2019-01-1111:16:55

2019-01-1111:20:09

DCH_TRAINING

Track UnitPrice ---------.99 D 8 N 2019-01-1111:16:55

2019-01-1111:20:09

DCH_TRAINING

vAlbum AlbumId NULL NULL NULL NULL 2019-01-1611:02:01

NULL

DCH_TRAINING

vAlbum AlbumTitle

NULL NULL NULL NULL 2019-01-1611:02:01

NULL

DCH_TRAINING

vAlbum ArtistId NULL NULL NULL NULL 2019-01-1611:02:01

NULL

DCH_TRAINING

vAlbum artistName

NULL NULL NULL NULL 2019-01-1611:02:01

NULL

DCH_TRAINING

vAlbum TrackId NULL NULL NULL NULL 2019-01-1611:02:01

NULL

DCH_TRAINING

vAlbum titleName NULL NULL NULL NULL 2019-01-1611:02:01

NULL

DCH_TRAINING

vAlbum Composer NULL NULL NULL NULL 2019-01-1611:02:01

NULL

DCH_TRAINING

vAlbum Milliseconds

NULL NULL NULL NULL 2019-01-1611:02:01

NULL

DCH_TRAINING

vAlbum minutes NULL NULL NULL NULL 2019-01-1611:02:01

NULL

DCH_TRAINING

vAlbum SizeBytes NULL NULL NULL NULL 2019-01-1611:02:01

NULL

18

Page 23: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

DatabaseName

TableName

ColumnName

ColumnFormat

ColumnType

ColumnLength

Nullable createdDate

lastAccessed

DCH_TRAINING

vAlbum mbSize NULL NULL NULL NULL 2019-01-1611:02:01

NULL

DCH_TRAINING

vAlbum GenreId NULL NULL NULL NULL 2019-01-1611:02:01

NULL

DCH_TRAINING

vAlbum genreName

NULL NULL NULL NULL 2019-01-1611:02:01

NULL

DCH_TRAINING

vAlbum MediaTypeId

NULL NULL NULL NULL 2019-01-1611:02:01

NULL

DCH_TRAINING

vAlbum mediaTypeName

NULL NULL NULL NULL 2019-01-1611:02:01

NULL

Back to [top].

19

Page 24: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.3. tableCountsSQL Example

/*=== tableCounts - Count rows in all Chinook tables

==== Topics

* Aggregates (Count, Sum, Min, Max, Avg, etc)* Column Alias, rename a column* Order by, also known as sorting* Union, multiple select queries stacked*/

Select  'Album ' as tableName ①  , count(*) as "Rows" from DCH_Training.Album ②

UNIONSelect  'Artist' as tableName  , count(*) from DCH_Training.Artist

UNIONSelect  'Customer' as tableName  , count(*) from DCH_Training.Customer

UNIONSelect  'Employee' as tableName  , count(*) from DCH_Training.Employee

UNIONSelect  'Genre' as tableName  , count(*) from DCH_Training.Genre

UNIONSelect  'Invoice' as tableName  , count(*) from DCH_Training.Invoice

UNIONSelect  'Invoice Line' as tableName  , count(*) from DCH_Training.InvoiceLine

UNIONSelect

20

Page 25: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

  'Media Type' as tableName  , count(*) from DCH_Training.MediaType

UNIONSelect  'Playlist' as tableName  , count(*) from DCH_Training.Playlist

UNIONSelect  'Playlist Track' as tableName  , count(*) from DCH_Training.PlaylistTrack

UNIONSelect  'Track' as tableName  , count(*) from DCH_Training.Track

Order by 2 desc ③

① First query in union determine sizes and names of columns.

② count(*) is an aggregate function

③ Order by can be by the ordinal number of the column (Column 1 is tableName, Column 2 isRows)

SQL download link click here

Table 2. Results

tableName Rows

Playlist Track 8715

Track 3503

Invoice Line 2240

Invoice 412

Album 347

Artist 275

Customer 59

Genre 25

Playlist 18

Employee 8

Media Type 5

Your table counts may vary from this example as the DCH_Training database isupdated to help with lesson content.

21

Page 26: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Figure 5. Commenting your SQL

Back to [top].

22

Page 27: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.4. dbObjectsSQL Example

/*=== dbObjects - Get a list of all the objects in a specific database

==== Topics

* Teradata Specific syntax

==== Special Note

* Change the database name from `chinook` to the database you are interested in*/

help database dch_training

SQL download link click here

Table 3. Results

Table/View/Macroname

Kind Comment

Protection

CreatorName

CommitOption

TransactionLog

Table/View/MacroDictionaryName

Table/View/Macro SQLName

Table/View/MacroNameUEscape

CreatorDictionaryName

CreatorSQLName

CreatorNameUEscape

Album

T NULL N WINDUSER

N Y Album

Album

WINDUSER

WINDUSER

Artist T NULL N WINDUSER

N Y Artist Artist WINDUSER

WINDUSER

Customer

T NULL N WINDUSER

N Y Customer

Customer

WINDUSER

WINDUSER

Employee

T NULL N WINDUSER

N Y Employee

Employee

WINDUSER

WINDUSER

Genre T NULL N WINDUSER

N Y Genre Genre WINDUSER

WINDUSER

Invoice

T NULL N WINDUSER

N Y Invoice

Invoice

WINDUSER

WINDUSER

InvoiceLine

T NULL N WINDUSER

N Y InvoiceLine

InvoiceLine

WINDUSER

WINDUSER

mComedyList

M NULL F DBC N Y mComedyList

mComedyList

DBC DBC

23

Page 28: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Table/View/Macroname

Kind Comment

Protection

CreatorName

CommitOption

TransactionLog

Table/View/MacroDictionaryName

Table/View/Macro SQLName

Table/View/MacroNameUEscape

CreatorDictionaryName

CreatorSQLName

CreatorNameUEscape

MediaType

T NULL N WINDUSER

N Y MediaType

MediaType

WINDUSER

WINDUSER

Playlist

T NULL N WINDUSER

N Y Playlist

Playlist

WINDUSER

WINDUSER

PlaylistTrack

T NULL N WINDUSER

N Y PlaylistTrack

PlaylistTrack

WINDUSER

WINDUSER

Track T NULL N WINDUSER

N Y Track Track WINDUSER

WINDUSER

vComedyTrack

V NULL F DBC N Y vComedyTrack

vComedyTrack

DBC DBC

Your database objects may vary from this example as the DCH_Training databaseis updated to help with lesson content.

Back to [top].

24

Page 29: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.5. tableColumnsSQL Example

/*=== tableColumns - Get a list of all the columns for a specific table or object in aknown database

==== Topics

* Teradata Specific syntax

==== Special Note

* Change the database name from `chinook` to the database you are interested in*/

help table dch_training.invoice

SQL Download link click here

Table 4. Results

ColumnName

Type

Comment

Nullable

Format

Title

MaxLength

DecimalTotalDigits

DecimalFractionalDigits

RangeLow

RangeHigh

UpperCase

Table/View?

Defaultvalue

CharType

IdColType

UDTName

Temporal

ColumnDictionaryName

ColumnSQLName

ColumnNameUEscape

DictionaryTitle

SQLTitle

TitleUEscape

UDTDictionaryName

UDTSQLName

UDTNameUEscape

InvoiceId

I NULL

N -(10)9

NULL

4 NULL

NULL

NULL

NULL

N T NULL

NULL

GD

NULL

N InvoiceId

InvoiceId

NULL

NULL

NULL

NULL

NULL

NULL

CustomerId

I NULL

N -(10)9

NULL

4 NULL

NULL

NULL

NULL

N T NULL

NULL

NULL

NULL

N CustomerId

CustomerId

NULL

NULL

NULL

NULL

NULL

NULL

25

Page 30: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

ColumnName

Type

Comment

Nullable

Format

Title

MaxLength

DecimalTotalDigits

DecimalFractionalDigits

RangeLow

RangeHigh

UpperCase

Table/View?

Defaultvalue

CharType

IdColType

UDTName

Temporal

ColumnDictionaryName

ColumnSQLName

ColumnNameUEscape

DictionaryTitle

SQLTitle

TitleUEscape

UDTDictionaryName

UDTSQLName

UDTNameUEscape

InvoiceDate

DA

NULL

N yyyy-mm-dd

NULL

4 NULL

NULL

NULL

NULL

N T NULL

NULL

NULL

NULL

N InvoiceDate

InvoiceDate

NULL

NULL

NULL

NULL

NULL

NULL

BillingAddress

CV

NULL

Y X(70)

NULL

70 NULL

NULL

NULL

NULL

N T NULL

1 NULL

NULL

N BillingAddress

BillingAddress

NULL

NULL

NULL

NULL

NULL

NULL

BillingCity

CV

NULL

Y X(40)

NULL

40 NULL

NULL

NULL

NULL

N T NULL

1 NULL

NULL

N BillingCity

BillingCity

NULL

NULL

NULL

NULL

NULL

NULL

BillingState

CV

NULL

Y X(40)

NULL

40 NULL

NULL

NULL

NULL

N T NULL

1 NULL

NULL

N BillingState

BillingState

NULL

NULL

NULL

NULL

NULL

NULL

BillingCountry

CV

NULL

Y X(40)

NULL

40 NULL

NULL

NULL

NULL

N T NULL

1 NULL

NULL

N BillingCountry

BillingCountry

NULL

NULL

NULL

NULL

NULL

NULL

BillingPostalCode

CV

NULL

Y X(10)

NULL

10 NULL

NULL

NULL

NULL

N T NULL

1 NULL

NULL

N BillingPostalCode

BillingPostalCode

NULL

NULL

NULL

NULL

NULL

NULL

26

Page 31: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

ColumnName

Type

Comment

Nullable

Format

Title

MaxLength

DecimalTotalDigits

DecimalFractionalDigits

RangeLow

RangeHigh

UpperCase

Table/View?

Defaultvalue

CharType

IdColType

UDTName

Temporal

ColumnDictionaryName

ColumnSQLName

ColumnNameUEscape

DictionaryTitle

SQLTitle

TitleUEscape

UDTDictionaryName

UDTSQLName

UDTNameUEscape

Total

D NULL

N ---------.99

NULL

8 10 2 NULL

NULL

N T NULL

NULL

NULL

NULL

N Total

Total

NULL

NULL

NULL

NULL

NULL

NULL

ColumnType defined the data type of a column. Reference: [ColumnType]

Since the results from this query are not very readable this snapshot below will show how theresults look.

Figure 6. tableColumns

Back to [top].

27

Page 32: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.6. findColumnSQL Example

/*=== findColumn - Find out what objects (Table, View) where a specific named columnexist

==== Topics

* Where, results filter or restriction* Teradata Specific syntax

==== Special Note

* ColumnTypes Reference:http://developer.teradata.com/doc/connectivity/tdnetdp/14.00/webhelp/DataTypeMappings.html* Replace `CustomerID` with the column you are interested in* The list of columns in the `Select` are the ones that are the most important,there are many other columns available. Use a single column name `*` to see them all.

*/

select  ColumnName  ,DatabaseName  ,TableName  ,ColumnFormat  ,ColumnType  ,ColumnLengthfrom dbc.columnsXwhere ColumnName = 'CustomerID'

SQL Download link click here

Table 5. Results

ColumnName DatabaseName

TableName ColumnFormat

ColumnType ColumnLength

CustomerId Chinook Invoice -(10)9 I 4

CustomerId Chinook Customer -(10)9 I 4

The ColumnType identifies the data type of the column. Reference: Column Type

Back to [top].

28

Page 33: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.7. NumbersNumbers can have different data types. The data type determines how much data you can put intothat column.

Table 6. Number Data types simplified

Data Types Length(Bytes)

Range of values

BYTEINT 1 -128 to +127

SMALLINT 2 -32768 to +32767

INTEGER 4 -2,147,483,648 to +2147,483,647

BIGINT 8 -9,233,372,036,854,775,80 8 to +9,233,372,036,854,775,8 07

DECIMAL 1-16 NUMERIC is in the ANSI SQL:2011 standard. DECIMAL is aTeradata synonym for NUMERIC.

NUMERIC 1-16 NUMERIC is in the ANSI SQL:2011 standard. DECIMAL is aTeradata synonym for NUMERIC.

FLOAT 8 IEEE format

SQL Small Whole Numbers Example

/*

=== Numbers

Some of the examples here do *NOT* show the actual smallest or largest value.They show a practical example of whay might be used in queries.

"Less is more" the smaller number of bytes used the more speed you can get out of aquery.

*/-- Smaller whole numbersSelect  '-- Smaller whole numbers:' as Description  ,-128 (ByteInt) as smallest_ByteInt -- Takes 1 byte of space  ,127 (ByteInt) as largest_ByteInt -- Takes 1 byte of space  ,-32768 (SmallInt) as smallest_SmallInt -- Takes 2 bytes of space  ,smallest_SmallInt (format '-99,999') (varchar(10)) as ssi  ,32767 (SmallInt) as largest_SmallInt -- Takes 2 bytes of space  ,largest_SmallInt (format '99,999') (varchar(10)) as lsi;

SQL Download link click here

Table 7. Small Whole Numbers Results

29

Page 34: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Description smallest_ByteInt

largest_ByteInt

smallest_SmallInt

ssi largest_SmallInt

lsi

 — Smallerwholenumbers:

-128 127 -32768 -32,768 32767 32,767

Back to [top].

SQL Large Whole Numbers Example

/*

=== Numbers

Some of the examples here do *NOT* show the actual smallest or largest value.They show a practical example of whay might be used in queries.

"Less is more" the smaller number of bytes used the more speed you can get out of aquery.

*/-- Larger whole numbersSelect  '--Larger whole numbers: ' as Description  ,-2147483648 (integer) as smallest_Integer -- Takes 4 bytes of space  ,smallest_Integer (format '-9,999,999,999') (varchar(15)) as si  ,2147483647 (integer) as largest_Integer -- Takes 4 bytes of space  ,largest_Integer (format '9,999,999,999') (varchar(15)) as li  ,-9223372036854775808 (BigInt) as smallestBigInt -- Takes 8 bytes of space  ,smallestBigInt (format '-9,999,999,999,999,999,999') (varchar(25)) as sbi  ,9223372036854775807 (BigInt) as largestBigInt -- Takes 8 bytes of space  ,largestBigInt (format '9,999,999,999,999,999,999') (varchar(25)) as lbi;

SQL Download link click here

Table 8. Large Whole Numbers Results

Description

smallest_Integer

si largest_Integer

li smallestBigInt

sbi largestBigInt

lbi

--Largerwholenumbers:

-2147483648

-2,147,483,648

2147483647

2,147,483,647

-9223372036854775808

-9,223,372,036,854,775,80

9223372036854775807

9,223,372,036,854,775,807

Back to [top].

30

Page 35: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

SQL Decimal Numbers Example

/*

=== Numbers

Some of the examples here do *NOT* show the actual smallest or largest value.They show a practical example of whay might be used in queries.

"Less is more" the smaller number of bytes used the more speed you can get out of aquery.

*/-- Decimal Numbers (These are practical examples, you can go crazy with decimalfractions)-- If using for currency then the decimal fraction is always 2 ie decimal(38,2)-- NUMERIC is in the ANSI SQL:2011 standard. DECIMAL is a Teradata synonym forNUMERIC.Select  '--Decimal Numbers: ' as Description  -- 38 digits total with 8 of them being decimal fractions,  -- takes 1-16 bytes of space  ,-678901234567890.12345678 (decimal(38,8)) as smallest_Decimal  ,smallest_Decimal (format '-999,999,999,999,999.9999999') (varchar(60)) as sd  -- 38 digits total with 8 of them being decimal fractions,  -- takes 1-16 bytes of space  ,678901234567890.12345678 (decimal(38,8)) as largest_Decimal  ,largest_Decimal (format '-999,999,999,999,999.9999999') (varchar(60)) as ld  -- Represents USA current debt at 02/15/2019 1:00PM  ,22020113259723.10 (decimal(18,2)) as currentDebt  ,currentDebt (format '$zz,999,999,999,999.99') (varchar(25)) as debt;

SQL Download link click here

Table 9. Decimal Numbers Results

Description smallest_Decimal

sd largest_Decimal

ld currentDebt debt

--DecimalNumbers:

-678901234567890.12345678

-678,901,234,567,890.1234568

678901234567890.12345678

678,901,234,567,890.1234568

22020113259723.10

$22,020,113,259,723.10

Back to [top].

31

Page 36: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

SQL Numeric Numbers Example

/*-- Numeric numbers (These are practical examples,-- if you are a scientist you may want more decimal fractions)-- How big of a number and decimal fractions do you really need???-- NUMERIC is in the ANSI SQL:2011 standard. DECIMAL is a Teradata synonym forNUMERIC.Select  '--Numeric Numbers: ' as Description  ,-678901234567890.12345678 (numeric(38,8)) as smallest_Numeric  ,smallest_Numeric (format '-999,999,999,999,999.9999999') (varchar(60)) as sn  ,smallest_Numeric (format '-99.99E99') (varchar(15)) as sme1 ①  ,smallest_Numeric (format '-9,999.99E99') (varchar(15)) as sme2; ①

① The Scientific format displays a number in exponential notation, replacing part of the numberwith E+n, in which E (exponent) multiplies the preceding number by 10 to the nth power.

SQL Download link click here

Table 10. Numeric Numbers Results

Description smallest_Numeric

sn sme1 sme2

--NumericNumbers:

-678901234567890.12345678

-678,901,234,567,890.1234568

-67.89E13 -6,789.01E11

Back to [top].

32

Page 37: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.8. Date FormatsIn this example the format of the date field needs to be MM/YYYY but, we want to keep the column adate column.

SQL Example

/*

=== Date examples

How to use a column with a `date` data type and reformat it.`

==== Topics

* Date functions* Teradata Specific syntax

*/

Select  CURRENT_DATE (FORMAT 'MM/YYYY') (CHAR(07)); -① ②

① Format applies your formatting to the date

② Char translates the formatted date in a text field

SQL Download link click here

Table 11. Results

Current Date

03/2019

Back to [top].

33

Page 38: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.9. System CalendarThe SYS_CALENDAR.CALENDAR system view helps to extend the properties of a DATE data typecolumn by means of a join.

The CALENDAR system view is defined for the years 1900 - 2100.

Think of the System Calendar as a table with ALL dates in it, between 1900-2100, with all sorts ofinformation about that date including monthly and quarterly.

A practical use of the System Calendar is to generate a list of dates that meet some criteria forjoining into a query for date restrictions or aggregation.

In this example all the column for a single date in the System Calendar are shown.

SQL Example - All Columns

/*

=== System Calendar

The SYS_CALENDAR.CALENDAR system view helps to extend the propertiesof a DATE data type column by means of a join.The CALENDAR system view is defined for the years 1900 - 2100.

==== Topics

* Between function* Calculated columns* Case statement* Coalesce function* Column Alias, rename a column* Comments, information or debugging* Concatation* Date functions* Derived Table (Sub-Query)* Formatting* Teradata Specific syntax* Where, results filter or restriction

*/-- Show all columns for a single dateSelect  *from SYS_CALENDAR.Calendarwhere  calendar_date = '1953-07-07'; ①

① Teradata default date format 'yyyy-mm-dd'

SQL Download link click here

34

Page 39: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Table 12. Results - All Columns

calendar_date

day_of_week

day_of_month

day_of_year

day_of_calendar

weekday_of_month

week_of_month

week_of_year

week_of_calendar

month_of_quarter

month_of_year

month_of_calendar

quarter_of_year

quarter_of_calendar

year_of_calendar

1953-07-07

3 7 188 19546

1 1 27 2792 1 7 643 3 215 1953

Back to [top].

In this example the most typical columns of the System Calendar are returned.

35

Page 40: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

SQL Example - Typical Columns

/*

=== System Calendar

The SYS_CALENDAR.CALENDAR system view helps to extend the propertiesof a DATE data type column by means of a join.The CALENDAR system view is defined for the years 1900 - 2100.

==== Topics

* Between function* Calculated columns* Case statement* Coalesce function* Column Alias, rename a column* Comments, information or debugging* Concatation* Date functions* Derived Table (Sub-Query)* Formatting* Teradata Specific syntax* Where, results filter or restriction

*/-- Show typical columns for a dateSelect  calendar_date  ,'System Calendar covers 1900-2100' as SysCalDescription ②  ,year_of_Calendar as yearOnly ②  ,month_of_year as monthOnly ②  ,day_of_month as dayOnly ②  ,day_of_week as dayNumberInWeek ②  ,case day_of_week ③  when 1 then 'Sunday'  when 2 then 'Monday'  when 3 then 'Tuesday'  when 4 then 'Wendsday'  when 5 then 'Thursday'  when 6 then 'Friday'  when 7 then 'Saturday'  end as dayWeek ②from SYS_CALENDAR.Calendarwhere  calendar_date = '1953-07-07'; ①

① Teradata default date format 'yyyy-mm-dd'

② Column alias

③ Case statement

36

Page 41: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

SQL Download link click here

Table 13. Results - Typical Columns

calendar_date

SysCalDescription

yearOnly monthOnly dayOnly dayNumberInWeek

dayWeek

1953-07-07 SystemCalendarcovers 1900-2100

1953 7 7 3 Tuesday

Back to [top].

In this example the columns related to weekly function for a date are returned.

SQL Example - Weekly Columns

/*

=== System Calendar

The SYS_CALENDAR.CALENDAR system view helps to extend the propertiesof a DATE data type column by means of a join.The CALENDAR system view is defined for the years 1900 - 2100.

==== Topics

* Between function* Calculated columns* Case statement* Coalesce function* Column Alias, rename a column* Comments, information or debugging* Concatation* Date functions* Derived Table (Sub-Query)* Formatting* Teradata Specific syntax* Where, results filter or restriction

*/-- Show weekly related columns for a dateSelect  calendar_date  ,'System Calendar covers 1900-2100' as SysCalDescription ②  ,week_of_month as weekInMonth ②  ,week_of_year as weekInYear1953 ②  ,week_of_calendar as weekInSysCalendar ②from SYS_CALENDAR.Calendarwhere  calendar_date = '1953-07-07'; ①

37

Page 42: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

① Teradata default date format 'yyyy-mm-dd'

② Column alias

SQL Download link click here

Table 14. Results - Weekly Columns

calendar_date SysCalDescription

weekInMonth weekInYear1953 weekInSysCalendar

1953-07-07 System Calendarcovers 1900-2100

1 27 2792

Back to [top].

In this example the columns related to monthly function for a date are returned.

38

Page 43: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

SQL Example - Monthly Columns

/*

=== System Calendar

The SYS_CALENDAR.CALENDAR system view helps to extend the propertiesof a DATE data type column by means of a join.The CALENDAR system view is defined for the years 1900 - 2100.

==== Topics

* Between function* Calculated columns* Case statement* Coalesce function* Column Alias, rename a column* Comments, information or debugging* Concatation* Date functions* Derived Table (Sub-Query)* Formatting* Teradata Specific syntax* Where, results filter or restriction

*/-- Show Monthly related columns for a dateSelect  calendar_date  ,'System Calendar covers 1900-2100' as SysCalDescription②  ,month_of_quarter as monthInQuarter1953 ②  ,month_of_year as monthInYear1953 ②  ,month_of_calendar as monthInSysCalendar ②from SYS_CALENDAR.Calendarwhere  calendar_date = '1953-07-07'; ①

① Teradata default date format 'yyyy-mm-dd'

② Column alias

SQL Download link click here

Table 15. Results - Monthly Columns

calendar_date SysCalDescription

monthInQuarter1953

monthInYear1953 monthInSysCalendar

1953-07-07 System Calendarcovers 1900-2100

1 7 643

Back to [top].

39

Page 44: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

In this example the columns related to quarterly function for a date are returned.

SQL Example - Quarterly Columns

/*

=== System Calendar

The SYS_CALENDAR.CALENDAR system view helps to extend the propertiesof a DATE data type column by means of a join.The CALENDAR system view is defined for the years 1900 - 2100.

==== Topics

* Between function* Calculated columns* Case statement* Coalesce function* Column Alias, rename a column* Comments, information or debugging* Concatation* Date functions* Derived Table (Sub-Query)* Formatting* Teradata Specific syntax* Where, results filter or restriction

*/-- Show Quartley related columns for a dateSelect  calendar_date  ,'System Calendar covers 1900-2100' as SysCalDescription ②  ,quarter_of_year as quarterInYear1953 ②  ,quarter_of_calendar as quarterInSysCalendar ②from SYS_CALENDAR.Calendarwhere  calendar_date = '1953-07-07'; ①

① Teradata default date format 'yyyy-mm-dd'

② Column alias

SQL Download link click here

Table 16. Results - Quarterly Columns

calendar_date SysCalDescription quarterInYear1953 quarterInSysCalendar

1953-07-07 System Calendar covers1900-2100

3 215

Back to [top].

40

Page 45: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

In this example a practical example where all the months between 2014 and 2018 are needed,formatted as YYYY/MM.

This result will be used in another example to fill in missing months for a Sales Previous year query.

SQL Example - Practical Example

/*

=== System Calendar

The SYS_CALENDAR.CALENDAR system view helps to extend the propertiesof a DATE data type column by means of a join.The CALENDAR system view is defined for the years 1900 - 2100.

==== Topics

* Between function* Calculated columns* Case statement* Coalesce function* Column Alias, rename a column* Comments, information or debugging* Concatation* Date functions* Derived Table (Sub-Query)* Formatting* Teradata Specific syntax* Where, results filter or restriction

*/-- Practical example Get all months between 2014-2018 in YYYY/MM formatSelect DISTINCT ④  YearMonth  ,1 as commonThing ⑤from( ③  Select  --*  calendar_Date  ,year_of_Calendar (format '9999') (char(4)) as yearIS ②  ,Month_of_Year (format '99') (char(2)) as monthIS ②  ,yearIS || '/' || MonthIS as YearMonth ② ⑦

  from SYS_CALENDAR.Calendar  where  calendar_date between '2014-01-01' and '2018-12-31' ①) as SC; ⑥

① Teradata default date format 'yyyy-mm-dd'

41

Page 46: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

② Column alias

③ Beginning of a Derived Table (Sub-Query)

④ Distinct returns just one row for each month of days

⑤ commonThing is used to help in doing FULL JOIN to another table, shown in future question

⑥ Table Alias for Derived Table (Sub-Query)

⑦ This is where the YYYY/MM version of the date is built and it is a character field

SQL Download link click here

Table 17. Results - Practical Columns

YearMonth commonThing

2014/01 1

2014/02 1

2014/03 1

2014/04 1

2014/05 1

2014/06 1

2014/07 1

2014/08 1

2014/09 1

2014/10 1

2014/11 1

2014/12 1

2015/01 1

2016/11 1

2016/12 1

2017/01 1

2017/02 1

2017/03 1

2017/04 1

2017/05 1

2017/06 1

2017/07 1

2017/08 1

2017/09 1

2017/10 1

2017/11 1

2017/12 1

42

Page 47: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

YearMonth commonThing

2018/01 1

2018/02 1

2018/03 1

2018/04 1

2018/05 1

2018/06 1

2018/07 1

2018/08 1

2018/09 1

2018/10 1

2018/11 1

2018/12 1

Not all of the results are displayed, there are 60 rows returned.

Back to [top].

43

Page 48: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.10. joinQuery Part AObjective: Get a list of tracks from the Artist Aerosmith where the Composer is Joe Perry.

Approach: Begin with a simple query to get one element of the objective. In this query we want toget the ArtistID for Aerosmith

SQL Example

/*=== joinQuery - Multiple Table join with result restriction

==== Topics

* Column Alias, rename a column* OLAP function* Where, results filter or restriction* Table alias, standardize and simplify table/view names*/

Select  AR.ArtistID  ,AR.name as artistName ①From DCH_Training.Artist AR ②where artistName = 'Aerosmith'

① Column alias, notice name is artistName

② Table alias, use alias on every instance of columns from that table

SQL Download link click here

Table 18. Results

ArtistId artistName

3 Aerosmith

Back to [top].

44

Page 49: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.11. joinQuery Part BObjective: Get a list of tracks from the Artist Aerosmith where the Composer is Joe Perry.

Approach: Add on to the initial query to get a list of all the Albums for the Artist Aerosmith

SQL Example

/*=== joinQuery - Multiple Table join with result restriction

Part B - Add the second table for the Join

==== Topics

* Column Alias, rename a column* Derived Table (Sub-Query)* Join objects (Table, View, Derived Table) together* Where, results filter or restriction* Table alias, standardize and simplify table/view names*/

Select  AR.ArtistID  ,AL.AlbumID  ,AR.name as artistName ①  ,AL.AlbumTitleFrom DCH_Training.Artist AR ②

inner Join DCH_Training.Album AL ②on AR.ArtistID = AL.ArtistID ③

where artistName = 'Aerosmith'

① Column alias, notice name is artistName

② Table alias, use alias on every instance of columns from that table

③ The common column used to join the two tables together

SQL Download link click here

Table 19. Results

ArtistId AlbumId artistName AlbumTitle

3 5 Aerosmith Big Ones

Back to [top].

45

Page 50: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.12. joinQuery Part CObjective: Get a list of tracks from the Artist Aerosmith where the Composer is Joe Perry.

Approach: Complete the request by joining the Title table and a row restriction using the like withthe wildcard % character.

SQL Example

/*=== joinQuery - Multiple Table join with result restriction

Part C - Add the third table and composer restriction

==== Topics

* Column Alias, rename a column* Join objects (Table, View, Derived Table) together* Like %Search% similar to `contains`* Order by, also known as sorting* Where, results filter or restriction*/

Select  AR.ArtistID  ,AL.AlbumID  ,T.TrackID  ,AR.name as artistName ①  ,AL.AlbumTitle  ,T.Name as trackName ①  ,T.ComposerFrom DCH_Training.Artist AR ②

inner Join DCH_Training.Album AL ②on AR.ArtistID = AL.ArtistID ③

inner join DCH_Training.Track Ton AL.AlbumID = T.AlbumID

where AR.Name = 'Aerosmith'  and T.Composer like '%Joe Perry%' ④

order by AL.AlbumTitle  ,trackName ⑤-- order by 5,6 ⑥

① Column alias, notice name is artistName

② Table alias, use alias on every instance of columns from that table

③ The common column used to join the two tables together

46

Page 51: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

④ The like with wildcard character % used on Composer column

⑤ The order by has both actual column name AL.AlbumTitle and an alias column trackName

⑥ Shows alternative method of order by using ordinal column numbers

SQL Download link click here

Table 20. Results

ArtistId

AlbumId

TrackId

artistName AlbumTitle trackName Composer

3 5 31 Aerosmith Big Ones Blind Man Steven Tyler, Joe Perry,Taylor Rhodes

3 5 34 Aerosmith Big Ones Crazy Steven Tyler, Joe Perry,Desmond Child

3 5 29 Aerosmith Big Ones Cryin' Steven Tyler, Joe Perry,Taylor Rhodes

3 5 27 Aerosmith Big Ones Dude (LooksLike A Lady)

Steven Tyler, Joe Perry,Desmond Child

3 5 35 Aerosmith Big Ones Eat The Rich Steven Tyler, Joe Perry,Jim Vallance

3 5 37 Aerosmith Big Ones Livin' On TheEdge

Steven Tyler, Joe Perry,Mark Hudson

3 5 24 Aerosmith Big Ones Love In AnElevator

Steven Tyler, Joe Perry

3 5 25 Aerosmith Big Ones Rag Doll Steven Tyler, Joe Perry,Jim Vallance, HollyKnight

3 5 23 Aerosmith Big Ones Walk On Water Steven Tyler, Joe Perry,Jack Blades, TommyShaw

3 5 26 Aerosmith Big Ones What It Takes Steven Tyler, Joe Perry,Desmond Child

Back to [top].

47

Page 52: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.13. Join TypesThe relationships between database objects are defined using join statements.

Two database objects are joined using one or more common columns between them.

3.13.1. Inner Join

An Inner Join can be used when you know there is at least one row in each of the two tables beingjoined. The business rules or the data model can help define when this relationship occurs.

An Inner Join can be used to restrict/filter a large amount of rows from one table by a limitednumber of rows in the second table.

An Inner Join can be used to replace a where clause with a list of values or a sub-query. The InnerJoin can be much more efficient than a where clause when there are a large number ofrestriction/filter rows.

3.13.2. Outer Join

• An Outer Join can be used when you know that there may no or is not one row in each of thetables being joined.

• An Outer Join returns ALL of the rows from one table and any matching rows from the secondtable.

• All Outer Joins has a direction, left outer join or right outer join. Think of it as one object on theleft and the second object on the right.

• The first Select object in the query is the Left object by default.

• The outer joined object is the right object.

• The direction of the outer join determines which object is the All object

• A Right Outer Join returns ALL the rows from the object on the RIGHT and any matching rowsfrom the left object.

• A Left Outer Join returns ALL the rows from the object on the LEFT and any matching rowsfrom the right object.

• The on clause of the join does NOT indicate the direction of the join. on G.GenreID = T.GenreIDand on T.GenreID = G.GenreID

48

Page 53: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Figure 7. Right Outer Join

The same query above could be written reversing the order in which the objects are referenced toshow a Left Outer join.

49

Page 54: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Figure 8. Left Outer Join

The following query returns a list of all Genres, there should be 28 Genres.

50

Page 55: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Genre List

/*=== joinTypes - Inner Join and Outer Join

==== Topics

* Aggregates (Count, Sum, Min, Max, Avg, etc)* Between function* Column Alias, rename a column* Comments, information or debugging* Group by, required for non-aggregate columns* Join objects (Table, View, Derived Table) together* Order by, also known as sorting* Where, results filter or restriction* Table alias, standardize and simplify table/view names*/

-- List of *all* Genre, there are 28 genresselect  G.GenreID  ,G.Name as genreName ①from DCH_Training.Genre Gorder by genreName;-- Order by 2 ②

① Column alias

② Alternative method to order by using Ordinal position not recommended

SQL Download link click here

Table 21. Results for Genre List

GenreId genreName

23 Alternative

4 Alternative & Punk

6 Blues

11 Bossa Nova

24 Classical

32 Club

22 Comedy

21 Drama

30 Dub Step

12 Easy Listening

15 Electronica/Dance

13 Heavy Metal

51

Page 56: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

GenreId genreName

17 Hip Hop/Rap

2 Jazz

7 Latin

3 Metal

25 Opera

9 Pop

14 R&B/Soul

8 Reggae

1 Rock

5 Rock And Roll

20 Sci Fi & Fantasy

18 Science Fiction

10 Soundtrack

31 Trance

19 TV Shows

16 World

Back to [top].

52

Page 57: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

The following query shows the results when a Inner Join is used.

There are only 25 Genres in the result as 3 genres have no tracks related to them.

Inner Join Example

/*=== joinTypes - Inner Join and Outer Join

==== Topics

* Aggregates (Count, Sum, Min, Max, Avg, etc)* Between function* Column Alias, rename a column* Comments, information or debugging* Group by, required for non-aggregate columns* Join objects (Table, View, Derived Table) together* Order by, also known as sorting* Where, results filter or restriction* Table alias, standardize and simplify table/view names*/-- Track Count by Genre (Inner Join), this returns 25 genres-- because 3 genres have no tracksSelect  G.GenreID  ,G.Name as genreName ①  ,count(T.TrackID) as numberTracks ②from DCH_Training.Track T

inner Join DCH_Training.Genre G ③on G.GenreID = T.GenreID

Group by  G.GenreID  ,genreName ④order by  genreName; ④

① Column Alias

② Aggregate column with alias

③ Join (Inner)

④ Column alias in group by and order by

SQL Download link click here

Table 22. Results for Inner Join

GenreId genreName numberTracks

23 Alternative 40

53

Page 58: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

GenreId genreName numberTracks

4 Alternative & Punk 332

6 Blues 81

11 Bossa Nova 15

24 Classical 74

22 Comedy 17

21 Drama 64

12 Easy Listening 24

15 Electronica/Dance 30

13 Heavy Metal 28

17 Hip Hop/Rap 35

2 Jazz 130

7 Latin 579

3 Metal 374

25 Opera 1

9 Pop 48

14 R&B/Soul 61

8 Reggae 58

1 Rock 1297

5 Rock And Roll 12

20 Sci Fi & Fantasy 26

18 Science Fiction 13

10 Soundtrack 43

19 TV Shows 93

16 World 28

The Genres Club, Dub Step, Trance are not in the results because the have no tracksrelated to them.

Back to [top].

54

Page 59: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

The following query shows the results when a Right Outer Join is used.

This query is different from the one below, note which table is selected first.

Right Outer Join Example

/*=== joinTypes - Inner Join and Outer Join

==== Topics

* Aggregates (Count, Sum, Min, Max, Avg, etc)* Between function* Column Alias, rename a column* Comments, information or debugging* Group by, required for non-aggregate columns* Join objects (Table, View, Derived Table) together* Order by, also known as sorting* Where, results filter or restriction* Table alias, standardize and simplify table/view names*/-- Track Count by Genre (Inner Join) Right-- This returns *ALL* 28 genres because the table on the right is the Genre tableSelect  G.GenreID  ,G.Name as genreName ①  ,count(T.TrackID) as numberTracks ②from DCH_Training.Track T

right outer Join DCH_Training.Genre G ③on G.GenreID = T.GenreID -- NOTE: G is first table, T is second table

Group by  G.GenreID  ,genreName ④order by  genreName; ④

① Column Alias

② Aggregate column with alias

③ Join (Right Outer)

④ Column alias in group by and order by

By default the first table in the select is the Left table, in this example it is the Tracktable. The joined table is the Right table and in this example it is the Genre table.Since this is a Right outer join all the rows from the Right table (Genre) arereturned with any matching rows from the Left table (Tracks).

55

Page 60: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

SQL Download link click here

Table 23. Results for Right Outer Join

GenreId genreName numberTracks

23 Alternative 40

4 Alternative & Punk 332

6 Blues 81

11 Bossa Nova 15

24 Classical 74

32 Club 0

22 Comedy 17

21 Drama 64

30 Dub Step 0

12 Easy Listening 24

15 Electronica/Dance 30

13 Heavy Metal 28

17 Hip Hop/Rap 35

2 Jazz 130

7 Latin 579

3 Metal 374

25 Opera 1

9 Pop 48

14 R&B/Soul 61

8 Reggae 58

1 Rock 1297

5 Rock And Roll 12

20 Sci Fi & Fantasy 26

18 Science Fiction 13

10 Soundtrack 43

31 Trance 0

19 TV Shows 93

16 World 28

All 28 Genres are returned in the results. The Genres Club, Dub Step, Trance areincluded and have a zero (0) trackCount.

Back to [top].

56

Page 61: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

The following query shows the results when a Left Outer Join is used.

This query is different from the one above, note which table is selected first.

Left Outer Join Example

/*=== joinTypes - Inner Join and Outer Join

==== Topics

* Aggregates (Count, Sum, Min, Max, Avg, etc)* Between function* Column Alias, rename a column* Comments, information or debugging* Group by, required for non-aggregate columns* Join objects (Table, View, Derived Table) together* Order by, also known as sorting* Where, results filter or restriction* Table alias, standardize and simplify table/view names*/-- Track Count by Genre (Inner Join) Left-- This returns *ALL* 28 genres because the table on the left is the Genre tableSelect  G.GenreID  ,G.Name as genreName ①  ,count(T.TrackID) as numberTracks ②from DCH_Training.Genre G

left outer Join DCH_Training.Track T ③on T.GenreID = G.GenreID

Group by  G.GenreID  ,genreName ④order by  genreName; ④

① Column Alias

② Aggregate column with alias

③ Join (Left Outer)

④ Column alias in group by and order by

By default the first table in the select is the Left table, in this example it is the Genretable. The joined table is the Right table and in this example it is the Track table.Since this is a Right outer join all the rows from the Left table (Genre) are returnedwith any matching rows from the Right table (Tracks).

57

Page 62: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

SQL Download link click here

Table 24. Results for Left Outer Join

GenreId genreName numberTracks

23 Alternative 40

4 Alternative & Punk 332

6 Blues 81

11 Bossa Nova 15

24 Classical 74

32 Club 0

22 Comedy 17

21 Drama 64

30 Dub Step 0

12 Easy Listening 24

15 Electronica/Dance 30

13 Heavy Metal 28

17 Hip Hop/Rap 35

2 Jazz 130

7 Latin 579

3 Metal 374

25 Opera 1

9 Pop 48

14 R&B/Soul 61

8 Reggae 58

1 Rock 1297

5 Rock And Roll 12

20 Sci Fi & Fantasy 26

18 Science Fiction 13

10 Soundtrack 43

31 Trance 0

19 TV Shows 93

16 World 28

All 28 Genres are returned in the results. The Genres Club, Dub Step, Trance areincluded and have a zero (0) trackCount.

Back to [top].

58

Page 63: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.14. Subquery FilterA subquery can be used to produce a list of ID’s that can be used in the main query as a filter togreatly reduce the processing time of the main query.

In this example we are using the subquery to get a list of TitleID’s for titles between 2 and 3 minuteslong.

This subquery will then be used as a filter against the fill tracks list to process an Artist name andthe longest (MAX) track for that artist.

This example could be solved with a simpler and quicker query but it is writtenthis way to show how a subquery list can be used as a filter in the main query.

First question would be how many tracks do we have in the Track table?

SQL Example (Count all tracks)

/*

=== SubQuery as Filter

NOTE: This query can be done quicker and simpler but, is done this wayto illustrate the filter method.

==== Topics

* Aggregates (Count, Sum, Min, Max, Avg, etc)* Between function* Calculated columns* Column Alias, rename a column* Comments, information or debugging* Derived Table (Sub-Query)* Group by, required for non-aggregate columns* Join objects (Table, View, Derived Table) together* Order by, also known as sorting* Where, results filter or restriction* Table alias, standardize and simplify table/view names*/-- Count of all tracks (3501)select  count(*) as totalTracks ① ②from DCH_Training.Track;go

① Column Alias

② Aggregate function

SQL Download link click here

59

Page 64: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Table 25. Results (Count all tracks)

totalTracks

3503

Back to [top].

The subquery needs to restrict the list of TrackID’s to those with a duration between 2-3 minutes.

The fields in this subquery can be used in the main query. The trackMinutes field will be used in themain query with the MAX aggregate function.

SQL Example (Limited Track List)

/*

=== SubQuery as Filter

NOTE: This query can be done quicker and simpler but, is done this wayto illustrate the filter method.

==== Topics

* Aggregates (Count, Sum, Min, Max, Avg, etc)* Between function* Calculated columns* Column Alias, rename a column* Comments, information or debugging* Derived Table (Sub-Query)* Group by, required for non-aggregate columns* Join objects (Table, View, Derived Table) together* Order by, also known as sorting* Where, results filter or restriction* Table alias, standardize and simplify table/view names*/-- List of tracks between 2-3 minutes (391)-- This will become the subquery in the main querySelect  T.TrackID  ,T.Name as trackName ①  ,(T.Milliseconds / 60000.00) as trackMinutes ① ②

from DCH_Training.Track T ③where trackMinutes between 2.00 and 3.00; ④go

① Column Alias

② Calculated column

③ Table alias

④ Where clause to limit track by 2-3 minute time range

60

Page 65: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

SQL Download link click here

Table 26. Results (Limtied Track List)

TrackId trackName trackMinutes

1420 It’s A Man’s Man’s Man’s World 2.80

3014 Desire 3.00

1419 I Got You (I Feel Good) 2.79

2669 Get Off Of My Cloud 2.93

1406 Futureal 2.93

1755 Arrepio 2.27

2732 Anyway, Anyhow, Anywhere 2.69

51 We Die Young 2.53

118 Slow Down 2.72

Some artists may have multiple tracks in the 2-3 minute range

There are 391 rows in the result, only the first 10 rows are displayed for clarity.

The titleName is used in the query just so we can verify the results.

Back to [top].

By performing an inner join on the subquery and the Tracks table, only the 391 matching tracks areused in the main query.

The MAX aggregate function can be used on the trackMinutes column.

The GROUP BY on the ArtistID will then show the maximum track time for each artist.

SQL Example (Main Query)

/*

=== SubQuery as Filter

NOTE: This query can be done quicker and simpler but, is done this wayto illustrate the filter method.

==== Topics

* Aggregates (Count, Sum, Min, Max, Avg, etc)* Between function* Calculated columns* Column Alias, rename a column* Comments, information or debugging* Derived Table (Sub-Query)* Group by, required for non-aggregate columns

61

Page 66: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

* Join objects (Table, View, Derived Table) together* Order by, also known as sorting* Where, results filter or restriction* Table alias, standardize and simplify table/view names*/-- Main query with subquery used to filterSelect  AR.ArtistID  ,AR.Name as artistNme ①  ,max(LTL.trackMinutes) as longestTrack ① ②from DCH_Training.Track T

INNER JOIN( -- This is subquery to restrict how many tracks to include ③  Select  T.TrackID  -- ,T.Name as trackName --Commented out, not needed for filtering ④  ,(T.Milliseconds / 60000.00) as trackMinutes ① ⑤

  from DCH_Training.Track T  where trackMinutes between 2.00 and 3.00) AS LTL -- Limited Tracks List ⑥ON LTL.TrackID = T.TrackID

INNER JOIN DCH_Training.Album AL -- To Get ArtistIDon AL.AlbumID = T.AlbumID

INNER JOIN DCH_Training.Artist AR -- To get Artist nameon AR.ArtistID = AL.ArtistID

Group By  AR.ArtistID -- Using ArtistID will assure proper grouping if a ArtistName isduplicated  ,AR.Name

Order by  longestTrack Desc

① Column Alias

② Aggregate function

③ This ( is the beginning of the subquery

④ The trackName column was commented out as it wasn’t needed in the main query

⑤ Calculated column

⑥ The end of the subquery where we have named the derived table LTL

SQL Download link click here

Table 27. Results (Main Query)

62

Page 67: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

ArtistId artistNme longestTrack

138 The Clash 3.00

69 Gene Krupa 3.00

70 Toquinho & Vinícius 3.00

150 U2 3.00

116 Passengers 3.00

155 Zeca Pagodinho 3.00

125 Raimundos 3.00

142 The Rolling Stones 3.00

24 Marcos Valle 2.99

There are 95 rows in the result, only the first 10 rows are displayed for clarity.

The titleName was used in the query just the results can be verified. This columnwill be dropped when this subquery is moved into the main query.

Back to [top].

63

Page 68: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.15. derivedTable 1 - Part AObjective: Get a list by Artist that includes number of albums, number of tracks, total artistminutes and average minutes per track.

Approach: Use a set of derived queries (aka sub-queries) to get the parts of the request andassemble the parts together in the main query.

This collection approach is typically used when the parts being collected come from varieddatabases or putting them in a single query makes it difficult to compose the query.

Figure 9. derivedTable Collection

Part A gets the number of albums by artist. It is the (Album Part) we need for the main query.

This request could be done using a single query. The derived tables are being usedhere, to show how they can be used to build parts of the results, that areassembled in a main query later.

Derived Tables are also know as sub-queries.

64

Page 69: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

SQL Example

/*=== derivedTable - Gets the list of artists and album counts

Part A - Gets the list of artists with album countthis will become one of the derived tables in the final query

==== Topics

* Aggregates (Count, Sum, Min, Max, Avg, etc)* Column Alias, rename a column* Group by, required for non-aggregate columns* Join objects (Table, View, Derived Table) together* Where, results filter or restriction* Table alias, standardize and simplify table/view names*/

select  AR.ArtistID  ,count(AL.AlbumID) as albumCount ① ②from DCH_Training.Album AL ③

INNER JOIN DCH_Training.Artist AR ③on AR.ArtistID = AL.ArtistID ④

Group by AR.ArtistID ⑤

① Column Alias

② Aggregate Count function

③ Table alias

④ Common column to join two tables

⑤ Any non-aggregate column must be included in group by

SQL Download link click here

Table 28. Results

ArtistId albumCount

223 1

265 1

19 2

122 1

80 2

244 1

202 1

65

Page 70: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

ArtistId albumCount

101 2

59 3

141 1

242 1

263 1

221 1

120 1

78 1

99 2

200 1

17 1

57 1

Only 20 rows of the result being shown. The result set has 204 rows, one for eachartist.

Back to [top].

66

Page 71: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.16. derived Table 1 -Part BObjective: Get a list by Artist that includes number of albums, number of tracks, total artistminutes and average minutes per track.

Approach: Use a set of derived queries (aka sub-queries) to get the parts of the request andassemble the parts together in the main query.

This collection approach is typically used when the parts being collected come from varieddatabases or putting them in a single query makes it difficult to compose the query.

Figure 10. derivedTable Collection

This part gets the number of tracks by artist and calculates the number of minutes total andaverage minutes per track from the milliseconds. It is the second part (Tracks Part) we need for themain query.

This request could be done using a single query. The derived tables are being usedhere, to show how they can be used to build parts of the results, that areassembled in a main query later.

Derived Tables are also know as sub-queries.

67

Page 72: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

SQL Example

/*=== derivedTable - The derived table collects data on one topic (Tracks)

Part B -Build the query that will become one of the derived tables

==== Topics

* Aggregates (Count, Sum, Min, Max, Avg, etc)* Cast for formatting* Column Alias, rename a column* Group by, required for non-aggregate columns* Join objects (Table, View, Derived Table) together* Table alias, standardize and simplify table/view names*/

Select  AL.ArtistID  ,count(T.TrackID) as trackCount  ,sum(T.Milliseconds) / 60000.00 as totalMinutes ①  ,avg(T.Milliseconds) / 60000.00 as avgMinutes ②from DCH_Training.Album AL

inner Join DCH_Training.Track Ton T.AlbumID = AL.AlbumID

group by AL.ArtistID

SQL Download link click here

Table 29. Results

ArtistId trackCount totalMinutes avgMinutes

72 15 54.25 3.61635666666667

179 12 57.47 4.78950277777778

96 12 50.27 4.18938194444444

227 1 2.95 2.94851666666667

144 20 76.33 3.81672

88 42 205.93 4.9029876984127

203 1 5.94 5.94043333333333

99 31 136.11 4.39078279569893

275 1 3.43 3.43341666666667

230 1 3.30 3.30106666666667

21 56 233.26 4.16541994047619

68

Page 73: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

ArtistId trackCount totalMinutes avgMinutes

139 30 128.59 4.28646833333333

238 1 6.52 6.51666666666667

246 1 2.22 2.21553333333333

56 14 48.92 3.49458571428571

83 14 47.37 3.38387619047619

91 20 70.19 3.50936833333333

155 19 67.75 3.56591228070175

115 12 60.82 5.06811111111111

① This calculated or derived field is the sum of time (Milliseconds) for all tracks for this artist.Dividing by 60,000.00 translates this into minutes.

② This calculated or derived field is the average of the time (Milliseconds) for all tracks for thisartist. Dividing by 60,000.00 translate this into minutes.

Notice that the division was done using a fractional number 60000.00 whichreturns the results with two decimal points of precision. If we had used an integernumber 60000 we would have gotten an whole number back and lost the twodecimal points of precision.

Only 20 rows of the result being shown. The result set has 204 rows, one for eachartist.

Back to [top].

69

Page 74: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.17. derivedTable 1 - Part CObjective: Get a list by Artist that includes number of albums, number of tracks, total artistminutes and average minutes per track.

Approach: Use a set of derived queries (aka sub-queries) to get the parts of the request andassemble the parts together in the main query.

This collection approach is typically used when the parts being collected come from varieddatabases or putting them in a single query makes it difficult to compose the query.

Figure 11. derivedTable Collection

This part assembles the album part (Part A) and tracks part (Part B) with artist information for themain or final query.

This request could be done using a single query. The derived tables are being usedhere, to show how they can be used to build parts of the results, that areassembled in a main query later.

Derived Tables are also know as sub-queries.

SQL Example

/*

70

Page 75: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

=== derivedTable - The derived table collects data on one topic (Albums)

Part C - Build the main query and include the two derived tables

==== Topics

* Aggregates (Count, Sum, Min, Max, Avg, etc)* Column Alias, rename a column* Derived Table (Sub-Query)* Group by, required for non-aggregate columns* Join objects (Table, View, Derived Table) together* Order by, also known as sorting* Where, results filter or restriction* Table alias, standardize and simplify table/view names

=== Assumptions

* Every Artist has at least one album*/

Select  AR.ArtistID  ,AR.Name as artistName  ,AC.albumCount ①  ,TC.totalMinutes  ,cast(TC.avgMinutes as decimal(5,2)) as averageMinutes ②from DCH_Training.Artist AR

inner join  ( ③  select  AR.ArtistID  ,count(AL.AlbumID) as albumCount ①  from DCH_Training.Album AL

  INNER JOIN DCH_Training.Artist AR  on AR.ArtistID = AL.ArtistID

  Group by AR.ArtistID  ) as AC ④on AC.ArtistID = AR.ArtistID

inner Join  ( ③  Select  AL.ArtistID  ,count(T.TrackID) as trackCount  ,sum(T.Milliseconds) / 60000.00 as totalMinutes ⑤  ,avg(T.Milliseconds) / 60000.00 as avgMinutes ⑥  from DCH_Training.Album AL

71

Page 76: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

  inner Join DCH_Training.Track T  on T.AlbumID = AL.AlbumID

  group by AL.ArtistID  ) as TC ④on TC.ArtistID = AR.ArtistID

Order by artistName

① A column from the derived table (sub-query) being used in the result

② CAST being used to reformat a decimal number to 5,2. Five digits total, two digits precision

③ The beginning of a derived table (sub-query) starts with a (

④ The end of the derived table (sub-query) is marked with a ) and a name for the derived table.The derived table name is used to qualify the use of the columns in the main query.

⑤ This calculated or derived field is the sum of time (Milliseconds) for all tracks for this artist.Dividing by 60,000.00 translates this into minutes.

⑥ This calculated or derived field is the average of the time (Milliseconds) for all tracks for thisartist. Dividing by 60,000.00 translate this into minutes.

SQL Download link click here

Table 30. Results

ArtistId artistName albumCount totalMinutes averageMinutes

230 Aaron Copland &London SymphonyOrchestra

1 3.30 3.30

202 Aaron Goldberg 1 4.45 4.45

1 AC/DC 2 80.89 4.49

214 Academy of St.Martin in theFields & Sir NevilleMarriner

1 7.75 3.88

215 Academy of St.Martin in theFields ChamberEnsemble & SirNeville Marriner

1 5.82 5.82

222 Academy of St.Martin in theFields, John Birch,Sir NevilleMarriner & SylviaMcNair

1 4.32 4.32

72

Page 77: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

ArtistId artistName albumCount totalMinutes averageMinutes

257 Academy of St.Martin in theFields, Sir NevilleMarriner &Thurston Dart

1 3.77 3.77

2 Accept 2 20.01 5.00

260 Adrian Leaper &Doreen de Feis

1 9.46 9.46

3 Aerosmith 1 73.53 4.90

197 Aisha Duo 1 9.23 4.62

4 Alanis Morissette 1 57.52 4.42

206 Alberto Turco &Nova ScholaGregoriana

1 4.09 4.09

5 Alice In Chains 1 54.16 4.51

252 Amy Winehouse 2 93.00 4.04

209 Anne-SophieMutter, HerbertVon Karajan &WienerPhilharmoniker

1 3.32 3.32

243 Antal Doráti &London SymphonyOrchestra

1 6.87 6.87

6 Antônio CarlosJobim

2 118.81 3.83

7 Apocalyptica 1 44.52 5.57

Only 20 rows of the result being shown. The result set has 204 rows, one for eachartist.

73

Page 78: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Figure 12. Multiple SQL Selects

Back to [top].

74

Page 79: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.18. derivedTable 2 - Part AObjective: The Top Order Tracks is a list of tracks from orders in a year that are $5 or more. Whatother tracks across all orders share a track from the Top Order Tracks list?

Approach: Use a set of derived tables (sub-queries) to create progressive filters to get the result

• Part A - List of invoices for one year that are $5 or more

• Part B - Get the list of tracks for the invoices in the Part A, this is the Top Order Tracks list

• Part C - Find all invoices that have a track from Part B the Top order Tacks list.

• Part D - Find all tracks, across all invoices, with a match in the Top Order List and count them

Figure 13. derivedTable Filter

This request could be done using a single query. The derived tables are being usedhere, to show how they can be used as a filter or reduce the number of rows in theresult.

Derived Tables are also know as sub-queries.

75

Page 80: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

SQL Example

/*=== derivedTable List of invoice numbers for orders $5 or more

Part A - Which invoices have a totoal of $5 or more.

==== Topics

* Column Alias, rename a column* Comments, information or debugging* Date functions* Where, results filter or restriction* Table alias, standardize and simplify table/view names*/

select-- i.customerid ①  I.InvoiceID-- ,i.InvoiceDate ①-- ,i.total ①from DCH_Training.Invoice I

where I.InvoiceDate between date '2018-01-01' and date '2018-12-31' ② ③and I.total >= 5.00

① Fields used during the testing of the derived table (sub-query) two hyphens -- used to commentout a line

② between function requires starting value and ending value

③ date indicates a date field, Teradata standard format is yyyy-mm-dd

SQL Download link click here

Table 31. Results

InvoiceId

383

404

362

339

341

375

402

354

381

333

76

Page 81: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

InvoiceId

360

411

396

390

348

369

367

409

346

Only 20 rows of the result being shown. The result set has 35 rows, one for eachinvoice of $5 or more.

Back to [top].

77

Page 82: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.19. derivedTable 2 - Part BObjective:

Approach:

Figure 14. derivedTable Filter

This request could be done using a single query. The derived tables are being usedhere, to show how they can be used as a filter or reduce the number of rows in theresult.

Derived Tables are also know as sub-queries.

78

Page 83: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

SQL Example

/*=== derivedTable List of tracks on the invoice numbers for orders $5 or more for year2018

Part B - List of tracks on the 2018 orders $5 or larger. (*Top Order Tracks* list*)

==== Topics

* Between function* Cast for formatting* Column Alias, rename a column* Comments, information or debugging* Date functions* Derived Table (Sub-Query)* Join objects (Table, View, Derived Table) together* Where, results filter or restriction* Table alias, standardize and simplify table/view names*/

Select Distinct ⑤  IL.TrackIDfrom DCH_Training.InvoiceLine IL

inner join  ( -- 2018 Invoices $5 or more ①  select  I.InvoiceID  from DCH_Training.Invoice I  where I.InvoiceDate between date '2018-01-01' and date '2018-12-31' ② ③  and I.total >= 5.00  ) as RI ④on RI.InvoiceID = IL.InvoiceID

① Derived Table (Sub-query) begins with a ( then the sub-query SQL

② between function requires starting value and ending value

③ date indicates a date field, Teradata standard format is yyyy-mm-dd

④ The end of the derived table (sub-query) is marked with a ) and a name for the derived table RIReduced Invoices. The derived table name is used to qualify the use of the columns in the mainquery.

⑤ DISTINCT used to eliminate duplicates, applied to the entire result set

SQL Download link click here

Table 32. Results

TrackId

1422

79

Page 84: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

TrackId

711

2085

735

2609

807

2681

2109

3109

1235

449

1307

473

1807

521

1823

2299

949

2323

Only 20 rows of the result being shown. The result set has 345 rows, one for eachtrack of a 2018 order of $5 or more.

Back to [top].

80

Page 85: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.20. derivedTable 2 - Part CObjective:

Approach:

Figure 15. derivedTable Filter

This request could be done using a single query. The derived tables are being usedhere, to show how they can be used as a filter or reduce the number of rows in theresult.

Derived Tables are also know as sub-queries.

81

Page 86: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

SQL Example

/*=== derivedTable List of invoices that share a track with another list

Part C - List of invoices that share a track from the 2018 orders $5 or larger (*TopOrder Tracks* list*)

==== TOPICS

* Distinct to elminate duplicates* Join multiple tables* Derived table or sub-query* Aggregation functions to be used for count* Table Alias* Between function* Date representation

*/

Select distinct ①  IL.InvoiceIDfrom DCH_Training.InvoiceLine IL

inner join  ( -- Track list for 2018 invoice $5 or more ②  Select DISTINCT ①  IL.TrackID  from DCH_Training.InvoiceLine IL

  inner join  ( -- 2018 Invoices $5 or more ③  select  I.InvoiceID  from DCH_Training.Invoice I  where I.InvoiceDate between date '2018-01-01' and date '2018-12-31' ⑦ ⑧  and I.total >= 5.00  ) as RI ④  on RI.InvoiceID = IL.InvoiceID

  ) as TL ⑤on TL.TrackID = IL.TrackID ⑥

① DISTINCT used to eliminate duplicates, applied to the entire result set

② Derived Table (Sub-query) begins with a ( then the sub-query SQL

③ Derived Table (Sub-query) begins with a ( then the sub-query SQL

④ The end of the derived table (sub-query) is marked with a ) and a name for the derived table RIReduced Invoices. The derived table name is used to qualify the use of the columns in the mainquery.

82

Page 87: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

⑤ The end of the derived table (sub-query) is marked with a ) and a name for the derived table TLTrack List. The derived table name is used to qualify the use of the columns in the main query.

⑥ Filter for only tracks that match tracks in the TL trackList Top OrderTrack list

⑦ between function requires starting value and ending value

⑧ date indicates a date field, Teradata standard format is yyyy-mm-dd

SQL Download link click here

Table 33. Results

InvoiceId

163

88

361

334

198

171

150

32

348

369

396

409

134

155

169

353

185

190

383

Only 20 rows of the result being shown. The result set has ??? rows, one for eachtrack of a 2018 order of $5 or more.

Back to [top].

83

Page 88: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.21. derivedTable 2 - Part D

Figure 16. derivedTable Filter

This request could be done using a single query. The derived tables are being usedhere, to show how they can be used as a filter or reduce the number of rows in theresult.

Derived Tables are also know as sub-queries.

SQL Example

/*

derivedTable List of album/track info for other tracks that match 2018 order $5 ormore track list

Part D - Add Album and Track information

==== Topics

* Between function* Column Alias, rename a column* Comments, information or debugging* Date functions* Derived Table (Sub-Query)* Group by, required for non-aggregate columns* Having, filter for aggregate column* Join objects (Table, View, Derived Table) together* Order by, also known as sorting* Where, results filter or restriction

84

Page 89: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

* Table alias, standardize and simplify table/view names*/

Select  IL.TrackID  ,T.Name as trackName ①  ,A.AlbumID  ,A.AlbumTitle  ,count(T.TrackID) as trackCount ②from DCH_Training.InvoiceLine IL

inner Join DCH_Training.Track Ton T.TrackID = IL.TrackID

inner join DCH_Training.Album Aon A.AlbumID = T.AlbumID

inner join  ( -- Any invoice with tracks from the 2018 invoice $5 or more track list ③  Select distinct ④  IL.InvoiceID  from DCH_Training.InvoiceLine IL

  inner join  ( -- Track list for 2018 invoice $5 or more ⑤  Select  IL.TrackID  from DCH_Training.InvoiceLine IL

  inner join  ( -- 2018 Invoices $5 or more ⑥  select DISTINCT ④  DCH_Training.I.InvoiceID  from DCH_Training.Invoice I  where I.InvoiceDate between date '2018-01-01' and date '2018-12-31' ⑦ ⑧  and I.total >= 5.00  ) as RI ⑨  on RI.InvoiceID = IL.InvoiceID

  ) TL ⑩  on TL.TrackID = IL.TrackID

  ) as SI ⑪on SI.InvoiceID = IL.InvoiceID

-- Syntax below is related to the top most query

group by ⑫  IL.TrackID  ,T.Name  ,A.AlbumID

85

Page 90: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

  ,A.AlbumTitle

Order by  trackCount Desc ⑬  ,trackname ⑭

Having trackCount >= 2 ⑮

① column alias

② derived column with column alias

③ The beginning of a derived table (sub-query) starts with a (

④ DISTINCT used to eliminate duplicates, applied to the entire result set

⑤ The beginning of a derived table (sub-query) starts with a (

⑥ The beginning of a derived table (sub-query) starts with a (

⑦ between function requires starting value and ending value

⑧ date indicates a date field, Teradata standard format is yyyy-mm-dd

⑨ The end of the derived table (sub-query) is marked with a ) and a name for the derived table RIReduced Invoices. The derived table name is used to qualify the use of the columns in the mainquery.

⑩ The end of the derived table (sub-query) is marked with a ) and a name for the derived table TLTrack List. The derived table name is used to qualify the use of the columns in the main query.

⑪ The end of the derived table (sub-query) is marked with a ) and a name for the derived table SISpecial Invoices. The derived table name is used to qualify the use of the columns in the mainquery.

⑫ Group by required for any column that is not an aggregate column

⑬ trackCount is a column alias of a derived column (Count) used here for sorting

⑭ trackName is a column alias

⑮ having is a filter for a aggregate column

SQL Download link click here

Table 34. Results

TrackId trackName AlbumId AlbumTitle trackCount

2108 Children Of TheGrave

174 Tribute 5

698 Good Golly MissMolly

55 Chronicle, Vol. 2 3

2250 Nega Do CabeloDuro

184 Os Cães LadramMas A CaravanaNão Pára

3

530 Ando MeioDesligado

42 Minha História 2

86

Page 91: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

TrackId trackName AlbumId AlbumTitle trackCount

1853 Battery 152 Master Of Puppets 2

1865 Better Than You 153 ReLoad 2

2172 Big Wave 179 Pearl Jam 2

2305 Binky TheDoormat

189 New AdventuresIn Hi-Fi

2

2793 CabeçaDinossauro

224 Acústico 2

449 Calling Dr. Love 37 Greatest Kiss 2

1226 Can I Play WithMadness

96 A Real Live One 2

2781 Comida 224 Acústico 2

681 Commotion 54 Chronicle, Vol. 1 2

2763 Compadre 222 Serie Sem Limite(Disc 1)

2

512 ComportamentoGeral

41 Meus Momentos 2

2317 Country Feedback 187 Out Of Time 2

1621 Dazed andConfused

132 Led Zeppelin I 2

2531 End OfRomanticism

204 Morning Dance 2

3064 Eruption 243 The Best Of VanHalen, Vol. I

2

Only 20 rows of the result being shown. The result set has 88 rows, one for eachtrack of an order with a matching track in the Top Order Track list.

Back to [top].

87

Page 92: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.22. Create ViewA view is a database object is built from other database objects like tables and views.

Views can help give you a simpler viewable version of a complex query.

Views can help you reuse a standard copy of a database object across queries.

Unlike a table which takes up permanent space for its data, a view does not take up permanentspace.

To create views in your database area you will need to have Perm Space assigned toyour account.

3.22.1. Example

In the Chinook database many of the queries require comprehensive Album information.

The Album view with comprehensive album information we need join data from five differenttables.

Figure 17. vAlbum Relationships

88

Page 93: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

SQL Example

/* Create vAlbums with all required parts

=== Create View - Create a view for comprehensive album information

NOTE: Your account must have `perm space` assigned to it to create a view

* Need to join the following tables** Album - Artist** Album - Track** Track - Genre** Track - Media Type

==== Topics

* Calculated columns* Column Alias, rename a column* Comments, information or debugging* Join objects (Table, View, Derived Table) together* Table alias, standardize and simplify table/view names* Teradata Specific syntax*/

--Drop view DCH_Training.vAlbum;

Create view DCH_Training.vAlbum ①-- Update View vAlbum ②

as

Select  AL.AlbumId  ,AL.AlbumTitle  ,AR.ArtistID  ,AR.Name as artistName ③  ,T.TrackId  ,T.Name as titleName  ,T.Composer  ,T.Milliseconds  ,T.Milliseconds / 60000.00 as minutes -- Divide milliseconds by 60,000 for minutes④  ,T.SizeBytes  ,T.SizeBytes / 1048576.00 as mbSize -- Megabyte 2^20 1024 x 1024 or 1,048,567 ⑤  ,G.GenreId  ,G.Name as genreName  ,MT.MediaTypeID  ,MT.Name as mediaTypeNamefrom DCH_Training.Album AL ⑥

INNER JOIN DCH_Training.Artist AR -- Artist name ⑥

89

Page 94: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

on AR.ArtistID = AL.ArtistID

INNER JOIN DCH_Training.Track T -- All tacks info ⑥on T.AlbumID = AL.AlbumId

INNER JOIN DCH_Training.Genre G -- Genre for each trackon G.GenreId = T.GenreId ⑥

INNER JOIN DCH_Training.MediaType MT -- MediaType for each trackon MT.MediaTypeId = T.MediaTypeId; ⑥

① The first time a view is built use the Create statement

② To change an existing view use the update statement

③ Column Alias in order avoid confusion with the field name

④ Derived Column (aka Calculated Column) notice the 60000.00 has two zeros of precision in orderto return a decimal number

⑤ Derived Column (aka Calculated Column) notice the 1048576.00 has two zeros of precision inorder to return a decimal number

⑥ Table alias, each joined table has it own unique table alias.

In this example the Album table was chosen as the main table of the view.

SQL Download link click here

If you didn’t create the view then you may not know the column names of the view.

To display a list of the vAlbum view columns use

help view vAlbum

The column list of the view will be returned.

90

Page 95: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Figure 18. Display View Columns

This column list may be sufficient enough for you to use the view in your work.

If you need more knowledge about how the vAlbum view was built use

show view vAlbum

The SQL statement used to create the vAlbum view will be returned.

91

Page 96: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Figure 19. Display View SQL

Any bulk comments /* comments \*/ will have been stripped out by Teradata whenthe view is created or updated.

92

Page 97: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Figure 20. Longest Query Rewards

Back to [top].

93

Page 98: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.23. Date FiltersThe Teradata extract function provides month, day and year.

The Teradata Csum OLAP function is used for the running totals.

Csum( column to sum, Column to sum by ).

This query displays a cumulative sum (Running total) of the sales occurring during the "BargainDays". "Bargain Days" are the first week of September thru December for 2018.

SQL Example

/*

dateFilters Date filters and OLAP function

==== Topics

* Column Alias, rename a column* Comments, information or debugging* Date functions* OLAP function basic (Csum, Rank, Cube)* Order by, also known as sorting* Where, results filter or restriction* Table alias, standardize and simplify table/view names*/

select  I.InvoiceDate  ,extract(month from I.InvoiceDate) as invoiceMonth ① ②  ,extract(day from I.InvoiceDate) as invoiceDay ②  ,I.CustomerID  ,I.Total as invoiceTotal ①  ,csum(invoiceTotal, I.InvoiceDate) as cumulativeSum ③from DCH_Training.Invoice I ④

where  extract(month from I.InvoiceDate) in (9,10,11,12) ②and extract(day from I.InvoiceDate) in (1,2,3,4,5,6,7,8) ②and extract(year from I.InvoiceDate) = 2018 ②order by  DCH_Training.I.InvoiceDate

① Column Alias

② Date function Extract

③ OLAP Csum

④ Table alias

94

Page 99: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

SQL Download link click here

Table 35. Results

InvoiceDate invoiceMonth invoiceDay CustomerId invoiceTotal cumulativeSum

2018-09-02 9 2 25 1.98 1.98

2018-09-02 9 2 27 1.98 3.96

2018-09-03 9 3 29 3.96 7.92

2018-09-04 9 4 33 5.94 13.86

2018-09-07 9 7 39 8.91 22.77

2018-10-03 10 3 6 1.98 26.73

2018-10-03 10 3 4 1.98 24.75

2018-10-04 10 4 8 3.96 30.69

2018-10-05 10 5 12 5.94 36.63

2018-10-08 10 8 18 8.91 45.54

2018-11-03 11 3 44 1.98 49.50

2018-11-03 11 3 42 1.98 47.52

2018-11-04 11 4 46 3.96 53.46

2018-11-05 11 5 50 5.94 59.40

2018-11-08 11 8 56 8.91 68.31

2018-12-04 12 4 21 1.98 72.27

2018-12-04 12 4 23 1.98 70.29

2018-12-05 12 5 25 3.96 76.23

2018-12-06 12 6 29 5.94 82.17

95

Page 100: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Figure 21. Time Quote

Back to [top].

96

Page 101: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.24. RankingRanking is a combination of sorting the results and assigning an ordinal number corresponding tothe rank for the result. Similar ranked numbers share the ordinal number assigned to them.

The Teradata Rank function uses just one argument, the column you want to rank by.

The Rank function and aggregate functions can not be a single select query.

In this query we want

• Ranking of Genre by the number of Sales.

• A Sale relates to an single InvoiceLineItem.

• Each InvoiceLineItem is related to a Track which has the Genre information

• So an Invoice with 6 InvoiceLineItems counts as a Sale count of 6

SQL Example

/*

=== Ranking - How to perform a ranking of the results

NOTE: Because `rank` can *NOT* be done in the same query as an aggregate function`count`this query uses a derived table for the `count` which is used in the main query forthe `rank`

==== Topics

* Aggregates (Count, Sum, Min, Max, Avg, etc)* Column Alias, rename a column* Comments, information or debugging* Derived Table (Sub-Query)* Group by, required for non-aggregate columns* Join objects (Table, View, Derived Table) together* OLAP function basic (Csum, Rank, Cube)* Table alias, standardize and simplify table/view names* Teradata Specific syntax* Union, multiple select queries stacked

==== Special Notes* Do *NOT* use `order by` when using `rank`, this will return the incorrect results*/

Select  GC.genreName  ,GC.saleCount  ,rank(GC.saleCount) as ranking ① ②from

97

Page 102: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

(  SELECT  G.Name as genreName ①  ,count(IL.InvoiceLineID) As saleCount ③  from DCH_Training.InvoiceLine IL

  inner join DCH_Training.Track T ④  on T.trackID = IL.TrackID

  inner join DCH_Training.Genre G ④  on G.GenreID = T.GenreID

  group by  genreName ⑤) as GC; -- genreCounts derviced table name (GC) ⑥

-- Restrict results by the ranking value requires the QUALIFY phrase-- like a where but for OLAP function columnsSelect  GC.genreName  ,GC.saleCount  ,rank(GC.saleCount) as ranking ① ②from(  SELECT  G.Name as genreName ①  ,count(IL.InvoiceLineID) As saleCount ③  from DCH_Training.InvoiceLine IL

  inner join DCH_Training.Track T ④  on T.trackID = IL.TrackID

  inner join DCH_Training.Genre G ④  on G.GenreID = T.GenreID

  group by  genreName ⑤) as GC -- genreCounts derviced table name (GC) ⑥QUALIFY ranking <= 10; ⑦

① Column alias

② OLAP function Rank

③ Aggregate function Count

④ Table alias

⑤ Column Alias for group by

⑥ Derived Table (Sub-query) named GC for genreCounts

98

Page 103: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Because the GC columns come from a derived table they can be used in group by.The restriction is that the Table alias GC can NOT be part of the column name.

Because Rank is automatically doing the Order by based on the column in the Rankstatement. Do NOT add an additional order by the results will be incorrect.

SQL Download link click here

Table 36. Results

genreName saleCount ranking

Rock 835 1

Latin 386 2

Metal 264 3

Alternative & Punk 244 4

Jazz 80 5

Blues 61 6

TV Shows 47 7

Classical 41 8

R&B/Soul 41 8

Reggae 30 10

Drama 29 11

Pop 28 12

Sci Fi & Fantasy 20 13

Soundtrack 20 13

Hip Hop/Rap 17 15

Bossa Nova 15 16

Alternative 14 17

World 13 18

Heavy Metal 12 19

Electronica/Dance 12 19

Easy Listening 10 21

Comedy 9 22

Rock And Roll 6 23

Science Fiction 6 23

<1>

The Genre’s Sci Fi & Fantasy and Soundtrack share ranking number 13 becausethey both have a saleCount of 20. There are two other shared ranking numbers 19and 23

99

Page 104: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Figure 22. Ranking Quote

Back to [top].

100

Page 105: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.25. RollupSometimes intermediate totals by different groupings in a hierarchy are needed.

The Group by Rollup OLAP function can provide this capability.

The rollup totals appear at the top of the results because of the order by

This query asks for track counts by the following groups

1. Grand (Everything)

2. County

3. Year

4. Genre

101

Page 106: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

SQL Example

/*

=== group Rollup = Getting group and grant totals

==== Topics

* Aggregates (Count, Sum, Min, Max, Avg, etc)* Column Alias, rename a column* Join objects (Table, View, Derived Table) together* OLAP function basic (Group Rollup)* Order by, also known as sorting* Table alias, standardize and simplify table/view names*/

-- Get track counts with rollup totals by 4 levels Grand, Country, Year, GenreSelect  I.BillingCountry as country ①  ,Extract(Year from I.InvoiceDate) as saleYear ① ②  ,G.Name as genreName  ,count(IL.TrackID) as trackCount ①from DCH_Training.Invoice I ③

Inner Join DCH_Training.InvoiceLine IL ③on IL.InvoiceId = I.InvoiceId

Inner Join DCH_Training.Track T ③on T.TrackID = IL.TrackID

Inner Join DCH_Training.Genre G ③on G.GenreID = T.GenreID

Group by Rollup ④  (  country  ,saleYear  ,genreName  )

Order by ⑤  country  ,saleYear  ,genreName  ,trackCount DESC

① Column alias

② Data function (Extract)

③ Table alias

102

Page 107: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

④ OLAP function (Group by Rollup)

⑤ Order by, columns should be in order of the group totals

SQL Download link click here

Table 37. Results

country saleYear genreName trackCount

NULL NULL NULL 2245

Argentina NULL NULL 38

Argentina 2015 NULL 12

Argentina 2015 Alternative & Punk 2

Argentina 2015 Metal 6

Argentina 2015 Rock 4

Argentina 2016 NULL 1

Argentina 2016 Metal 1

Argentina 2018 NULL 25

Argentina 2018 Alternative & Punk 7

Argentina 2018 Easy Listening 2

Argentina 2018 Jazz 2

Argentina 2018 Latin 8

Argentina 2018 Rock 5

Argentina 2018 Soundtrack 1

Australia NULL NULL 38

Australia 2014 NULL 12

Australia 2014 Metal 3

Australia 2014 Rock 9

Australia 2015 NULL 1

Australia 2015 Rock 1

Australia 2016 NULL 2

Australia 2016 Latin 2

Australia 2017 NULL 23

Australia 2017 Blues 1

Australia 2017 Heavy Metal 3

Australia 2017 Metal 5

Australia 2017 Reggae 2

Australia 2017 Rock 12

Only the first 2 countries are displayed. There are 561 rows in the actual result.

103

Page 108: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

The Country total has null for saleYear and genreName

The Year total has null for genreName

Back to [top].

104

Page 109: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.26. CubeThe Teradata Cube OLAP function generates a result that basically ALL of the aggregate totals acrossall three of the columns used as dimensions.

The results of a Cube query can take considerable time to complete depending on the amount ofdata being analyzed. Some consideration should be given creating a table (Materializing) using theresults of a Cube query. Then subsequent queries against the materialized Cube table will be muchquicker.

In this example the Cube will be generated based on three columns or dimensions.

1. Country

2. Sales Year

3. Genre Name

Each Cell of a Cube can contain one of more values including aggregates.

The two aggregates being collected for each of the intersecting cells is

• Track Count

• Sales Total

Here is what the Cube looks like using a visual reference.

Figure 23. Sample Cube

The Teradata Cube OLAP function creates slices based on combinations of the dimension columns.

There are 8 different slices available from a Cube result. In this example that are

1. Single cell slice for one Country, one Sales Year and, one GenreName.

2. Country - GenreName slice

105

Page 110: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3. Country - Sale Year Slice

4. Sale Year - Genre Name Slice

5. Country only slice

6. Sale Year only slice

7. Genre Name only Slice

8. Grand total slice

The following visuals may help to describe the different slices.

Figure 24. Country - Genre Name Slice

Figure 25. Country - Sale Year Slice

106

Page 111: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Figure 26. Sale Year - Genre Name Slice

Figure 27. Country Only Slice

107

Page 112: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Figure 28. Sale Year Only Slice

Figure 29. Genre Name Only Slice

108

Page 113: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Figure 30. Grand total slice

Figure 31. Cube Quote

109

Page 114: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.27. Cube BasicThis query shows the Cube OLAP function being used for the Country, SaleYear and, GenreNamecolumns.

110

Page 115: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

SQL Example

/*

=== group Cube = Getting group and grand totals

==== Topics

* Aggregates (Count, Sum, Min, Max, Avg, etc)* Column Alias, rename a column* Join objects (Table, View, Derived Table) together* OLAP function basic (Group Rollup)* Order by, also known as sorting* Table alias, standardize and simplify table/view names*/

-- Get track counts with rollup totals by 4 levels Grand, Country, Year, GenreSelect  I.BillingCountry as country ①  ,Extract(Year from I.InvoiceDate) as saleYear ① ②  ,G.Name as genreName  ,count(IL.TrackID) as trackCount ① ③  ,sum(I.Total) as saleTotal ① ③from DCH_Training.Invoice I ④

Inner Join DCH_Training.InvoiceLine IL ④on IL.InvoiceId = I.InvoiceId

Inner Join DCH_Training.Track T ④on T.TrackID = IL.TrackID

Inner Join DCH_Training.Genre G ④on G.GenreID = T.GenreID

Group by Cube ⑤  (  country  ,saleYear  ,genreName  )

Order by  country  ,saleYear  ,genreName  ,trackCount DESC

① Column alias

② Date function EXTRACT Year

③ Aggregate function SUM, COUNT

111

Page 116: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

④ Table Alias

⑤ OLAP Function GROUP BY Cube, NOTE: the () around the dimension columns

SQL Download link click here

Table 38. Results

country saleYear genreName trackCount saleTotal

NULL NULL NULL 2240 20848.62

NULL NULL Alternative 14 211.17

NULL NULL Alternative &Punk

244 1961.66

NULL NULL Blues 61 429.66

NULL NULL Bossa Nova 15 86.13

NULL NULL World 13 182.18

NULL 2014 NULL 454 4011.48

NULL 2014 Alternative &Punk

63 466.29

NULL 2014 Blues 11 112.86

NULL 2014 Bossa Nova 1 13.86

Argentina NULL NULL 38 334.62

Argentina NULL Alternative &Punk

9 80.19

Argentina NULL Easy Listening 2 27.72

Argentina NULL Jazz 2 3.96

Argentina NULL Latin 8 91.08

Austria NULL NULL 38 404.62

Austria NULL Classical 2 11.88

Austria NULL Drama 1 18.86

Austria NULL Jazz 2 17.82

Austria NULL Latin 2 3.96

Austria NULL Metal 7 48.51

Austria NULL Pop 1 5.94

Austria NULL R&B/Soul 4 18.81

Brazil 2014 NULL 38 334.62

Brazil 2014 Alternative &Punk

2 27.72

Brazil 2014 Blues 5 29.70

Brazil 2014 Hip Hop/Rap 2 27.72

Brazil 2014 Latin 2 17.82

112

Page 117: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

country saleYear genreName trackCount saleTotal

Brazil 2014 Metal 6 19.80

Brazil 2014 Reggae 1 13.86

Brazil 2014 Rock 20 198.00

Only a small portion of the results are being displayed, there are 928 rows in theresult.

It is possible to view any one slice by using the proper combination of filters for is null on thedimension columns Country, Sale Year and, Genre Name.

Back to [top].

113

Page 118: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.28. Cube Slice TypeIf the different slice types are being used for other queries or reports it is a good practice to add acolumn to define the Slice Type.

SQL Example

/*

=== group Cube = Getting group and grandtotals, adding sliceType

==== Topics

* Aggregates (Count, Sum, Min, Max, Avg, etc)* Column Alias, rename a column* Join objects (Table, View, Derived Table) together* OLAP function basic (Group Rollup)* Order by, also known as sorting* Table alias, standardize and simplify table/view names*/

-- Get track counts with rollup totals by 4 levels Grand, Country, Year, GenreSelect  I.BillingCountry as country ①  ,Extract(Year from I.InvoiceDate) as saleYear ① ②  ,G.Name as genreName  ,count(IL.TrackID) as trackCount ① ③  ,sum(I.Total) as saleTotal ① ③  ,CASE ④  WHEN (country is null) and (saleYear is null) and (genreName is null) then'Grand' ⑤  WHEN (country is null) and (saleYear is null) then 'Genre'  WHEN (country is null) and (genreName is null) then 'Year'  WHEN (saleYear is null) and (genreName is null) then 'Country'  WHEN(country is null) then 'YearGenre'  WHEN (saleYear is null) then 'CountryGenre'  WHEN (genreName is null) then 'CountryYear'  ELSE 'CountryYearGenre'  END as sliceTypefrom DCH_Training.Invoice I ⑥

Inner Join DCH_Training.InvoiceLine IL ⑥on IL.InvoiceId = I.InvoiceId

Inner Join DCH_Training.Track T ⑥on T.TrackID = IL.TrackID

Inner Join DCH_Training.Genre G ⑥on G.GenreID = T.GenreID

Group by Cube ⑦

114

Page 119: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

  (  country  ,saleYear  ,genreName  )

--Order by ⑧-- country-- ,saleYear-- ,genreName-- ,trackCount DESC

① Column Alias

② Date function EXTRACT Year

③ Aggregate function SUM, COUNT

④ Case statement, this is the if clause for SQL

⑤ Each SliceType is determine by which dimension columns is null

⑥ Table alias

⑦ OLAP Function GROUP BY Cube, NOTE: the () around the dimension columns

⑧ Order by was commented out, in many cases the order of the Cube is NOT important.

The Case statement processes the SliceType in the order of the when clauses.

Be careful of the Case statement when order to assure the SliceType is accurate.

SQL Download link click here

Table 39. Results

country saleYear genreName trackCount saleTotal sliceType

Czech Republic 2018 Rock 6 71.40 CountryYearGenre

Brazil 2017 Classical 6 39.60 CountryYearGenre

Austria 2017 R&B/Soul 3 17.82 CountryYearGenre

Hungary 2015 Comedy 1 21.86 CountryYearGenre

France 2015 Rock 17 116.82 CountryYearGenre

Spain 2014 Metal 1 0.99 CountryYearGenre

Chile 2017 Rock 6 35.64 CountryYearGenre

115

Page 120: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

country saleYear genreName trackCount saleTotal sliceType

Canada 2014 Rock 27 255.42 CountryYearGenre

Germany 2017 Alternative &Punk

1 8.91 CountryYearGenre

Norway 2018 Alternative &Punk

2 3.96 CountryYearGenre

Czech Republic 2014 Electronica/Dance

2 17.82 CountryYearGenre

Brazil 2015 Blues 1 0.99 CountryYearGenre

Belgium 2014 Rock 6 35.64 CountryYearGenre

Poland NULL Rock 22 191.07 CountryGenre

Netherlands NULL Rock 18 198.00 CountryGenre

Sweden NULL Jazz 1 13.86 CountryGenre

France NULL Soundtrack 5 54.45 CountryGenre

UnitedKingdom

NULL Jazz 4 13.86 CountryGenre

Czech Republic NULL Metal 8 102.15 CountryGenre

NULL 2017 Heavy Metal 3 41.58 YearGenre

NULL 2015 Soundtrack 4 55.44 YearGenre

NULL 2014 Bossa Nova 1 13.86 YearGenre

NULL 2014 World 3 41.58 YearGenre

NULL NULL Comedy 9 112.30 Genre

NULL 2017 NULL 447 4256.25 Year

NULL 2016 NULL 443 4140.26 Year

NULL 2015 NULL 455 4329.45 Year

NULL 2014 NULL 454 4011.48 Year

Germany 2018 NULL 10 51.48 CountryYear

India 2017 NULL 11 84.15 CountryYear

Chile 2015 NULL 9 161.19 CountryYear

USA 2015 NULL 102 946.72 CountryYear

Italy 2015 NULL 11 52.47 CountryYear

Norway NULL NULL 38 362.62 Country

USA NULL NULL 494 4667.06 Country

Spain NULL NULL 38 334.62 Country

Finland NULL NULL 38 350.62 Country

116

Page 121: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Only a small portion of the results are being displayed, there are 928 rows in theresult.

Back to [top].

117

Page 122: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.29. Cube CreateBecause the Teradata Cube OLAP function may take considerable time to return results it would bebetter to load the results into a table.

This query is an example of a Cube table. The results from the Cube query are materilized into thistable.

To create a table your account will need Perm Space and special access rightsgranted.

118

Page 123: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

SQL Example

/*

=== createCube - Materilize the cube into a table

NOTE: To create a table your account will need `Perm Space`

NOTE: To create a table your account will need spevcial access rights granted.

==== Topics

* Teradata Specific syntax*/

-- DROP Table DCH_Training.CountrySaleYearGene_Cube;

CREATE SET TABLE DCH_Training.CountrySaleYearGene_Cube ,NO FALLBACK ,  NO BEFORE JOURNAL,  NO AFTER JOURNAL,  CHECKSUM = DEFAULT,  DEFAULT MERGEBLOCKRATIO  (  CubeID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY ①  (START WITH 1  INCREMENT BY 1  MINVALUE -2147483647  MAXVALUE 100000000  NO CYCLE),  Country VARCHAR(40) CHARACTER SET LATIN NOT CASESPECIFIC,  SaleYear INTEGER,  GenreName VARCHAR(120) CHARACTER SET LATIN NOT CASESPECIFIC,  TrackCount INTEGER,  SaleTotal DECIMAL(10,2),  SliceType VARCHAR(20),PRIMARY KEY (CubeID)) ②INDEX (Country) ③INDEX (SaleYear) ③INDEX (GenreName) ③INDEX (SliceType); ④

① CubeID is a system generate unique key column. This unique key is done to help Teradatadistribute the Cube results properly for better performance.`

② Primary Key assists in the proper distribution of results on the Teradata server

③ INDEX definitions are used when how the access of this table will be performed. The SliceTypeindex will most likely be used in most queries against this Cube table.

Back to [top].

119

Page 124: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.30. Cube InsertAfter the Cube table has been created the results from the Cube query need to be inserted into thetable.

SQL Example

/*

=== insertCube - Load the cube table with cube query results

==== Topics

* Aggregates (Count, Sum, Min, Max, Avg, etc)* Between function* Calculated columns* Case statement* Column Alias, rename a column* Comments, information or debugging* Delete from statement* Insert into statement* Join objects (Table, View, Derived Table) together* OLAP function Group by Cube* Table alias, standardize and simplify table/view names* Teradata Specific syntax

*/

-- Assume trable is *NOT* empty amd is being reloadeddelete from DCH_Training.CountrySaleYearGene_Cube; ①

-- Insert results from Cube query

Insert into DCH_Training.CountrySaleYearGene_Cube  ( -- NOTE: CubeID is *NOT* in columns to be updated -②  Country  ,SaleYear  ,GenreName  ,TrackCount  ,SaleTotal  ,SliceType  )

Select  I.BillingCountry as country ③  ,Extract(Year from I.InvoiceDate) as saleYear ③ ④  ,G.Name as genreName  ,count(IL.TrackID) as trackCount ③ ④  ,sum(I.Total) as saleTotal ③ ④  ,CASE ⑤

120

Page 125: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

  WHEN (country is null) and (saleYear is null) and (genreName is null) then'Grand' ⑥  WHEN (country is null) and (saleYear is null) then 'Genre'  WHEN (country is null) and (genreName is null) then 'Year'  WHEN (saleYear is null) and (genreName is null) then 'Country'  WHEN(country is null) then 'YearGenre'  WHEN (saleYear is null) then 'CountryGenre'  WHEN (genreName is null) then 'CountryYear'  ELSE 'CountryYearGenre'  END as sliceTypefrom DCH_Training.Invoice I ⑦

Inner Join DCH_Training.InvoiceLine IL ⑦on IL.InvoiceId = I.InvoiceId

Inner Join DCH_Training.Track T ⑦on T.TrackID = IL.TrackID

Inner Join DCH_Training.Genre G ⑦on G.GenreID = T.GenreID

Group by Cube ⑧  (  country  ,saleYear  ,genreName  )

① Is is good practice to make sure the table you are inserting into in empty

② The columns of the Cube are listed, minus the CubeID which is generated automatically byTeradata

③ Column Alias

④ Date function EXTRACT Year

⑤ Case statement, this is the if clause for SQL

⑥ Each SliceType is determine by which dimension columns is null

⑦ Table alias

⑧ OLAP Function GROUP BY Cube, NOTE: the () around the dimension columns

SQL Download link click here

Back to [top].

121

Page 126: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.31. Cube QueriesBy using the SliceType is is possible to look at any of the 8 slices of the cube.

Cube Grand Slice

/*

=== cubeQuery - Example of Cube table queries

==== Topics

* Where, results filter or restriction* Table alias, standardize and simplify table/view names*/

-- Grand TotalsSelect  CB.TrackCount  ,CB.SaleTotalfrom DCH_Training.CountrySaleYearGene_Cube CB ①Where CB.SliceType ='Grand'; ②

① Table alias

② Where filter

SQL Download link click here

Table 40. Cube Grand Slice Results

TrackCount SaleTotal

2245 20995.26

Back to [top].

122

Page 127: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Cube Country Slice

/*

=== cubeQuery - Example of Cube table queries

==== Topics

* Where, results filter or restriction* Table alias, standardize and simplify table/view names*/

-- Country SliceSelect  CB.Country  ,CB.TrackCount  ,CB.SaleTotalfrom DCH_Training.CountrySaleYearGene_Cube CB ①Where CB.SliceType ='Country' ②Order by  CB.Country;

① Table alias

② Where filter

SQL Download link click here

Table 41. Cube Country Slice Results

Country TrackCount SaleTotal

Argentina 38 334.62

Australia 38 334.62

Austria 38 404.62

Belgium 38 334.62

Brazil 190 1677.10

Canada 304 2689.96

Chile 38 415.62

Czech Republic 78 933.81

Denmark 38 334.62

Finland 38 350.62

France 193 1814.17

Germany 152 1392.48

Hungary 38 446.62

India 74 667.28

Ireland 38 446.62

123

Page 128: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Country TrackCount SaleTotal

Italy 38 334.62

Netherlands 38 352.62

Norway 38 362.62

Poland 38 334.62

Portugal 76 687.24

Spain 38 334.62

Sweden 38 340.62

United Kingdom 114 1003.86

USA 494 4667.06

Back to [top].

Sales Year Slice

/*

=== cubeQuery - Example of Cube table queries

==== Topics

* Where, results filter or restriction* Table alias, standardize and simplify table/view names*/

-- SaleYear SliceSelect  CB.SaleYear  ,CB.TrackCount  ,CB.SaleTotalfrom DCH_Training.CountrySaleYearGene_Cube CB ①Where CB.SliceType ='Year' ②Order by  CB.SaleYear;

① Table alias

② Where filter

SQL Download link click here

Table 42. Cube Sales Year Slice Results

SaleYear TrackCount SaleTotal

2014 454 4011.48

2015 455 4329.45

2016 443 4140.26

124

Page 129: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

SaleYear TrackCount SaleTotal

2017 447 4256.25

2018 446 4257.82

Back to [top].

Genre Name Slice

/*

=== cubeQuery - Example of Cube table queries

==== Topics

* Where, results filter or restriction* Table alias, standardize and simplify table/view names*/

-- GenreName SliceSelect  CB.GenreName  ,CB.TrackCount  ,CB.SaleTotalfrom DCH_Training.CountrySaleYearGene_Cube CB ①Where CB.SliceType ='Genre' ②Order by  CB.GenreName;

① Table alias

② Where filter

SQL Download link click here

Table 43. Cube Genre Name Slice Results

GenreName TrackCount SaleTotal

Alternative 14 211.17

Alternative & Punk 244 1968.59

Blues 61 429.66

Bossa Nova 15 86.13

Classical 41 317.04

Comedy 9 112.30

Drama 29 549.56

Easy Listening 10 138.60

Electronica/Dance 12 149.62

Heavy Metal 12 161.37

125

Page 130: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

GenreName TrackCount SaleTotal

Hip Hop/Rap 18 183.24

Jazz 80 752.40

Latin 386 3493.34

Metal 267 2142.75

Pop 28 239.75

R&B/Soul 41 338.62

Reggae 30 332.64

Rock 836 7754.67

Rock And Roll 6 83.16

Sci Fi & Fantasy 20 198.87

Science Fiction 6 103.40

Soundtrack 20 242.55

TV Shows 47 823.65

World 13 182.18

Back to [top].

Sales Year-Genre Name Slice

/*

=== cubeQuery - Example of Cube table queries

==== Topics

* Where, results filter or restriction* Table alias, standardize and simplify table/view names*/

-- SalesYear-GenreName SliceSelect  CB.SaleYear  ,CB.GenreName  ,CB.TrackCount  ,CB.SaleTotalfrom DCH_Training.CountrySaleYearGene_Cube CB ①Where CB.SliceType ='YearGenre' ②Order by  CB.SaleYear  ,CB.GenreName;

① Table alias

② Where filter

126

Page 131: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

SQL Download link click here

Table 44. Cube Sales Year-Genre Name Slice Results

SaleYear GenreName TrackCount SaleTotal

2014 Alternative & Punk 63 466.29

2014 Blues 11 112.86

2014 Bossa Nova 1 13.86

2014 Easy Listening 3 41.58

2014 Electronica/Dance 2 17.82

2014 Heavy Metal 4 50.49

2014 Hip Hop/Rap 2 27.72

2014 Jazz 20 185.13

2014 Latin 83 789.03

2014 Metal 62 502.92

2014 Pop 1 13.86

2014 R&B/Soul 8 69.30

2014 Reggae 6 58.41

2014 Rock 180 1561.23

Only a small portion of the results are displayed. There are 104 rows in the result.

Back to [top].

127

Page 132: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Country-Genre Name Slice

/*

=== cubeQuery - Example of Cube table queries

==== Topics

* Where, results filter or restriction* Table alias, standardize and simplify table/view names*/

-- Country-GenreName SliceSelect  CB.Country  ,CB.GenreName  ,CB.TrackCount  ,CB.SaleTotalfrom DCH_Training.CountrySaleYearGene_Cube CB ①Where CB.SliceType ='CountryGenre' ②Order by  CB.Country  ,CB.GenreName;

① Table alias

② Where filter

SQL Download link click here

Table 45. Cube Country-Genre Name Slice Results

Country GenreName TrackCount SaleTotal

Argentina Alternative & Punk 9 80.19

Argentina Easy Listening 2 27.72

Argentina Jazz 2 3.96

Argentina Latin 8 91.08

Argentina Metal 7 36.63

Argentina Rock 9 81.18

Argentina Soundtrack 1 13.86

Australia Blues 1 13.86

Australia Heavy Metal 3 41.58

Australia Latin 2 3.96

Australia Metal 8 87.12

Australia Reggae 2 17.82

Australia Rock 22 170.28

Austria Classical 2 11.88

128

Page 133: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Only a small portion of the results are displayed. There are 237 rows in the result.

Back to [top].

Country-Sales Year Name Slice

/*

=== cubeQuery - Example of Cube table queries

==== Topics

* Where, results filter or restriction* Table alias, standardize and simplify table/view names*/

-- Country-SaleYear SliceSelect  CB.Country  ,CB.SaleYear  ,CB.TrackCount  ,CB.SaleTotalfrom DCH_Training.CountrySaleYearGene_Cube CB ①Where CB.SliceType ='CountryYear' ②Order by  CB.Country  ,CB.SaleYear;

① Table alias

② Where filter

SQL Download link click here

Table 46. Cube Country-Sales Year Slice Results

Country SaleYear TrackCount SaleTotal

Argentina 2015 12 55.44

Argentina 2016 1 0.99

Argentina 2018 25 278.19

Australia 2014 12 55.44

Australia 2015 1 0.99

Australia 2016 2 3.96

Australia 2017 23 274.23

Austria 2014 2 3.96

Austria 2015 23 344.23

Austria 2017 12 55.44

129

Page 134: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Country SaleYear TrackCount SaleTotal

Austria 2018 1 0.99

Belgium 2014 7 36.63

Belgium 2016 25 278.19

Belgium 2018 6 19.80

Only a small portion of the results are displayed. There are 101 rows in the result.

Back to [top].

Country-Sales Year-Genre Name Name Slice

/*

=== cubeQuery - Example of Cube table queries

==== Topics

* Where, results filter or restriction* Table alias, standardize and simplify table/view names*/

-- Country-SaleYear-GenereName CellSelect  CB.Country  ,CB.SaleYear  ,CB.GenreName  ,CB.TrackCount  ,CB.SaleTotalfrom DCH_Training.CountrySaleYearGene_Cube CB ①Where CB.SliceType ='CountryYearGenre' ②Order by  CB.Country  ,CB.SaleYear  ,CB.GenreName;

① Table alias

② Where filter

SQL Download link click here

Table 47. Cube Country-Sales Year-Genre Name Slice Results

Country SaleYear GenreName TrackCount SaleTotal

Argentina 2015 Alternative &Punk

2 7.92

Argentina 2015 Metal 6 35.64

Argentina 2015 Rock 4 11.88

130

Page 135: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Country SaleYear GenreName TrackCount SaleTotal

Argentina 2016 Metal 1 0.99

Argentina 2018 Alternative &Punk

7 72.27

Argentina 2018 Easy Listening 2 27.72

Argentina 2018 Jazz 2 3.96

Argentina 2018 Latin 8 91.08

Argentina 2018 Rock 5 69.30

Argentina 2018 Soundtrack 1 13.86

Australia 2014 Metal 3 17.82

Australia 2014 Rock 9 37.62

Australia 2015 Rock 1 0.99

Australia 2016 Latin 2 3.96

Only a small portion of the results are displayed. There are 423 rows in the result.

Back to [top].

131

Page 136: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.32. Parameter FieldsBy using a Parameter Field ?Parameter queries can popup dialog boxes to asked for user inputwhich in turn can be used in the query.

How you name the parameter fields determines the order in which they are asked.To assure the order you intended recede the parameter field name with a fewdigits (01Parameter, 02Parameter).

These examples are done using the Teradata SQL Assistant tool. Other tools mayhandle parameter fields differently

Figure 32. Sample query with parameter fields

132

Page 137: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Parameter fields

/*

=== queryParameter

==== Topics

* Like %Search% similar to `contains`* Where, results filter or restriction* Table alias, standardize and simplify table/view names* Teradata Specific syntax

*/Select  VA.TitleName  ,AlbumTitle  ,ArtistNamefrom DCH_Training.vAlbum VA ①where VA.TitleName like '%' || '?01FirstKeyWord' || '%' ②  and VA.TitleName like '%' || '?02SecondKeyWord' || '%' ②  and VA.ArtistName like '%' || '?03ArtistName' || '%' ②

① Table alias

② Parameter Field ?01FirstKeyword, 02SecondKeyWord, '03ArtistName'

SQL Download link click here

When running the query in Teradata SQL Assistant the following popup’s will appear.

Figure 33. Parameter 01FirstKeyWord

133

Page 138: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Figure 34. Parameter 02SecondKeyWord

Figure 35. Parameter 03ArtistName

The values entered into the dialog boxes are used in the query and the results are.

134

Page 139: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

When running the query in Database5Pro the following popup will appear.

Figure 36. Parameter Field Databse5Pro

Table 48. Parameter Fields Results

titleName AlbumTitle artistName

When Love Comes To Town The Best Of 1980-1990 U2

Love Rescue Me Rattle And Hum U2

Luminous Times (Hold On ToLove)

B-Sides 1980-1990 U2

When Love Comes To Town Rattle And Hum U2

Pride (In The Name Of Love) The Best Of 1980-1990 U2

Pride (In The Name Of Love) Rattle And Hum U2

Love Comes Tumbling B-Sides 1980-1990 U2

135

Page 140: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.33. Parameter TableWhen testing and running queries sometimes there are a set of Prompts that require a standard setof responses. By creating a Parameters Table to hold these response, they can be used in queries toget a known set of results. The Parameters Table is typically created in your personal database area.

In order to create a Parameters Tabl`e and populate it, it requires Perm Space andspecial access roles.

By naming the Response sets you can easily switch between the different sets of responses andshare one Parameter Table across multiple queries.

The name of the Parameter Table and its columns are completely up to your preference.

Parameter Table

/*

=== parameterTable - Create local table for parameters

==== Topics

* Column Alias, rename a column* Comments, information or debugging* Having, filter for aggregate column* Insert into statement* Join objects (Table, View, Derived Table) together* Where, results filter or restriction* Table alias, standardize and simplify table/view names* Teradata Specific syntax* Update statement*/

-- Drop Table myParms

-- Create parms table with columns needed for queriesCreate Table schusterjdchbull.myParms ①(  ParmSetName VARCHAR(25) not null, ②  ParmOne INTEGER, -- Used as Join column ③  Country VARCHAR(40) CHARACTER SET LATIN NOT CASESPECIFIC,  SaleYear INTEGER,  genreID INTEGER,  likeTrack varchar(40) CHARACTER SET LATIN NOT CASESPECIFIC,  trackCount INTEGER,  startDate DATE,  endDate DATE,PRIMARY KEY(ParmSetName));

136

Page 141: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

① Create table NOTE: schusterjdchbull is authors database area

② ParmSetName allows for multiple parameter sets in this Parameter table, use names which reflectthe columns or filters

③ ParmOne is the column used to join the Parameter set to the main query

SQL Download link click here

137

Page 142: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Parameter Table Inserts

/*

=== parameterTable - Create local table for parameters

==== Topics

* Column Alias, rename a column* Comments, information or debugging* Having, filter for aggregate column* Insert into statement* Join objects (Table, View, Derived Table) together* Where, results filter or restriction* Table alias, standardize and simplify table/view names* Teradata Specific syntax* Update statement*/

-- Insert a parm set, just columns neededInsert into schusterjdchbull.myParms ①(  ParmSetName  ,ParmOne  ,genreID  ,likeTrack)Select  'TName-Genre' as ParmSetName ② ③  ,1 as ParmOne ③  ,4 as genreID ②  ,'love' as likeTrack; ②

-- Insert a parm set, just columns neededInsert into schusterjdchbull.myParms ①(  ParmSetName  ,ParmOne  ,startDate  ,endDate)Select  'RangeSales' as ParmSetName ② ③  ,1 as ParmOne ③  ,'2018-01-01' as startDate ②  ,'2018-12-31' as endDate; ②

① Insert statement. NOTE: schusterjdchbull is authors database area

② Column Alias

138

Page 143: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

③ TName-Genre`and `RangeSales are the parameter set names, `ParmOne is the number 1, used tolink to main query

A Parameter Table will have many columns to handle different sets of responses.When loading Insert values into a parameter set you only need to load values intothose columns needed for the query.

SQL Download link click here

After the values have been loaded into the parameter sets, the Parameter Table look like.

Table 49. Parameter Table Results

ParmSetName

ParmOne Country SaleYear genreID likeTrack

trackCount

startDate endDate

TName-Genre

1 NULL NULL 4 love NULL NULL NULL

RangeSales

1 NULL NULL NULL NULL NULL 2018-01-01

2018-12-31

The following query shows how the Parameter Table is used with a main query.

139

Page 144: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Parameter Table Inserts

/*

=== parameterTable - Create local table for parameters

==== Topics

* Column Alias, rename a column* Comments, information or debugging* Having, filter for aggregate column* Insert into statement* Join objects (Table, View, Derived Table) together* Where, results filter or restriction* Table alias, standardize and simplify table/view names* Teradata Specific syntax* Update statement*/

-- Run the actual query with myParms supplying parameSelect  T.Name as trackName ①  ,T.GenreID  ,G.Name as genreName ①

from DCH_Training.Track T ②

inner join Genre G ②on G.GenreID = T.GenreID

inner join schusterjdchbull.myParms MP ② ③on MP.ParmOne = 1 ④

where MP.ParmSetName = 'TName-Genre' ⑤  and trackName like '%' || MP.likeTrack || '%' ⑥  and t.GenreID = MP.genreID ⑦

① Column alias

② Table alias

③ Parameter Table under the authors schusterjdchbull database area

④ MP.ParmOne will always have a value of 1, this performs the join between the main query andthe Parameter Table

⑤ TName-Genre is the name of the parameter set to use from the Parameter table

⑥ MP.likeTrack is one of the columns in the Parameter Table

⑦ MP.genreID is one of the columns in the Parameter Table

When this query is run the values in the TName-Genre row of the Parameters Table will be used toreturn results for tracks with love in the name from the Alternative and Punk genre (genreID: 4).

140

Page 145: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Table 50. Results for love in Alternative & Punk genre

trackName GenreId genreName

The One I Love 4 Alternative & Punk

Real Love 4 Alternative & Punk

She Loves Me Not 4 Alternative & Punk

Jesus Of Suburbia / City Of TheDamned / I Don’t Care / DearlyBeloved / Tales Of AnotherBroken Home

4 Alternative & Punk

My Lovely Man 4 Alternative & Punk

Underwater Love 4 Alternative & Punk

Stand Inside Your Love 4 Alternative & Punk

Rollover D.J. 4 Alternative & Punk

The TName-Genre row of the Parameter Table can be modified by using an Update statement.

Modify Parameter Set

/*

=== parameterTable - Create local table for parameters

==== Topics

* Column Alias, rename a column* Comments, information or debugging* Having, filter for aggregate column* Insert into statement* Join objects (Table, View, Derived Table) together* Where, results filter or restriction* Table alias, standardize and simplify table/view names* Teradata Specific syntax* Update statement*/

-- Update an existing ParmSetUpdate schusterjdchbull.myParms ①set  genreID = 4  ,likeTrack = 'Edge'where ParmSetName = 'TName-Genre'; ②

① Update statement against authors sachusterjdchbull Parameter Table

② TName-Genre is the row being updated, the likeTrack column is being changed from love toedge

After the update is done this is what the Parameter Table will look like

141

Page 146: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Table 51. Updated Parameter Table results

ParmSetName

ParmOne Country SaleYear genreID likeTrack

trackCount

startDate endDate

TName-Genre

1 NULL NULL 4 Edge NULL NULL NULL

RangeSales

1 NULL NULL NULL NULL NULL 2018-01-01

2018-12-31

Now when the same main query is run again the results are based on the new values in theTName-Genre row of the Parameter Table.

Table 52. Updated main query results

trackName GenreId genreName

Edge Of The World 4 Alternative & Punk

The result has just tracks with Edge in it.

142

Page 147: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.34. Volatile TableVolatile Tables are created in Spool Space and do not require any Perm Space.

They are exist for the users session, after that they are automatically deleted.

To assure your INSERTED data is available remember to user the ON COMMIT PRESERVE ROWS.

143

Page 148: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

SQL Example CREATE VOLATILE TABLE

/*

=== Volatile Tables

Volatile tables exist in `Spool Space` not `Perm Space`

If you create table with VOLATILE option, the life of the table will be only for thecurrent session.It will be automatically dropped by Teradata manager once session expires. (Bothdefinition and content)

Options NOT available for VOLATILE Tables:

Permanent JournalsForeign KeyCompression at Column LevelDefault ValuesName of IndexesOrder by

==== Topics

* Collect Stats statement* Column Alias, rename a column* Comments, information or debugging* Create Table* Delete from statement* Insert into statement* Join objects (Table, View, Derived Table) together* Order by, also known as sorting* Table alias, standardize and simplify table/view names* Teradata Specific syntax*/

-- Drop table trackReviewList;

-- Create the VOLATILE tableCREATE VOLATILE TABLE trackReviewList ①  (  trackID integer not null ②  ,focusCategory varchar(25)  ,PRIMARY KEY (trackID) ③  )ON COMMIT PRESERVE ROWS; ④

① CREATE VOLATILE TABLE looks very similar to a normal CREATE TABLE, this command needsto be run by itself

144

Page 149: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

② In this example trackID is unique and is used as the PRIMARY KEY so it must also be NOT NULL

③ In this example trackID is unique and is used as the PRIMARY KEY

④ ON COMMIT PRESERVE ROWS` required to use the INSERTED rows

If you attempt to run the CREATE VOLATILE TABLE with other SQL commands together an errormessage similar to the one below will be displayed.

Results (Error)

ErrorCode: -2147467259[Teradata Database]Info: 0, StatementNumber: 1ErrorMessage: [Teradata Database] [3932] Only an ET or null statement is legal after aDDL Statement.

If the CREATE VOLATILE TABLE is run properly the following message will be displayed.

Results CREATE VOLATILE TABLE

Command(s) completed successfully.

SQL Download link click here

145

Page 150: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

The COLLECT STATS is an optional command but, running it will help in the performance ofqueries using the VOLATILE table.

SQL Example COLLECT STATS

/*

=== Volatile Tables

Volatile tables exist in `Spool Space` not `Perm Space`

If you create table with VOLATILE option, the life of the table will be only for thecurrent session.It will be automatically dropped by Teradata manager once session expires. (Bothdefinition and content)

Options NOT available for VOLATILE Tables:

Permanent JournalsForeign KeyCompression at Column LevelDefault ValuesName of IndexesOrder by

==== Topics

* Collect Stats statement* Column Alias, rename a column* Comments, information or debugging* Create Table* Delete from statement* Insert into statement* Join objects (Table, View, Derived Table) together* Order by, also known as sorting* Table alias, standardize and simplify table/view names* Teradata Specific syntax*/

-- Collect Stats helps performanceCOLLECT STATS COLUMN(trackID) ①ON trackReviewList;

① COLLECT STATS help performance when using this VOLATILE TABLE, in this example thePRIMARY KEY is used for the stats collection.

SQL Download link click here

146

Page 151: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Results COLLECT STATS

Command(s) completed successfully.

Inserting rows into a Volatile Table may seem different for some other types of inserts. By usingthe SELECT command with the values in the same order as the columns, this simplified version canbe used.

This list of TrackID and focusCategory are a selection of tracks we are specifically interested in. Thislist could be limited to just a few tracks or could be expanded to hundreds of tracks.

147

Page 152: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

SQL Example INSERT INTO

/*

=== Volatile Tables

Volatile tables exist in `Spool Space` not `Perm Space`

If you create table with VOLATILE option, the life of the table will be only for thecurrent session.It will be automatically dropped by Teradata manager once session expires. (Bothdefinition and content)

Options NOT available for VOLATILE Tables:

Permanent JournalsForeign KeyCompression at Column LevelDefault ValuesName of IndexesOrder by

==== Topics

* Collect Stats statement* Column Alias, rename a column* Comments, information or debugging* Create Table* Delete from statement* Insert into statement* Join objects (Table, View, Derived Table) together* Order by, also known as sorting* Table alias, standardize and simplify table/view names* Teradata Specific syntax*/

-- Insert rows with data into VOLATILE tableinsert into trackReviewList select 3018, 'Upcoming' ①;insert into trackReviewList select 3037, 'Old Trend';insert into trackReviewList select 3031, 'Old Trand';insert into trackReviewList select 3017, 'Upcoming';insert into trackReviewList select 2949, 'Radio Play';insert into trackReviewList select 2937, 'Old Trend';insert into trackReviewList select 2050, 'Radio Play';insert into trackReviewList select 2959, 'Radio Play';insert into trackReviewList select 2957, 'Upcoming';insert into trackReviewList select 3018, 'Upcoming';insert into trackReviewList select 3018, 'Upcoming';

① The first value of 3018 get inserted into the first column (trackid) of the Volatile Table the

148

Page 153: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

second value of Upcoming gets inserted into the second column (focusCategory) of the VolatileTable

By putting the semicolon (;) at the beginning of lines 36 thru 45 and ending with asemicolon on line 45 this statement becomes a single transaction query. When youare inserting a large number of rows using this method improves performance.

SQL Download link click here

Results INSERT INTO

(9 rows affected)

149

Page 154: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

When using the Volatile Table in a query it is reference just as any other table would be.

SQL Example SELECT Example

/*

=== Volatile Tables

Volatile tables exist in `Spool Space` not `Perm Space`

If you create table with VOLATILE option, the life of the table will be only for thecurrent session.It will be automatically dropped by Teradata manager once session expires. (Bothdefinition and content)

Options NOT available for VOLATILE Tables:

Permanent JournalsForeign KeyCompression at Column LevelDefault ValuesName of IndexesOrder by

==== Topics

* Collect Stats statement* Column Alias, rename a column* Comments, information or debugging* Create Table* Delete from statement* Insert into statement* Join objects (Table, View, Derived Table) together* Order by, also known as sorting* Table alias, standardize and simplify table/view names* Teradata Specific syntax*/

-- Display inserted rowsselect  T.Name as trackName ①  ,G.Name as GenreName  ,RL.trackID  ,RL.focusCategoryFrom trackReviewList RL ②

inner Join DCH_Training.Track T ②on T.trackID = RL.TrackID ③

Inner Join DCH_TRaining.Genre G ②

150

Page 155: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

on G.GenreID = T.GenreID

order by -- Not available in VOLATILE tables ④  trackName DESC;

① Column alias

② Table alias

③ RL is the trackReviewList the Volatile Table

④ Order By will not work with the Volatile Table and it will NOT display an error.

SQL Download link click here

Table 53. Results SELECT Example

trackName GenreName trackID focusCategory

Walk To The Water Rock 2957 Upcoming

The Wanderer Rock 3037 Old Trend

The Three Sunrises Rock 2949 Radio Play

Sunday Bloody Sunday Rock 3018 Upcoming

Love Is Blindness Rock 2937 Old Trend

Lemon Rock 3031 Old Trand

I Feel Good (I Got You) -Sossego

Latin 2050 Radio Play

Hallelujah Here SheComes

Rock 2959 Radio Play

All I Want Is You Rock 3017 Upcoming

After this Teradata session is closed the trackReviewList table is automatically deleted.

If the SELECT query using the trackReviewList is attempted again the following error message willbe displayed.

Results Error Message

ErrorCode: -2147467259[Teradata Database]Info: 0, StatementNumber: 1ErrorMessage: [Teradata Database] [3807] Object 'trackReviewList' does not exist.

Back to [top].

151

Page 156: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

3.35. Copy TableIt is possible to copy a table with all of its data to a new table.

Your account must have Perm Space and special access rights to perform this query.

SQL Example

/*

=== copyTable Quickly copy a table or a query into a table

NOTE: You must have `Perm Space` and special access roles to use the `CREATE TABLE`DDL command.

Because the table created is done automatically the first column of the table isconsidered to be an INDEX column.

==== Topics

* Column Alias, rename a column* Comments, information or debugging* Create Table* Delete from statement* Join objects (Table, View, Derived Table) together* Table alias, standardize and simplify table/view names* Teradata Specific syntax*/

-- Copy the entire `Genre` table WITH all the DATA-- This is a DDL statement and must be run by itselfCREATE TABLE SCHUSTERJDCHBULL.copy_Genre AS ①(  SELECT ②  *  FROM DCH_Training.Genre G ③)WITH DATA; ④

① CREATE TABLE command with AS keyword, the new table will be named copy_Genre

② This is the sub-query referencing the original table to be copied

③ Table alias

④ WITH DATA will copy all the data from the original table (Genre) into the new table(copy_Genre)

SQL Download link click here

When the CREATE TABLE command is successful the following message will be displayed

152

Page 157: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Results CREATE TABLE SELECT

Command(s) completed successfully.

To verify that the table was created you can perform a SELECT against it.

SQL Example SELECT

/*

=== copyTable Quickly copy a table or a query into a table

NOTE: You must have `Perm Space` and special access roles to use the `CREATE TABLE`DDL command.

Because the table created is done automatically the first column of the table isconsidered to be an INDEX column.

==== Topics

* Column Alias, rename a column* Comments, information or debugging* Create Table* Delete from statement* Join objects (Table, View, Derived Table) together* Table alias, standardize and simplify table/view names* Teradata Specific syntax*/

-- Lets see what is in the `copy_Genre` tableSelect  * ①from SCHUSTERJDCHBULL.copy_Genre;②

① The asterisk (*) selects all columns of the table, good practice is to avoid using the *SELECT *, forthis example it is ok

② The new table copy_Genre was created in the users area SCHUSTERDCHBULL

SQL Download link click here

Table 54. Results CREATE TABLE SELECT

GenreId Name

11 Bossa Nova

14 R&B/Soul

6 Blues

24 Classical

153

Page 158: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

GenreId Name

12 Easy Listening

13 Heavy Metal

16 World

17 Hip Hop/Rap

15 Electronica/Dance

22 Comedy

7 Latin

4 Alternative & Punk

30 Dub Step

19 TV Shows

25 Opera

2 Jazz

23 Alternative

8 Reggae

9 Pop

31 Trance

3 Metal

32 Club

5 Rock And Roll

10 Soundtrack

1 Rock

21 Drama

18 Science Fiction

20 Sci Fi & Fantasy

Back to [top].

154

Page 159: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

It is possible to create a query that the results would be inserted into a new table.

Your account must have Perm Space and special access rights to perform this query.

SQL Example Query

/*

=== copyTable Quickly copy a table or a query into a table

NOTE: You must have `Perm Space` and special access roles to use the `CREATE TABLE`DDL command.

Because the table created is done automatically the first column of the table isconsidered to be an INDEX column.

==== Topics

* Column Alias, rename a column* Comments, information or debugging* Create Table* Delete from statement* Join objects (Table, View, Derived Table) together* Table alias, standardize and simplify table/view names* Teradata Specific syntax*/

-- Create a table that is a copy of Query WITH all the DATA from the results-- This is a DDL statement and must be run by itselfCREATE TABLE SCHUSTERJDCHBULL.copy_reggaeTrack as ①(  Select ②  T.TrackID  ,T.Name as trackName ③  ,AL.AlbumTitle  from DCH_Training.Track T ④

  INNER JOIN DCH_Training.Album AL ④  on AL.AlbumID = T.AlbumID

  where T.GenreID = 8)WITH DATA; ⑤

① CREATE TABLE command with AS keyword, the new table will be named copy_ReggaeTrack

② This SELECT is the derived table (Sub-Query) used to generate the table

③ Column Alias

④ Table alias

155

Page 160: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

⑤ WITH DATA will copy all the data from the SELECT into the new table (copy_ReggaeTrack)

SQL Download link click here

When the CREATE TABLE command is successful the following message will be displayed

Results CREATE TABLE

Command(s) completed successfully.

To verify that the table was created you can perform a SELECT against it.

SQL Example Query

/*

=== copyTable Quickly copy a table or a query into a table

NOTE: You must have `Perm Space` and special access roles to use the `CREATE TABLE`DDL command.

Because the table created is done automatically the first column of the table isconsidered to be an INDEX column.

==== Topics

* Column Alias, rename a column* Comments, information or debugging* Create Table* Delete from statement* Join objects (Table, View, Derived Table) together* Table alias, standardize and simplify table/view names* Teradata Specific syntax*/

-- Lets see what is in the `copy_Genre` tableSelect  * ①from SCHUSTERJDCHBULL.copy_Genre;②

① The asterisk (*) selects all columns of the table, good practice is to avoid using the *SELECT *, forthis example it is ok

② The new table copy_ReggaeTrack was created in the users area SCHUSTERDCHBULL

SQL Download link click here

Table 55. Results CREATE TABLE Query

156

Page 161: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

TrackId trackName AlbumTitle

310 Sábado A Noite Cidade Negra - Hits

3046 Higher Ground UB40 The Best Of - Volume Two[UK]

293 Onde Você Mora? Acústico MTV [Live]

2228 Equal Rights Downpresser Man Greatest Hits

2227 Crystal Ball Greatest Hits

3040 I Would Do For You UB40 The Best Of - Volume Two[UK]

3043 Kingston Town UB40 The Best Of - Volume Two[UK]

283 A Sombra Da Maldade Acústico MTV [Live]

303 Falar A Verdade Cidade Negra - Hits

306 Realidade Virtual Cidade Negra - Hits

299 Onde Você Mora? Cidade Negra - Hits

286 Firmamento Acústico MTV [Live]

2224 Mystic Man Greatest Hits

302 A Estrada Cidade Negra - Hits

3048 C’est La Vie UB40 The Best Of - Volume Two[UK]

285 Soldado Da Paz Acústico MTV [Live]

2221 Buk-In-Hamm Palace Greatest Hits

2219 I’m The Toughest Greatest Hits

2223 Wanted Dread And Alive Greatest Hits

3038 Breakfast In Bed UB40 The Best Of - Volume Two[UK]

300 O Erê Cidade Negra - Hits

2218 Jah Seh No Greatest Hits

304 Firmamento Cidade Negra - Hits

291 Berlim Acústico MTV [Live]

292 Já Foi Acústico MTV [Live]

296 Realidade Virtual Acústico MTV [Live]

307 Doutor Cidade Negra - Hits

3044 Wear You To The Ball UB40 The Best Of - Volume Two[UK]

2216 Johnny B. Goode Greatest Hits

3051 Until My Dying Day UB40 The Best Of - Volume Two[UK]

295 Conciliação Acústico MTV [Live]

157

Page 162: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

TrackId trackName AlbumTitle

2226 Pick Myself Up Greatest Hits

3039 Where Did I Go Wrong UB40 The Best Of - Volume Two[UK]

301 A Sombra Da Maldade Cidade Negra - Hits

289 Podes Crer Acústico MTV [Live]

312 Eu Também Quero Beijar Cidade Negra - Hits

2222 Bush Doctor Greatest Hits

294 Pensamento Acústico MTV [Live]

3042 Here I Am (Come And Take Me) UB40 The Best Of - Volume Two[UK]

309 Downtown Cidade Negra - Hits

284 Johnny B. Goode Acústico MTV [Live]

305 Pensamento Cidade Negra - Hits

282 Girassol Acústico MTV [Live]

308 Na Frente Da TV Cidade Negra - Hits

3049 Reggae Music UB40 The Best Of - Volume Two[UK]

2225 Coming In Hot Greatest Hits

3050 Superstition UB40 The Best Of - Volume Two[UK]

2217 Don’t Look Back Greatest Hits

3045 (I Can’t Help) Falling In LoveWith You

UB40 The Best Of - Volume Two[UK]

311 A Cor Do Sol Cidade Negra - Hits

290 A Estrada Acústico MTV [Live]

298 A Cor Do Sol Acústico MTV [Live]

287 Extra Acústico MTV [Live]

3047 Bring Me Your Cup UB40 The Best Of - Volume Two[UK]

288 O Erê Acústico MTV [Live]

3041 Homely Girl UB40 The Best Of - Volume Two[UK]

2220 Nothing But Love Greatest Hits

297 Mensagem Acústico MTV [Live]

158

Page 163: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

4. Python TeradataPython is a programming language that is used for doing data analytics. Python can be used withTeradata and the Teradata ODBC driver. Teradata SQL is used in the Python programs.

The Teradata interface to Python is done by the Teradata Python module and the Teradata 32 BitODBC Driver.

The Teradata 32 Bit ODBC driver must be installed for the Teradata Python Moduleto work. However, you do NOT need to have a Data Source Name (DSN) configuredto use the Teradata Python Module.

Reference: Teradata Python link is here

An edited version by the author of the Teradata Python Module documentation can be viewed here

This Python section will use Microsoft Powershell to perform most of the commands.

This Python section will use Microsoft Visual Studio Code editor for the Python code and testing.Any text editor can be used to code Python programs.

4.1. Verifying PythonPython must be installed on your system to use the Teradata Python module.

This learning guide do NOT include how to install Python as this varies between systems.

The commands to verify python and pip versions are

python --versionpip --version

159

Page 164: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Figure 37. Verify Python

Verify Python

1. python --version will return the version of python. The Teradata Python Module has beencertified to work with Python 3.4+ / 2.7+, Windows/Linux/Mac, 32/64 bit. NOTE: Version 3.7 ofpython is being used for this learning guide.

2. pip --version will return the version of the Python Install Program (PIP). The Teradata Pythonmodule can be installed with version 10.0 and higher.

4.2. Install Teradata Python ModuleTo install the Teradata Python module you will use Powershell and the `PIP`command.

The command to install Teradata Python module is

pip install teradata

160

Page 165: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Figure 38. Install Python

Install Python

1. pip install teradata uses the Python Install Program (PIP) to locate the Teradata repository andperform the install.

2. Looks like the author needs to update the PIP. NOTE: The install worked with a Version 10.0 ofPIP and has been verified to work with Version 19.0 of PIP.

At some locations you may not be able run the PIP command. You will need torequest assistance from technical support to complete the installation.

4.3. Hello WorldHello World is a program typically used to just test for basic connectivity with as little code aspossible.

161

Page 166: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Python helloWorld

# --- helloWorld-drbc.py a Teradata Python test# SQL As a Second Language (SASL) Learning Guide# DRBC.state.mi.us is the MDHHS Testing server

# --- imports the Teradata Python Module for use in the program.import teradata

# -- initializes the “UdaExec” framework# name and version of our application during initialization so that# we can get feedback about our application in DBQL and Teradata Viewpoint## `logConsole=False` not to log to the console, so that our print statement iseasier to read.udaExec = teradata.UdaExec (appName="HelloWorld-drbc", version="1.0",  logConsole=False)

# --- Creates a connection to a Teradata system named `drbc.state.mi.us` using the# Teradata 32 Bit ODBC driver. No DSN required.session = udaExec.connect(method="odbc", system="drbc.state.mi.us",  username="schusterjdchbull", password="**********")

print("Teradata / Python test (drbc) - SASL Learning Guide")

# --- The Teradata SQL command `SELECT GetQueryBand()` will confirm the# Python connetion without any actual database access, simple# This should return one row of resultsfor row in session.execute("SELECT GetQueryBand()"):  print(row)

Results

The results from this Python example will include the Row 1: with the QueryBand in it.

Windows PowerShellCopyright (C) 2016 Microsoft Corporation. All rights reserved.

PS Z:\Dropbox\PWC\SASL> & C:/Python372/python.exez:/Dropbox/PWC/SASL/python/helloWorld-drbc.py ①Teradata / Python test (drbc) - SASL Learning Guide ②Row 1: [=S> ApplicationName=HelloWorld-drbc;Version=1.0;JobID=20190207130653-9;ClientUser=jschust2;Production=False;udaAppLogFile=Z:\Dropbox\PWC\SASL\logs\HelloWorld-drbc.20190207130653-9.log;gitRevision=e439b53;gitDirty=True;UtilityName=PyTd;UtilityVersion=15.10.0.21;]③PS Z:\Dropbox\PWC\SASL>

162

Page 167: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

① This is the Powershell command to run the helloWorld program, your command will lookdifferent than this.

② This is the confidence message from line 24 of the helloWorld program

③ This is the result from the select query on line 29 of the helloWorld program

4.4. Get CubeWhen using Python it is good practice to have the Teradata server do most of the work to preparethe data for Python analysis. A good example of this is the Teradata OLAP Cube function. Reference:Cube.

The following Python example uses the cube query to generate a large summary result.

Python getCube

# --- getCube.py a Teradata Python real wrold example# SQL As a Second Language (SASL) Learning Guide# DRBC.state.mi.us is the MDHHS Testing server

# --- imports the Teradata Python Module for use in the program.import teradata

# -- initializes the “UdaExec” framework# name and version of our application during initialization so that# we can get feedback about our application in DBQL and Teradata Viewpoint## `logConsole=False` not to log to the console, so that our print statement iseasier to read.udaExec = teradata.UdaExec (appName="getCube", version="1.0",  logConsole=False)

# --- Creates a connection to a Teradata system named `drbc.state.mi.us` using the# Teradata 32 Bit ODBC driver. No DSN required.session = udaExec.connect(method="odbc", system="drbc.state.mi.us",  username="schusterjdchbull", password="*******")

print("Teradata / Python Real World (drbc) - SASL Learning Guide")

# --- Teradata SQL to generate a OLAP cube in the file 0018b-cube.sqlsql = """Select  I.BillingCountry as country ①  ,Extract(Year from I.InvoiceDate) as saleYear ① ②  ,G.Name as genreName  ,count(IL.TrackID) as trackCount ① ③  ,sum(I.Total) as saleTotal ① ③

163

Page 168: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

  ,CASE ④  WHEN (country is null) and (saleYear is null) and (genreName is null) then'Grand' ⑤  WHEN (country is null) and (saleYear is null) then 'Genre'  WHEN (country is null) and (genreName is null) then 'Year'  WHEN (saleYear is null) and (genreName is null) then 'Country'  WHEN(country is null) then 'YearGenre'  WHEN (saleYear is null) then 'CountryGenre'  WHEN (genreName is null) then 'CountryYear'  ELSE 'CountryYearGenre'  END as sliceTypefrom DCH_Training.Invoice I ⑥

Inner Join DCH_Training.InvoiceLine IL ⑥on IL.InvoiceId = I.InvoiceId

Inner Join DCH_Training.Track T ⑥on T.TrackID = IL.TrackID

Inner Join DCH_Training.Genre G ⑥on G.GenreID = T.GenreID

Group by Cube ⑦  (  country  ,saleYear  ,genreName  )

"""

# --- The Teradata SQL command `0018b-cube.sql` will run the# SQL and perform the complex cube functions.# After Teradata has finished the results will then be# sent back to the Python program.for row in session.execute(sql):  print(row)

Python getCube

1. Column Alias

2. Date function EXTRACT Year

3. Aggregate function SUM, COUNT

4. Case statement, this is the if clause for SQL

5. Each SliceType is determine by which dimension columns is null

6. Table alias

164

Page 169: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

7. OLAP Function GROUP BY Cube, NOTE: the () around the dimension columns

The results from the Teradata cube query are sent back in a Python List format.

Results

PS Z:\Dropbox\PWC\SASL> & C:/Python372/python.exez:/Dropbox/PWC/SASL/python/getCube.pyTeradata / Python Real World (drbc) - SASL Learning GuideRow 1: [Brazil, 2014, Blues, 5, 29.70, CountryYearGenre]Row 2: [France, 2015, Soundtrack, 2, 27.72, CountryYearGenre]Row 3: [Czech Republic, 2014, Alternative & Punk, 2, 17.82, CountryYearGenre]Row 4: [Portugal, 2017, TV Shows, 1, 10.91, CountryYearGenre]Row 5: [Canada, 2015, Drama, 2, 13.89, CountryYearGenre]Row 6: [Finland, 2014, Latin, 5, 44.55, CountryYearGenre]Row 7: [France, 2015, Latin, 5, 69.30, CountryYearGenre]Row 8: [Canada, None, TV Shows, 1, 3.98, CountryGenre]Row 823: [Finland, None, Reggae, 1, 13.86, CountryGenre]Row 824: [Germany, None, Easy Listening, 2, 27.72, CountryGenre]Row 825: [Germany, 2015, Alternative & Punk, 1, 13.86, CountryYearGenre]Row 826: [Hungary, None, Drama, 2, 43.72, CountryGenre]Row 827: [France, None, Bossa Nova, 1, 13.86, CountryGenre]Row 828: [Denmark, 2017, None, 16, 198.00, CountryYear]

Only a few rows of the Python result are displayed. There are 828 rows in theresult.

Back to [top].

165

Page 170: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

5. REST ServicesWhile REST stands for Representational State Transfer, which is an architectural style fornetworked hypermedia applications, it is primarily used to build Web services that are lightweight,maintainable, and scalable.

REST has become one of the most important technologies for web applications and ApplicationProgrammatic Interfaces (API). The standards for using REST are very well defined anddocumented.

To use REST services with a Teradata database there needs to be a Teradata REST Server to handlethe request and responses.

The example shown in this document were done using the Phoenix LearningLabs Teradata research servers.

Figure 39. Example REST Server

166

Page 171: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

5.1. REST RequestThe REST Request is formatted and prepared by an Web Application or API.

The Teradata SQL query is typically formatted in a JSON format and sent as a REST Request to theTeradata REST server over HTTPS connection.

The Teradata REST server translates the REST Request into a standard Teradata query and sends itto the Teradata database server to be run.

Example REST Request

/*

=== REST Request

Example of a SQL statement being sent to the REST server.

NOTE: This example is using the Phoenix Learning Labs Teradata research servers.

==== Topics

* Aggregates (Count, Sum, Min, Max, Avg, etc)* Column Alias, rename a column* Comments, information or debugging* Group by, required for non-aggregate columns* Join objects (Table, View, Derived Table) together* REST Services*/

curl -X POST \ ①  http://10.1.10.183:1080/tdrest/systems/TD15/queries \ ②  -H 'Accept: application/vnd.com.teradata.rest-v1.0+json' \  -H 'Authorization: Basic anNjaHVzdDI6VGhlcmluZzY2NiE=' \ ③  -H 'Content-Type: application/json' \  -H 'Postman-Token: 9abb296f-a600-484d-8e37-ff1d0977377d' \  -H 'cache-control: no-cache' \  -d '{  "query": "SELECT G.Name as genreName,count(IL.InvoiceLineID) As saleCount fromChinook.InvoiceLine IL inner join Chinook.Track T on T.trackID = IL.TrackID inner joinChinook.Genre G on G.GenreID = T.GenreID group by genreName;", ④  "format": "object"}'

① CURL is a command to run a REST request

② Address of the Teradata REST server

③ Encoded User ID and Password

④ Teradata SQL query

167

Page 172: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

REST Request Download link click here

5.2. REST ResponseThe result set (Response) of the Teradata query are sent to the Teradata REST server whichtranslates then into a JSON format and send them back to the application or API.

Example REST Response

{  "queueDuration": 3,  "queryDuration": 204,  "results": [  {  "resultSet": true,  "data": [  {  "genreName": "Easy Listening",  "saleCount": 10  },  {  "genreName": "Comedy",  "saleCount": 9  },  {  "genreName": "Jazz",  "saleCount": 80  },  {  "genreName": "Rock",  "saleCount": 836  },  {  "genreName": "Drama",  "saleCount": 29  },  {  "genreName": "Latin",  "saleCount": 386  },  {  "genreName": "Heavy Metal",  "saleCount": 12  },  {  "genreName": "R&B/Soul",  "saleCount": 41  },  {  "genreName": "Rock And Roll",

168

Page 173: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

  "saleCount": 6  },  {  "genreName": "Reggae",  "saleCount": 30  },  {  "genreName": "World",  "saleCount": 13  },  {  "genreName": "Alternative",  "saleCount": 14  },  {  "genreName": "Classical",  "saleCount": 41  },  {  "genreName": "Pop",  "saleCount": 28  },  {  "genreName": "Metal",  "saleCount": 267  },  {  "genreName": "Hip Hop/Rap",  "saleCount": 18  },  {  "genreName": "Science Fiction",  "saleCount": 6  },  {  "genreName": "Alternative & Punk",  "saleCount": 244  },  {  "genreName": "Sci Fi & Fantasy",  "saleCount": 20  },  {  "genreName": "TV Shows",  "saleCount": 47  },  {  "genreName": "Electronica/Dance",  "saleCount": 12  },  {

169

Page 174: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

  "genreName": "Blues",  "saleCount": 61  },  {  "genreName": "Soundtrack",  "saleCount": 20  },  {  "genreName": "Bossa Nova",  "saleCount": 15  }  ],  "rowCount": 24,  "rowLimitExceeded": false  }  ]}

170

Page 175: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

6. Power-BIPower-BI is a data analytics, ETL, data visualization and dashboard tool. It is not a general SQLaquery tool like SQL-Assistant, SQL Studio or BI-Query.

Power-BI is a desktop tool that allows for the use of Teradata databases to create models that can beused to create visual charts and business graphs.

Power-BI also has an optional services component that allows for the publication of the reportsand charts produced by the Power-BI desktop.

The Power-BI Services component require a special Power-BI server and software.

It is still possible to share the work you do with Power-BI with others who also have a copy ofPower-BI desktop.

It is also possible to produce a copy of the Power-BI charts in a PDF format with some limitations.

If you are going to use Power-BI for a large number of projects it is suggested that you create ablank template with the tables and relationships already defined, basically a starter model. Thenwhen you are starting a new project make a copy of this Starter Template and use it for yourproject.

To run Power-BI the system needs to have .NET 4.2 runtime or higher and theTeradata .NET provider 16.10 or higher.

6.1. Get DataTo start the connection the Teradata server and do the Direct Query links to the database objectsyou need to do your work.

To get started click on the Get Data Icon in the menu bar.

If you have Power-BI models you have done already they will appear in the listalong with

171

Page 176: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Figure 40. Get Data Link on menu bar

Then start to enter Teradata until the Teradata database connection appears, then click on theConnect button.

172

Page 177: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Figure 41. Get Data Teradata server

Next step is to click on the Get Data Icon from the main menu.

6.2. Server NameThis next step is Very Important. Connect to the proper Teradata Server using the full URL for thatserver.

Change the Data Connectivity Mode to Direct Query, do *NOT* use Import, then click on the OKbutton.

173

Page 178: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Figure 42. Server Name and Direct Query

6.3. LoginSelect the Database tab and enter in your Teradata credentials for that server, then click on theConnect button.

Figure 43. Teradata login

6.4. NavigationNavigation consist of going to the database(s) on the Teradata Server and getting the objects youwant to use in your Model. In our example we will use the DCH_Training database, scroll down to itand click on the right pointing arrow.

174

Page 179: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Figure 44. Database navigation

6.5. Select ObjectsAll of the database objects in the selected database will be displayed.

Do not be tempted to click on everything, Less is More Start with a few objects,you can always go back and add more.

In this example only three objects will be selected, then click on the Load button.

• Albums

• Tracks

• Genre

As you select objects to pane to the right will display a sample of the contents ofthat object. This makes it easier to verify you have selected the correct object.

175

Page 180: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Figure 45. Select objects from database

Power-BI will then go through a process where information about the objects are transferred fromthe Teradata Server to the Power-BI model. The data is NOT transferred just the metadata about thedatabase objects is transferred.

Figure 46. Creating (Direct Query) connections

176

Page 181: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

6.6. Edit queriesAt this point you might think you can use the data to start doing a data visualization but, you have afew housekeeping tasks your Should do.

The database objects are listed in the pane to the right of the page, you can open the tables up byclicking on the right arrow next to the name of the object.

Edit (Power-BI) queries

This Edit Queries is not how you create queries to use in Power-BI. This Edit Queries is to addediting steps to the data of the objects you just added to the Power-BI Model. Think of Edit Queriesas a way of cleaning up or enhancing the raw data from the tables you selected. More or less theEdit Queries is like an Extraction, Loading and Transformation (ETL) utility inside of Power-BI.

You don’t have to do any Edit Queries if the data you are referencing is ready foruse in Power-BI. The author has found that most tables need some form ofcleaning and/or transformation to make them easier to use in Power-BI.

177

Page 182: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Figure 47. Data Type mistake

Power-BI thinks the column AlbumID is a number column , see the 1 2 3 in the column header? Thisis incorrect and while it will work it would be better to define the data type for AlbumID to be astring.

By right-clicking on the column heading you can change the data type for this column.

178

Page 183: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Figure 48. Change Data Type

After you have done this change the column heading now shows A B C and a new step has beenadded to the Applied Steps for the Album table.

179

Page 184: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

Figure 49. Changed Data Type

There is more to come for the Power-BI getting started with Teradata. The authoris working on additional content for the Learning Guide.

180

Page 185: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

7. TipsThis tips can be considered suggestions to make developing SQL a little bit easier.

7.1. Aggregate FunctionsThese functions are used to compress or limit the number of rows into a single row.

• Count(?) Counts the number of rows, duplicates included in the count.

• Count Distinct(?) Count the number of rows, duplicates only counted once.

• Sum(?) Sums the values in the column, the column must be a numeric column.

7.2. Column Alias• Column alias help to give meaningful, non conflicting names.

• Good practice, alias column names use lowerUpper naming to identify them as alias (ie:albumCount, salesDollars, genreAverage)

• Good practice, try to use the same column alias across all queries.

7.3. Dates• Default Teradata date format is yyyy-mm-dd

• Convert a string into a date with DATE function (DATE '2018-01-01')

• Extract parts of a date with the EXTRACT function (EXTRACT MONTH I.InvoiceDate)

7.4. DDL queries• The CREATE TABLE, DELETE TABLE, CRATE VIEW, DELETE VIEW DDL statements must be

executed by themselves

• Most DDL queries require that the user account have PERM SPACE assigned to it along with specialaccess rights.

7.5. Derived Tables (Sub-Queries)• Start with a regular query until you get the results you need.

• Enclose the regular query in (…) and assign a table alias name.

• Good practice is to start a derived table with a ( on a line by itself.

• Good practice is to end a derived table with a ( as XX on a line by itself

• Good practice is to indent the derived table within the ( and ) as XX

181

Page 186: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

7.6. Formatting / Conversion• Cast(x,y) can be used to reduce number of digits of precision.

X=Number of digits on both sides of the decimal point totaled (ie: 999.99 X=5)

Y=Number of digits of precision, number og digits to the right of the decimal point. (ie: 999.99 Y=2)

7.7. Join• The Left table is defined by the first Select in the query.

• The Right table is defined by the object in the Join clause.

• The Inner Join returns results where there is a matching column in both Left and Right tables.

• The Outer Join returns ALL results from one table and any matching results from the othertable.

• The ALL table is determined by the direction of the Outer join (Left Outer Join, Right OuterJoin).

7.8. Naming practice• Good practice, System Generated Primary Index column name include a ID suffix (AlbumID,

TrackID).

• Good practice, Primary Key and Foreign Key join columns should use the same name.

• Short descriptive column names are better than abbreviations.

7.9. OLAP Functions• CSUM uses two arguments. First argument is the column to be summed, the second argument is

the column to sum by.

• Rank only has one argument. This argument is the field to be ranked. Duplicate values in thisargument will share a ranking number. Rank automatically performs an order by.

7.10. Order By• Can use actual column name (T.Milliseconds, I.InvoiceDate), column alias name (trackCount,

genreName), or ordinal position (1,2,3,4).

• Good practice is to avoid using ordinal position because as queries change the number andorder of select columns, the results can become invalid.

182

Page 187: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

7.11. Parameter fields (Prompts)• Parameter fields start with a ?.

• Avoid using (-, _) characters in the name, results can be incorrect

• Use a two digit prefix (01, 02,03) to assure prompts are in the order required

• You can NOT enter a list a values to a parameter field (ie: 1,34,78,111)

7.12. Select columns• Use single quote ' to denote text.

• Use double-quotes " for renaming objects.

• Indent columns selected.

• Limit one column per row.

• Avoid using the (*) to select all columns of a database object, column names and orders maychange over time and errors will occur.

• Put commas at the beginning of the column name, not at the end, starting on the 2nd column.

Not recommended

Select  T.Name as trackName,  I.InvoiceDate,  AL.Name as albumName,  count(T.TackID) as trackCount,

Recommended

Select  T.Name as trackName  ,I.InvoiceDate  ,AL.Name as albumName  ,count(T.TackID) as trackCount

7.13. Table Alias• Table alias shorten the typing needed to complete the query, 1-3 character alias recommended.

• Use the same table alias across all queries.

• Good practice is to have table alias used everywhere in the query, including Select, From, Join,Where, Group By and Order By.

• Good Practice is to have table alias be uppercase (IE: I, IL, T, G)

183

Page 188: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

7.14. Teradata Specific• Teradata will look for any Primary Index specified in the DDL.

• If a Primary Index is not specified, it will then look for Primary Key constraint in DDL for makingit Primary Index.

7.15. Union• UNION allows joining of multiple queries

• Each queries must have same number and data type of columns.

• First query in union determine sizes and names of columns.

• Start small and build on to the Union query.

7.16. Where• Good practice, put and where clauses on separate lines

• Good practice, put or where clause on single line

• Use (..) to help clarify logical groupings

184

Page 189: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

8. Contact InformationAuthor contact Information

Email: [email protected]

Phone: 517-927-7400

Please provide any feedback, corrections or suggestions to the author. The folksproviding the most amount of feedback will win prizes.

The author admits to not being able to spell. He attributes this to skipping Englishclasses to get more computer time.

185

Page 190: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

9. ReferenceThis reference material and links may change over time.

If you get a broken link use your GoogleFoo to locate the material.

9.1. Related LinksDatabase 5 Pro SQL Tool: https://fishcodelib.com/database.htm

Database 5 Pro Ver 26.7 download: click here

DBeaver SQL Tool: https://dbeaver.io/

Stack Overflow (Teradata Forum): https://stackoverflow.com/questions/tagged/teradata

9.2. Teradata linksDocumentation: https://docs.teradata.com/landing-page/

Forum: https://community.teradata.com/

SQL Assistant: https://bit.ly/2LYpXxB

SQL Introduction: https://bit.ly/2Fhxp5C

Teradata Studio: http://downloads.teradata.com/download/tools/teradata-studio

Teradata Tools and Utilities (TTU): https://downloads.teradata.com/download/tools/teradata-tools-and-utilities-windows-installation-package

Teradata Tools and Utilities (TTU) Ver 16.10 download link: click here

9.3. Chinook database creationThe Teradata script used to create the Chinook database is available at this link.

9.4. Column TypeColumnType reference table. Reference: http://developer.teradata.com/doc/connectivity/tdnetdp/14.00/webhelp/DataTypeMappings.html

Table 56. ColumnType

ColumnType Abbrev ColumnType Description

A1 ARRAY 

AN MULTI-DIMENSIONAL ARRAY

AT TIME 

186

Page 191: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

ColumnType Abbrev ColumnType Description

BF BYTE

BO BLOB 

BV VARBYTE

CF CHARACTER 

CO CLOB

CV VARCHAR 

D DECIMAL

DA DATE 

DH INTERVAL DAY TO HOUR

DM INTERVAL DAY TO MINUTE 

DS INTERVAL DAY TO SECOND

DY INTERVAL DAY 

F FLOAT

HM INTERVAL HOUR TO MINUTE 

HS INTERVAL HOUR TO SECOND

HR INTERVAL HOUR 

I INTEGER

I1 BYTEINT 

I2 SMALLINT

I8 BIGINT 

JN JSON

MI INTERVAL MINUTE 

MO INTERVAL MONTH

MS INTERVAL MINUTE TO SECOND 

N NUMBER

PD PERIOD(DATE) 

PM PERIOD(TIMESTAMP WITH TIME ZONE)

PS PERIOD(TIMESTAMP) 

PT PERIOD(TIME)

PZ PERIOD(TIME WITH TIME ZONE) 

SC INTERVAL SECOND

SZ TIMESTAMP WITH TIME ZONE 

TS TIMESTAMP

TZ TIME WITH TIME ZONE 

UT UDT Type

XM XML 

187

Page 192: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

ColumnType Abbrev ColumnType Description

YM INTERVAL YEAR TO MONTH

YR INTERVAL YEAR 

++ TD_ANYTYP

188

Page 193: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

10. Document HistoryTable 57. Document History

Date Version Author Description

04/02/2019 V2.2c JHRS Started Power-BI

03/27/2019 V2.2b JHRS Added System_Calendar question resolved clickme on new page Added 2 versions based on SQLdirectory

03/08/2019 v2.2a JHRS Answer MM/YYYY question, REST Services

02/19/2018 V2.1z JHRS Answered subquery filter question Move [top]reference to questions list

02/15/2019 V2.1y JHRS Answered Numbers question

02/08/2019 V2.1x JHRS Added ADOC info in Documentation section

02/08/2019 V2.1w JHRS Security issue resolved

02/07/2019 V2.1w JHRS Started the python/teradata with 0018b-cube.sqlas example

02/06/2019 V2.1v JHRS Replacement for Help database, add database

01/30/2019 V2.1u JHRS Volatile tables, Copy Table, Copy Query

01/28/2019 V2.1t JHRS Editing for PDF

01/17/2019 V2.1s JHRS Parameter Fields, Parameter table

01/16/2019 V2.1r JHRS Added cube

01/16/2018 V2.1q JHRS added DCH_Training. for queries

01/14/2019 V2.1p JHRS OLAP rollup, Considerations

01/11/2019 V2.1n JHRS Added view updates, dateFunctions, SQL Toolinfo title 'Learning Guide'

01/10/2019 V2.1M JHRS Moved Tips from SQL queries to make themsmaller and avoid sync issues, fixed joindefinitions updated derived query B

01/09/2019 v2.1k JHRS Added View and join types, plaques

01/08/2018 V2.1j JHRS Updated Chinook introduction

01/03/2019 V2.1h JHRS Added derived Table for Filters Added diagramsfor derived tables

01/02/2019 V2.1g JHRS Updated derived query for collections

12/28/2018 V2.1f JHRS Added derivedQuery from archived

12/27/2018 V2.1e JHRS Added joinQuery set from archive

12/21/2018 V2.1d JHRS Added vsCode snippet for quick query insertadded Reference section

12/20/2018 V2.1c JHRS Attempting standard document template

12/17/2018 V2.1b JHRS Initial version

189

Page 194: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

10.1. Documentation MaintenanceThis Learning Guide was created and maintained using the ASCIIDoctor mark-up syntax.

ASCIIDoctor is a Ruby based program to translate simple text into well formatted and crossreferenced HTML pages for a web site and PDF files for distribution.

ASCIIDoctor is similar to Markdown but with many of the restrictions of Markdown elminated.

ASCIIDoctor Reference is at this link.

If you interested in the ASCIIDoctor file that was used to generate this Learning Guide you candownload it at this link.

ASCIIDoctor allows the author to focus on content and worry less about formatting and crossreferences.

By using any text editor, like Microsoft Visual Studio Code, it is possible to produce quality andaccurate documents in much less time than traditional word processors.

The author has created a set of Visual Studio Code Snippets that allow for even quicker documentgeneration. A copy of those ASCIIDoctor snippets are available at this link.

The author has a YouTube video showing how to get started with ASCIIDoctor which is available atthis link

For those who do not have access to YouTube the video can be viewed the the following Link -Getting Starter ASCIIDoctor

11. Format fillerPlease excuse this area, it is being used to make the Page numbering appear correctly in the PDFversion of this document.

11.1. Format Filler

11.2. Format Filler

11.3. Format Filler

11.4. Format Filler

11.5. Format Filler

190

Page 195: SQL as a Second Language · 2019-07-15 · • Teradata SQL Assistant - Included in the Teradata Tools and Utilities installation package • Teradata Studio - Available as a separate

11.6. Format Filler

11.7. Format Filler

191