0% found this document useful (0 votes)
17 views41 pages

Teradata Vantage SQL Basics

Uploaded by

Justin Wang
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
17 views41 pages

Teradata Vantage SQL Basics

Uploaded by

Justin Wang
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 41

After successfully completing this course, you will be able to:

 Work with Teradata Studio Express for submitting queries to the Teradata Database
 Write basic SELECT statements using the FROM, WHERE, and ORDER BY query clauses
 Apply SQL predicates such as IN, BETWEEN, and LIKE for data retrieval
 Add multiple search conditions using the logical operators NOT, AND and OR
 Understand Teradata character, numeric, and datetime data types
 Convert data from one type to another, both explicitly and implicitly
 Apply basic character, numeric, and datetime functions such as SUBSTRING, STRPOS, ROUND,
FLOOR, EXTRACT and ADD_MONTHS
 Describe what NULLs are and how to incorporate NULL syntax into queries correctly.
 Extract important information from an Explain plan and understand how it’s influenced by statistics
 Write SELECT statements using subqueries, inner and outer joins
 Write SELECT statements using the EXISTS predicate
 Write queries to produce totals and subtotals in reports using the GROUP BY and HAVING query
clauses and aggregation operators such as COUNT, SUM, and MAX
 Write nested SELECT statements using Derived Tables and Common Table Expressions
 Combine multiple SELECTs using the set operations UNION, EXCEPT, and INTERSECT
 Write SELECT statements using the EXISTS predicate
 Display values based upon conditions using the CASE expression and the NULLIF and COALESCE
functions
 Return a sample as a number or a percentage of rows using the SAMPLE clause
 Return a number or a percentage of rows using the TOP clause

Audiences

 Power Users
 Application Developers
 Data Analysts
 Database Administrators
 Architects/Designers
One client tool to manage Teradata Vantage

Modern user interface supported on Linux, Mac, and Windows

Create, modify, and format SQL statements with visual builder, pre-built templates, and autocomplete

Quickly load or export the data to and from tables

Export result sets to Excel, XML, or text files

Manage all database objects with visual navigations

Copy and compare database objects

Teradata Studio is a client-based graphical interface used to perform Teradata database administration, external
data access, and query tasks.

Teradata Studio is built on the Eclipse Rich Client Platform (RCP) which takes advantage of the RCP framework for
building and deploying native GUI applications. It extends the Eclipse Data Tools Platform (DTP) to provide
enhancements for accessing objects and data stored in Teradata-supported databases. Teradata Plug-in for Eclipse,
in addition to the features provided in Teradata Studio, plugs into your existing Eclipse IDE and provides wizards to
help users create Java database objects such as Java Stored Procedures and Java User Defined Functions. Teradata
Plug-in for Eclipse is a tool for developers creating Java applications and database objects.

Operating systems that Teradata Studio (Express) supports:

Windows

Mac OSX

Linux (discontinued in 17.20)

Teradata Studio Express


Teradata Studio Express is a base-level product. It is a client-based graphical interface
and provides an information discovery tool for retrieving and displaying data from
your Vantage Advanced SQL Engine systems. Its main use is for running SQL
statements, displaying result set data, and storing SQL execution history.
Equivalent to Teradata SQL Assistant with added features and new UI.
Database Connections Management

Connection Profile wizard to set up and manage database connections.
Database Explorer

 Data Source Explorer to view all database objects
 Property Form provides details about tables, columns, indexes, constraints,
triggers, space use, and privileges

Data Management

 Table Editor to easily add, delete, or update table rows
 Data Wizard to extract or load to and from existing tables
 Smart Loader for flat files to Teradata Database (including Data Lab) and
Hadoop

Ad-hoc Reporting

 SQL Editor to create and modify SQL statements with syntax checking and
formatting
 SQL Query Builder to visually build and edit SQL queries
 Execute individual or multiple SQL Statements
 Run Stored Procedures, Macros, and User-defined Functions
 Result Set Viewer with the ability to save, export, or print the results
 History Viewer to track the submitted SQL queries and preview results status

Teradata Studio
Teradata Studio, in addition to the features provided in Teradata Studio Express,
includes administration dialogs and wizards. It is mainly used by administrators to
create and administer database objects. Teradata Studio is a tool for DBAs, Data
Scientists, and Power Users. Teradata Studio also provides a client-based graphical
interface for performing SQL, and database administrative/management tasks on
Vantage Advanced SQL Engines, Teradata Aster Databases, and Hadoop systems.
Equivalent to Teradata Assistant and Teradata Administrator with added
features and new UI.
Additional Features in Teradata Studio

Teradata Administration

 Teradata database objects management
 Security commands to grant or revoke access and system rights
 Administer Roles and Profiles
 Manage Privileges on database objects
 Objects dependency browser
 Compare database objects
 Move Space between Teradata databases
 Teradata statistics collections management
 Secure Zones administration

Data Management

 Smart Loader for Teradata Database and Hadoop
 Bi-directional data movement from Teradata/Teradata and Teradata/Hadoop

Modular Display

The window helps you to visualize the Teradata Studio homepage and understand
each component, such as Menu and Toolbar, Data Source Explorer, SQL Editor, etc.

Creating Connections

1. Defining a Connection.
2. To begin using Teradata Studio, create a Connection Profile for your
database.
3. Connection to any database must be made through a JDBC (Java-
based data access technology) connection. The Connection Profile
details the JDBC information required to connect to an instance of a
Vantage Advanced SQL Engine.
4. When connecting to the Vantage Advanced SQL Engine, determine
which mode you will be using. Studio defaults to ANSI mode rather
than Teradata mode. Therefore, you may need to change it in the data
connection profile.
5. Use the Test Connection option to verify the connection with the
username and password. If you choose to save the password, do this
after testing the connection.
6. Connecting to a data source is the equivalent of “logging on” with
Teradata Studio. You may choose from any previously defined data
connection profile. Just right mouse click on the defined data
connection and select “Connect”.

 To connect to an existing Database Connection double-click on its name.


 The Database Explorer Tree displays an alphabetical listing of databases and objects of the connected user.
 To expand an item/object click on the arrow or double-click on the object name (Expanded view is shown below).
 Right-click an item to access its context-sensitive menu.
 For this course, some of the users/databases we will be using, are the following:
o EMPLOYEE_SALES
o FINANCE_PAYROLL
o DBC
o TRAINEE_nn

Data Source Explorer Preferences


The Data Source Explorer Load Preferences enables you to configure your preference settings for loading database and user

objects and to determine what folders are shown in the hierarchical display.

You can set preferences to:


Load Database and Users
Load:

 All databased and all users


 Only databases and certain users
 All databases and users with PermSpace configured

Configure Hierarchical Display


Configure hierarchical display to:

 All databases and all users


 Only certain folders you specify

SQL Editor

The SQL Editor provides an integrated environment to develop SQL statements for execution. You can validate SQL syntax, save
files to a project or export to system files, execute all SQL in a file, or execute the SQL as individual statements. You must specify
a Connection Profile before you can execute an SQL query statement.

The SQL Editor displays when you open an SQL/DDL file or when you select the Query Development perspective. Double-click an
SQL/DDL file in Project Explorer to open that file.
The session connected by the Data Source Explorer Tree is not reused in the editor. Each SQL editor window connects to a new session.

Connection Monitor

Information about the number of sessions connected by Studio can be shown in the Connection Monitor:
Window > Show View > Other > Teradata > Connection Monitor

Dragging Object Names to the Query Window

You can click and drag object(s) from the Database Explorer tree to the Query
window.

 By default, qualified names are automatically included. Use the


Preferences > Teradata Datatools Preferences > SQL Handling dialog to
turn off this option if desired.
 The Shift and Ctrl keys can also be used to select multiple objects in the
Database Explorer tree for the purpose of dragging multiple objects to the
Query Window.

Refer to the animation below to learn more.

You can drag objects from the Data Source Explorer and drop them into the SQL Editor to build
your SQL statement. The object name appears in the SQL Editor at the location where you drop it.
You can drag object names from the Database Explorer tree to the Query pane. Click and drag the
object from the Explorer tree to the Query pane. The name of the object appears in the Query
window. Use the Ctrl key to add a comma after the object name when it is dragged to the Query
Window. Dragging Multiple Objects

You can use the Shift and Ctrl keys on the keyboard to select more than one
object from the Database Explorer Tree that can be dragged to the Query
window.

 Use the Ctrl key to select additional objects


 Use the Shift key to select a range of objects

To do so, go to Preferences > Teradata Datatools > SQL Handling and


select Qualify names for drag and drop in SQL Editor to qualify names
when objects are dragged from the Data Source Explorer and dropped in the
SQL Editor. Clear this check box if you do not want names qualified.
SQL Editor Features

Features of SQL Editor are listed below:


 You can validate syntax using Syntax Validation as you edit
 The SQL Parser parses the SQL statement according to the grammar for the
version of Vantage or Aster specified in the Connection Profile

Rectangular block selection or column mode selection allows you to select the text vertically within

the text. To do so, you can click the SQL Editor and toggle between column mode selection and

normal mode selection using:

 SHIFT + ALT + A (Windows and Linux)


 command ⌘ + option ⌥ + A (MacOS)

SQL Editor Preferences: Execute Current Text


There are several ways to execute SQL statements, either from the Execute button
dropdown list or the right-click context menu.

Below are the different execute options available.


Execute
Execute
Execute as Individual Selected
Execute All Selected Execute Current Text
Statements Text as One
Text
Statement

Execute
Execute all Execute
the highlighted st Execute the statement
statements the highlighted st
atement(s) in the Execute all statements between the previous
in the editor atement(s) in the
editor as in the editor as a single and the following
as a single editor as a single
individual request (sequentially) semicolon based on the
request (in request (in
requests cursor position
parallel) parallel)
(sequentially)

Execute current text and submits the SQL at the current cursor position, similar to
"highlight all text between the previous and the next semicolon and submit it". To set the
preferences, go to:
Preferences > Data Management > SQL Development > SQL Editor and select
your choices.
Project Explorer
The Project Explorer provides a hierarchical view of the Projects and their resource
files. You can select SQL files for editing or create new SQL files.

Result Set Viewer


The Result Set Viewer provides an enhanced view of the result set, including
options to hide columns, filter on column values, find column values, copy data to the
clipboard, format cell data, and switch between grid and text view. The result set is
displayed in its own view with its own toolbar.

Setting Result Set Viewer Preferences


You can change preferences to customize the view by, for example, displaying
alternating row background colors, enabling or disabling row numbers, column
headers, table grid lines, and thousand separators on numeric columns. You
can change the max display row count, as well as the display null value and
date format. To change the preferences, go to the following path:

Preferences > Teradata Datatools > Result Set Viewer

To summarize, Result Set Viewer can help to:

 Display, Print, or Format the results


 Format and Filter the results
 Find and Copy cells
 Save or Export result sets to Excel, XML, or text files

SQL History

 Elapsed time and row count of the Queries


 Submitted SQL queries information
 Import/export history
 Filters options
 Show connection source information

The SQL History form provides an enhanced display of the history information. As you execute
SQL statements from the SQL Editor or run functions from the Data Source Explorer, an entry is
added to the SQL History list. The history displays extensive information about each SQL
execution, including execution elapsed time, DBMS time, fetch time, database server, row count,
parameter display for macros and stored procedures, as well as displaying the SQL statement and
SQL statement type. The SQL History form displays the data in a grid format that lets you select
rows or cells, and you can copy cells or rows, sort columns, delete rows, edit the note or SQL for a
history entry, filter columns, search for result history data, format the display, and re-execute SQL
statements. You can add notes manually by clicking on the Note column value. You can also
choose to be prompted to add notes when you execute the SQL. You can sort columns in
ascending and descending order with the exception of the Parameters column. Rows can be
selected by clicking in the numbered row header. Column order, collapsed columns, filter, sort,
and formatting are preserved from session to session. If a filter is in effect, the result of a newly
executed SQL statement is inserted as the top row, regardless of whether it meets the filter
criterion. If a sort is in effect the new entry is inserted in the sorted order. The Result column
contains a summary of the executed SQL operation. To read the entire contents in a column cell,
hover the mouse pointer over the cell. Error results show as red text in the resulting tool tip
display.
Comment
You can embed Standard SQL compliant comments within an SQL request.

The SQL Parser recognizes the following types of ANSI/ISO SQL:2016-compliant embedded
comments:

Simple Comments Bracketed Comments


A bracketed comment is
a text string of
The simple form of a
unrestricted length that
comment is delimited by
is delimited by the
two consecutive
beginning comment
HYPHEN-MINUS
characters SOLIDUS
(U+002D) characters (--)
(U+002F) and ASTERISK
at the beginning of the
(U+002A) /* and the end
comment and the
comment characters
newline character at the
ASTERISK and SOLIDUS
end of the comment.
*/.
-- comment_text
/* comment_text */
Simple SQL comments
Bracketed comments
cannot span multiple
can begin anywhere on
lines.
an input line and can
span multiple lines.
HELP Object
The HELP command is available for most objects, for example
HELP DATABASE | USER | INDEX | COLUMN | STATISTICS | TRIGGER |
FUNCTION | PROCEDURE
Detailed information about this object is returned.
SHOW Object

The SHOW statements return the source code (DDL) of the named objects.

These statements are particularly useful for application developers who need to
develop exact replicas of existing tables, views, triggers, hash and join indexes, stored
procedures, user-defined functions, or macros for purposes of testing new software.

Some SHOW statements optionally return database object definition SQL text in XML
format.

SHOW SELECT

Displays the DDL for all database objects referenced by a specified DML request.

You must have one of the following privileges to execute a SHOW or SHOW IN XML
request:

 The privileges necessary to perform the specified DML request and any right on
each database object
 The SELECT privilege on the dbc.tvm system table
The SHOW report lists the DML_statement DDL definitions in order of dependencies, first
listing the definitions of independent objects and then listing dependent objects.

The rank ordering of the DDL definitions in the report is as follows:

1. Base tables
2. Referenced (parent) tables of base tables
3. Error tables
4. Views
5. Macros
6. Triggers
7. Join and hash indexes
8. UDTs

DML_statement is limited to the following SQL DML statements:

 DELETE
 INSERT
 INSERT … SELECT
 MERGE
 SELECT
 UPDATE

SQL Editor with Outline View

You can access SQL Editor with Outline View by navigating through the following path:

Window > Show View > Other > General > Outline

The Outline view appears at the bottom of the screen.

Click and drag the Outline view up to the right-hand side of the SQL Editor.

As you select SELECT Statements from the Outline view, the SQL statement is
highlighted in the SQL Editor window.
Additional Studio Preferences
Summary

Characteristics of Teradata Studio include:

 Windows-based utility that is used to access any JDBC Compliant database


 GUI access to the Teradata Dictionary
 SQL commands like SHOW and HELP can also be used to provide dictionary
information
 History can be used to recall a previously issued request to the Query Window
 Query Builder feature allows for easy creation of SQL statements
 Provides a Data Source Explorer to easily view database objects

LAB 1

 Create a database connection for the training server based on the credentials
you received
o Don't forget to remove TMODE = ANSI
 Modify Studio preferences:
o Show a flat list instead of a hierarchy of databases in the Explorer Tree
o Enable Execute Current Text
o Any additional option you consider appropriate
 Locate the finance_payroll.hr_payroll table and check the info returned in the
Explorer Tree
 Run HELP TABLE and SHOW TABLE for this table
 Open a SQL Editor window and execute a
SELECT * FROM finance_payroll.hr_payroll;
 Click the Export Results to File icon and rerun the Select, saving the result to a
CSV file.

Lesson 4 of 22

Basic Select Clauses


After completing this module, you will be able to:

 Distinguish between three classes of SQL queries


 Use ORDER BY to sort result sets
 Alias column names for providing new names
 Use DISTINCT to project a distinct list of result rows
 Apply WHERE constraints to conditionally return rows
 Project character or numeric literal values
 Write SQL in a way that is more structured and easier to read

SQL is the “non-procedural” language of the database, but an interpretive language.


Designed for Relational Database Management Systems (RDBMS).

Procedural languages contain looping constructs and IF/ELSE logic that interpretive
languages don’t contain. Such constructs do, however, exist in Stored Procedures. Stored
Procedures are SQL based.

Most of the SQL in this course adheres to ANSI/ISO standards.


ANSI: American National Standards Institute (US)
ISO: International Organization for Standardization (World)

SQL Classifications: SQL statements are commonly divided into three categories:
Data Definition Language (DDL): Used to define and create database objects such as
tables, views, macros, databases, and users.
CREATE Define a table, view, macro, index, trigger, or stored procedure.
DROP Remove a table, view, macro, index, trigger, or stored procedure.
ALTER Change table structure or protection definition.

Data Manipulation Language (DML): Used to work with the data, including such tasks as
inserting data rows into a table, updating an existing row, or performing queries on the
data. The focal point of this course will be on SQL statements in this category.
SELECT Select data from one or more tables.
INSERT Place a new row into a table.
UPDATE Change data values in one or more existing rows.
DELETE Remove one or more rows from a table.

Data Control Language (DCL): Used for administrative tasks such as granting and
revoking privileges to database objects or controlling ownership of those objects.
GRANT Give user privileges on database objects.
REVOKE Remove user privileges on database objects.
GIVE Transfer database ownership.

SQL Keywords and Reserved Words


Keywords are words that have special meanings in SQL statements.
Teradata and ANSI/ISO SQL standards restrict the use of certain words as identifiers
because those words may be incorrectly interpreted as SQL keywords. Restricted words
should not be used as database object names or as parameters in application programs
that interface with the database. The categories of restricted words are:
Statement Keyword: The statement keyword, the first keyword in an SQL statement, is
usually a verb. For example, in the INSERT statement, the first keyword is INSERT.
Other Keywords: Other keywords appear throughout a statement as qualifiers (for
example, DISTINCT, PERMANENT), or as words that introduce clauses (for example, IN,
AS, AND, TO, WHERE) By convention, keywords appear entirely in uppercase letters.
However, SQL keywords are not case-sensitive and can be in uppercase or lowercase
letters
Reserved Words: These words are used as keywords by Teradata or ANSI/ISO SQL
They cannot be used as identifiers to name database objects, such as databases, tables,
columns, or stored procedures
The SYSLIB.SQLRestrictedWords view lists all restricted words for the current database
release.

Naming rules
The following rules apply to SQL:

1.

Object names/identifiers are composed of the following characters:

 Uppercase or lowercase letters (A to Z and a to z)


 Digits (0 through 9)
 Special characters ($, #, and _)
2.

Names may not begin with a digit

3.

Names are limited to 128 characters

4.

Enclosing an object name in double quotes (") enables the use of additional
characters and reserved keywords: CREATE TABLE "my
table?"("column" int); which should be avoided
5.

Object names are always case insensitive

 Deviation from Standard SQL which treats quoted identifiers case


sensitive

These additional restrictions apply in SQL:


An object name consisting entirely of white spaces is not allowed
A trailing white space is not considered part of an object name
Using QUOTATION MARKS Characters with Object Names
Enclosing an object name in QUOTATION MARKS characters (U+0022) enables the use
of characters, spaces, symbols, and other special characters that may not otherwise be
allowed. For example, an object name containing a white space character must be
enclosed in quotation marks: "object name". QUOTATION MARKS characters that
delineate object names are not stored in Dictionary tables, and when querying a Dictionary
view, results that contain such names are displayed without the double quotation marks.
However, if you include the name in a subsequent database request, you must add double
quotation marks, or the request fails.
Case Sensitivity of Object Names
Object names are not case-dependent. Any mix of uppercase and lowercase can be used
when defining or referencing object names in a request. Because of this, you cannot reuse
a name that is required to be unique just by changing its case.
For example, the following statements are identical:
SELECT Salary FROM Employee WHERE EmpNo = 10005;
SELECT SALARY FROM EMPLOYEE WHERE EMPNO = 10005;
select salary from employee where empno = 10005;
Note: The column name is the default title of an output column, so the system returns
these names in the same case in which the names were defined.
A Simple SELECT
An example of a simple SELECT statement is shown below.
Show a list of the last and first names of all employees.
The query for the above problem statement can be written as:

Using WHERE to Eliminate Rows


A WHERE clause of a SELECT statement (or construct) can be used to restrict the number
of rows returned. A conditional search expression, also referred to as a conditional
expression or predicate, must be satisfied by the row or rows returned by the statement.
Logical expressions include comparisons of numeric values, character strings, and partial
string comparisons. Follow the examples below to learn about using the WHERE clause.
The basic comparison operators are equal (=), not equal (<>), greater than (>), less
than (<), greater than or equal to (>=), and less than or equal to (<=).
In the above examples, Example 1 shows how to apply a condition to a numeric column
(using no single quotes), while Example 2 shows how to apply a condition on a character
column (single quotes required). If qualifying on a literal character column without single
quotes, then the database considers the literal to be an object name. The following
comparison operators are Teradata extensions to the ANSI SQL:2016 standard. Their use
is deprecated.
ANSI Operator Teradata Extension Function
= EQ Tests for equality
^=

<> NE Tests for inequality

NOT=
< LT Tests for less than
<= LE Tests for less than or equal
> GT Tests for greater than
Tests for greater than or
>= GE
equal
Character String Comparison
Comparing two character strings of unequal length:
 The shorter of the two is padded on the right with spaces before the comparison
occurs ????
 Effectively ignoring trailing spaces: 'a' = 'a '
Case Sensitivity
Is 'a' = 'A'?
To answer this question, you should understand that:
 Each character column is defined as either CASESPECIFIC or NOT
CASESPECIFIC
 If either operand in a comparison is case specific then the comparison is case
sensitive
Teradata SQL allows two different modes of session operation. Let's understand this with
an example.

1. In ANSI mode WHERE last_name = 'brown' will return no row for 'Brown'.
2.
CASESPECIFIC attribute can be added to an operand to override the default, e.g.
 WHERE last_name = 'brown' (NOT CASESPECIFIC) (Overwrite case
sensitive literal in ANSI mode)
 WHERE last_name (CASESPECIFIC) = 'brown' (Overwrite case sensitive
column in Teradata mode)
ORDER BY Clause

The order in which columns are listed in the ORDER BY clause is significant. The
column named first is the major sort column. The second and subsequent are minor
sort columns.

Column References and ORDER BY

 Each column_name you specify in an ORDER BY clause must be the


name of a column in a relation referenced in the SELECT expression list
o The columns named do not have to match the columns in the
SELECT expression list
 You can also order on a column name alias
 You can specify up to 64 columns
 Each column specified in the ORDER BY clause can have its own sort
order, either ascending (ASC) or descending (DESC)
 You may indicate the sort column by specifying its position within the
SELECT column list
 You cannot specify BLOB or CLOB columns in the column name list
because you cannot sort on LOB values

An example is shown below.


Summary

The ORDER BY clause specifies the column(s) for sorting the result set.

 Default ASCending order, DESCending can be specified:


o ORDER BY last_name DESC;
 Up to 64 columns can be added as a comma-delimited list:
o ORDER BY last_name ASC, first_name DESC;
 Can be sorted by a column, not in the Select list:
o ORDER BY birthdate;
 Can specify the column position with the Select instead of the
name:
o ORDER BY 1, first_name DESC; (not recommended)
 Can be sorted by an expression:

Requires more spool & CPU usage ⇒ don't order by too many columns.
o ORDER BY quantity * price;

o ORDER BY columns are duplicated in spool
o Varchar columns are expanded to the defined maximum size

ORDER BY: Session Collation and Casespecific

The sorting of character data is based on two parameters:


The CASESPECIFIC Option
 Each character column is defined as either CASESPECIFIC or NOT
CASESPECIFIC
 This default can be overridden using
ORDER BY col ([NOT] CASESPECIFIC);

The Session Collation


 Multiple collations predefined
 Default set on user level
 Can be changed for the current session using SET SESSION
COLLATION collation_sequence;

The same logic is applied when two strings are compared using less/greater.

SET SESSION COLLATION changes the collation sequence for the current session.

This statement is a Teradata extension to the ANSI SQL:2011 standard.


Teradata Database offers multiple standard collation sequences in which data can be defined as

CASESPECIFIC or NOT CASESPECIFIC.

This affects how the collation sequences collate and compare data.

All users share the same collation to get the same results.
Aliasing a Column
Naming Columns and Expressions
Each column in a SELECT result has a name that is derived from the list of specified
column names (expressions) that generated the data. The name is typically the
column name from which the data came.
An alias can be used for any column when a pseudonym is more descriptive or easier
to use.

Alias names must meet the same requirements as names of other database objects.

The scope of alias names is confined to the query.


You can specify a column alias with or without the keyword AS on the first
reference to the column in the query.
When the query is executed:

You can rename, or alias, a projected column for the current select.

 More descriptive column name:


o lname AS "last name"
 Shorter column name for display:
o manager_employee_number AS mgr#
 Readable name for calculated columns:
o salary_amount / 12 AS monthly_sal
 The keyword AS is optional but recommended
o Easier to spot if a column is aliased
Legacy Teradata syntax using the NAMED clause is supported for backward
compatibility.
The NAMED clause is enclosed in parentheses immediately following the
renamed column.
An example is shown below.
SELECT manager_employee_number (NAMED mgr#)
,department_number (NAMED dept#)
,last_name
,first_name
,salary_amount / 12 (NAMED monthly_sal)
FROM employee_sales.employee
ORDER BY mgr#, last_name
;

Referencing a Column Alias


Naming Columns

Teradata SQL allows for naming derived columns and renaming existing columns. For
every expression that is given a name, that name is entered in a NAMED list that
associates the expression with the name. This is true for both forms of naming
columns, NAMED and AS.

This temporary name can be referenced elsewhere in the request. But it should not be
the same as another column name of any table used in a query. If the parser finds an
unqualified column name it searches the column lists of all tables named in the SQL
statement.

 If a matching column is found in only one table the requested


information is returned
 If it's found in two or more tables an ambiguous column name error is
reported.
3809 Column 'xxx' is ambiguous
 Only if it's not found, the NAMED list is searched for the column name

Two examples are shown below to demonstrate referencing a Column Alias.


DISTINCT
DISTINCT is an optional keyword that can come directly after the SELECT keyword.

DISTINCT specifies that duplicate rows are not to be returned.

Only one row is to be returned from any set of duplicates that might result from a

given select list. Rows are duplicates only if each value in one is equal to the

corresponding value in the other.

Depending on the optimizer plan DISTINCT might return a sorted result set, ordered

over all columns. As the plan might change it is recommended to add an explicit

ORDER BY if a sorted answer set is required.


SELECT ALL specifies that duplicate rows are to be returned. It's the default option, thus hardly
used.

To Summarize:

1. 1

The DISTINCT keyword is specified directly after the SELECT keyword

2. 2

It consolidates duplicate output rows to a single occurrence

3. 3

Increased spool and CPU usage


4. 4
More expensive than ORDER BY over all columns
Select Star
The asterisk expands into a list of column names in the physical order in which the
column names appear within their table/view declaration.

An example is shown below.

The asterisk (*) indicates that we wish to see all of the columns in the table.

Useful only while developing queries.

 Should be avoided in production queries


 Number and order of columns unknown without executing the select
 Number and order of columns in the base table(s) or view(s) might change

Select only the data that you really need.


Default Database

The default database is a Teradata extension to Standard SQL that defines a


database that is used to look for unqualified names, such as table, view, trigger, or
macro names, in SQL statements.

The default database is not the only database used to find an unqualified name in an
SQL statement. The parser also looks for the name in:

 Other databases, if any, referenced by the SQL statement


 The login user database for a volatile table, if the unqualified object
name is a table name

If the unqualified object name exists in more than one of these databases,
the SQL statement produces a 3806 Table/view/trigger name xxx' is an
ambiguous error.

If the unqualified object is a function, the parser also looks for the name in:

 The databases defined by SET SESSION UDFSEARCHPATH


 The SYSLIB and TD_SYSFNLIB databases

Changing the Default Database


Once logged on, you can change the default database by using the DATABASE
command:
DATABASE employee_sales;

The default database is employee_sales until either:

 User logs off


 A new Database command is issued

You can override a default DATABASE in a single SQL statement by explicitly


specifying the database:
SELECT * FROM employee_sales.employee;

 A session always has a default database, initially set during login using
o Connection properties (JDBC, ODBC, etc.)
o Default database option of the user's profile
o Default database option of the user
o If none is defined the user name is used
 Can be changed for the current session by using
DATABASE new_default_database;
 Used by the parser to look for unqualified names, such
as table, view, or macro names, in SQL statements
 SELECT *
 FROM employee_sales.employee;
 Example 1

 DATABASE employee_sales;
 SELECT *
 FROM employee;
 Example 2

 Example 1 and Example 2 produce the same result.


 Recommendation: Don't mix qualified and unqualified names.
 Built-In Functions
 Built-in functions return information about the system. They can be used
anywhere that a literal can appear.
 Click each + to learn more.
Mainly used for extracting information from the system views.
SELECT DatabaseName, TableName, TableKind
FROM dbc.TablesV
WHERE DatabaseName = DATABASE;

Summary

 SQL has three classes of queries:


o DDL
o DML
o DCL
 The number of rows returned can be affected by condition applied via a
WHERE clause
 You can rearrange the order of the rows in the result set by using ORDER
BY
 You can alias a column name using AS
 Operators like =, <>, <=, >=, < and > can be used as qualifiers
 DISTINCT can be used to project a distinct list of result rows
 Understanding the ANSI collating sequence can help when writing
conditions
Try completing the labs in the AWS lab environment. When you get the desired results,
compare your code with the code under the Solution tabs.
Retrieve all departments with a budget amount over 20 million.
Show the department's number (renamed to dept_no) & name and its budget amount (renamed to budget).

Order the result set by descending budget.

HELP TABLE hr_departments;


Retrieve all departments with a budget
amount over 20 million.
Show the department's number (renamed to
dept_no) & name and its budget amount (renamed HELP
to budget). TABLE hr_departments;

Order the result set by descending budget.

Retrieve all the staff being from the payroll


employed for more than 40 years
(years_service).

Show employee's first & last name, birthdate HELP


& hire date and the years of service TABLE hr_departments;
(abbreviated to YS).

Order the result set by hire date.


Retrieve a list of unique combinations of
transaction types (trans_type) and
transaction modes (operation) from the
transaction table. HELP
TABLE hr_departments;
Order the result set by transaction type and
mode.

You might also like