Você está na página 1de 9

Teradata SQL Quick Reference Guide: Simplicity by Design, Second

Edition
by Tom Coffing, Michael Larkins and Steve Wilmes
Coffing Data Warehousing. (c) 2006. Copying Prohibited.

Reprinted for Chandrasekhar Marisetti, IBM


mc.sekhar@in.ibm.com
Reprinted with permission as a subscription benefit of Books24x7,
http://www.books24x7.com/

All rights reserved. Reproduction and/or distribution in whole or in part in electronic,paper or


other forms without written permission is prohibited.

TeradataSQLQuickReferenceGuide:SimplicitybyDesign,SecondEdition

Preface
Overview
"You miss 100% of the shots you don't take"
Wayne Gretzky
Asking the right questions is half the battle to greatly impacting the company's bottom line, but sometimes knowing the proper SQL inhibits
users from taking their shot at corporate greatness. This book is dedicated to assisting users in asking the right questions by providing an
easy to understand guide that takes the difficulty out of SQL.
The purpose of "SQL Reference Guide Simplicity by Design" is simple: Users need an easy and concise reference book at their fingertips
that they can refer to, without having to search through larger books for SQL help. After the generic syntax, there are applied examples that
have been written based on the SQL_CLASS database, which can be downloaded from our website at: www.CoffingDW.Com.
The "SQL Reference Guide Simplicity by Design" follows this format for each command:
n

SQL Command Easy lookup with a great INDEX in the back

Short Definition

Syntax

Examples

Examples explained

Hint Man - Tips from pros

Issues Common Mistakes

Solutions to those issues

The standards for "SQL Reference Guide" are as follows:


<database-name>

Substitute an actual database name in this location

<table-name>

Substitute an actual table name in this location

<comparison>

Substitute a comparison in this location, i.e. a=1

<column-name>

Substitute an actual column name in this location

<data-value>

Substitute a literal data value in this location

[ optional entry ]

Everything between the [ ] is optional, not required to be valid syntax , use when needed

{ use this | or this }

Use one of the keywords or symbols on either side of the "|", but not both. I.e. { LEFT | RIGHT } use either "LEFT" or "RIGHT" but not both

The Select Command


The SELECT Command selects which columns are needed for the report (or answer set) and the tables that contain them.
SELECT
{*}
FROM <table-name>;
SELECT * FROM Course_Table;
Hint - Man The asterisk returns every column in the table. The SELECT * relates to columns and the WHERE clause relates to rows
selected.
Issues:

The message, "3807: Table/view/trigger '<table-name> does not exist." will occur when the table being selected from does not reside on Teradata.
Or, you are in the wrong database.

Solutions:

Check the spelling of the <table-name>, use the SELECT DATABASE syntax to confirm you are in the correct database or HELP DATABASE
<database-name> to see all objects in the database.

SELECT { <column-name> }
[,<column-name> ]
FROM
<table-name>;
SELECT Customer_Number FROM Customer_Table;

Page 2 / 9
Reprintedforibm\mc.sekhar@in.ibm.com,IBM

CoffingDataWarehousing,CoffingPublishing(c)2006,CopyingProhibited

TeradataSQLQuickReferenceGuide:SimplicitybyDesign,SecondEdition

SELECT Dept_No
,Dept_Name FROM Department_Table;
Hint - Man When requesting multiple columns in a table each column is separated from the next by a comma. Experienced users often
place the comma at the beginning for easy debugging.
Issues:

A missing comma could be a problem with this syntax. Here is the Error

Message:

3810: Column 'Column1Column2' does not exist.

Solution:

Search through the SQL code to locate the two columns with no comma between the two, and place a comma. Or you could have an extra comma
at the end of the last column selected. Take the extra comma out.

The WHERE Clause


The WHERE clause eliminates certain ROWS from the result set and is used when users don't want to see every single row in a table.
SELECT { * | <column-name> }
[,<column-name> ]
FROM
<table-name>
WHERE { <column-name> | <expression> } <comparison> <data-value> ;

SELECT * FROM Employee_Table


WHERE Dept_No = 400;
English: The above example will SELECT all columns from the Employee_Table if the employee's department number is 400.
Hint - Man If a query has no WHERE clause then every row will be selected. If you want to access data as fast as possible use the
Primary Index column in the WHERE clause.
Issues:

3535: A character string failed conversion to a numeric value. The <data- value> in the WHERE clause does not match the data type of the
<column- name>. Also remember that numeric values are not in single quotes ' '. Character data should be in single quotes.

Solutions:

The first thing to do is to find out the data type of the <column-name> involved by running HELP TABLE <table-name>. Next, adjust the <data-value>
to match the data type.

Comparators: AND/OR
Many times a single comparison in a WHERE clause is not enough to specify the desired rows. The AND/OR commands are called logical
operators. The AND syntax requires both comparisons to be true. The OR syntax however, only requires one of the two to be true.
SELECT <column-name>
[,<column-name> ]
FROM
<table-name>
WHERE <column-name> <comparison> <data-value> AND | OR
<column-name> <comparison> <data-value>;

SELECT * FROM Order_Table


WHERE Customer_Number = 11111111
AND Order_Total > 10000;
English: Above we select all columns if the customer number = 11111111 AND the Order_Total is greater than 10000. Both have to be true for
data to come back.
SELECT Product_Id, Daily_Sales FROM Sales_Table
WHERE Sale_Date = '2000-09-28'
ORSale_Date = '2000-10-01';
English: Above we select two columns for any row that has a sale date of either September 28 2000 or October 1 2000. Only one of them has
to be true.
Hint - Man If you get a syntax error with an OR command it is probably because you did not name the column in the where clause twice.
For example, you can't say WHERE DEPT_NO = 10 OR 20. You must say WHERE DEPT_NO = 10 OR DEPT_NO = 20.
Issues:

You get now rows coming back in the answer set

Solutions:

Remember that when you use AND that you must utilize two different columns. For example, an employee could not have a SALARY of $50,000
AND $75,000. You could however have an employee in department 100 AND have a salary of $50,000.

Combining Comparators: AND/OR


Page 3 / 9
Reprintedforibm\mc.sekhar@in.ibm.com,IBM

CoffingDataWarehousing,CoffingPublishing(c)2006,CopyingProhibited

TeradataSQLQuickReferenceGuide:SimplicitybyDesign,SecondEdition

SELECT <column-name>
[...,<column-name> ]
FROM
<table-name>
WHERE ( <column-name> <comparison> <data-value> OR
<column-name> <comparison> <data-value> ) AND
<column-name> <comparison> <data-value> ;

SELECT Last_Name, First_Name FROM Student_Table


WHERE (Class_Code = 'JR' OR
Class_Code = 'SO') AND
Grade_Pt > 2.5;
English: The above selects two columns if the student has a Class_Code of 'JR' or 'SO' and that 'JR' or 'SO' has a Grade_Pt above 2.5.
Hint - Man When there is an AND/OR combination the AND is always done first by Teradata unless the OR pair is in parentheses, like
the above example.
Issues:

The data you expected to come back may not.

Solutions:

You need to remember that when combining AND/OR comparators that Teradata will analyze the AND first unless you place parenthesis around the
OR statements.

Combining Multiple AND Comparators or Multiple OR Comparators


SELECT <column-name>
[...,<column-name> ]
FROM
<table-name>
WHERE <column-name> <comparison> <data-value> AND | OR
<column-name> <comparison> <data-value> AND | OR
<column-name> <comparison> <data-value>

SELECT * FROM Student_Course_Table


WHERE Student_Id = 280023 OR
Student_Id = 333450 OR
Student_Id = 231222;
English: Above we select every column from the row if the Student_Id is 280023 or 333450 or 231222.
SELECT Employee_No FROM Employee_Table
WHERE Dept_No <> 400 AND
Salary > 40000 AND
Salary < 50000;
English: Above we select one column from the row if the Dept_No is not equal to 400 and the salary is greater than $40000, but less than
$50000.
Hint - Man Dealing with NOT, AND an OR can be confusing. You can place parenthesis around the SQL and it will be evaluated first.
Hint - Man Be careful when using multiple AND statements. Remember that ALL criteria must be met in order for the row to be returned in
the result set. For example, a user should not search for a student with a Grade_pt of 3.0 and 4.0. This will not work because
nobody can have a Grade_pt of both 3.0 and 4.0. An OR should have possibly been used.

IS NULL Clause and IS NOT NULL Clause


NULL data is often described as empty data, but it is actually undetermined data. Therefore you can never check if something is EQUAL to
NULL. You can only check if something IS NULL or IS NOT NULL.
SELECT <column-name>
[...,<column-name> ]
FROM
<table-name>
WHERE <column-name> IS NULL

SELECT Last_Name, First_Name FROM Student_Table


WHERE Grade_Pt IS NULL;
English: Above we select two columns from any row that has a NULL value for Grade_pt.
SELECT Last_Name, First_Name FROM Student_Table

Page 4 / 9
Reprintedforibm\mc.sekhar@in.ibm.com,IBM

CoffingDataWarehousing,CoffingPublishing(c)2006,CopyingProhibited

TeradataSQLQuickReferenceGuide:SimplicitybyDesign,SecondEdition

WHERE Grade_Pt IS NOT NULL;


English: Above we select two columns from any row that does NOT have a NULL value for Grade_pt.
Hint - Man Sometimes when checking if something is = NULL you will get an error and sometimes you will not get an error, but no rows
will be returned. When checking for NULLS the only valid statements are IS NULL or IS NOT NULL.
Issues:

= NULL is not a valid SQL statement. Change the syntax to IS NULL. 3731: The user must use IS NULL or IS NOT NULL to test for NULL values.

Solution:

Adjust the SQL syntax from '=NULL' to 'IS NULL' or 'IS NOT NULL'.

NOT Clause
The NOT Clause will check for values that are NOT <, > or equal to a value. Teradata searches for the logical opposite of the
<comparison> statement.
SELECT <column-name>
FROM
<table-name>
WHERE <column-name> NOT <comparison> <data-value> ;
SELECT Course_Name FROM Course_Table
WHERE Seats NOT >= 20;
English: Above we find all courses where there are less than 20 seats in the course.
SELECT Customer_Name, Phone_Number
FROM Customer_Table
WHERE Customer_Name NOT = 'ACE Consulting';
English: Above we SELECT two columns for all Customers except 'ACE Consulting'.
Alternative Syntax:
SELECT <column-name>
FROM
<table-name>
WHERE NOT ( <column-name> <comparison> <data-value> );
SELECT Course_Name FROM Course_Table
WHERE NOT ( Seats >= 20 );
SELECT Customer_Name, Phone_Number
FROM Customer_Table
WHERE NOT ( Customer_Name = 'ACE Consulting' );
Hint - Man Running this syntax without parentheses is permissible, but not recommended.
Issues:

Teradata returns the message: 3707: Syntax error, expected something like an 'IN' keyword between the 'NOT' keyword and '<comparison>'. This is a
problem caused by the 'NOT' not being properly placed in the SQL.

Solutions:

Locate the 'NOT' in the SQL and place it directly before the <column-name>, with the <comparison> after that.

IN and NOT IN
The IN comparison is an alternative to using one or more OR comparisons on the same column in the WHERE clause of a SELECT.
Teradata actually views the IN clause as a multiple OR statement. If the criteria are in the <value-list>, a row will be returned.
SELECT <column-name>
[...,<column-name> ]
FROM
<table-name>
WHERE <column-name> IN | NOT IN (<value-list>) ;
SELECT Dept_Name, Mgr_No FROM Department_Table
WHERE Dept_No IN ( 200, 300,100 );
English: Above we select two columns from each row where the Dept_no is 200 or 300 or 100.
SELECT * FROM Order_Table
WHERE Order_Number NOT IN (123585, 123456);
English: Above we select all columns unless the Order_Number is 123585 or 123456.
SELECT * FROM Department_Table
WHERE Dept_Name IN ('Sales', 'Marketing');
Page 5 / 9
Reprintedforibm\mc.sekhar@in.ibm.com,IBM

CoffingDataWarehousing,CoffingPublishing(c)2006,CopyingProhibited

TeradataSQLQuickReferenceGuide:SimplicitybyDesign,SecondEdition

English: Above we select all columns from the Department_Table if the department name is Sales or Marketing. Notice the single quotes
around 'Sales' and 'Marketing'. They are not numbers so they need single quotes.
Hint - Man Do not place the word 'NULL' in the <value-list> for a 'NOT IN', being that no rows will be returned every time.
Issues:

3706: Syntax error: expected something between an {integer | character-string} and ';'. This error is caused by a lack of parentheses around the
<value-list>.

Solutions:

Place a '(' before the <value-list> and a ')' after the final entry in the<value- list>.

= ANY, NOT = ALL


The =ANY command is the logical equivalent to the IN clause. The NOT = ALL command is similar to the NOT IN clause.
SELECT <column-name>
[...,<column-name> ]
FROM
<table-name>
WHERE <column-name> = ANY (<value-list>) ;
SELECT Dept_Name, Mgr_No FROM Department_Table
WHERE Dept_No = ANY (200, 300, 100);
English: The above example selects two columns if the Dept_No is 200 or 300 or 100. This is the same syntax as WHERE Dept_No IN (200,
300, 100).
SELECT <column-name>
[...,<column-name> ]
FROM
<table-name>
WHERE <column-name> NOT = ALL (<value-list>) ;
SELECT * FROM Order_Table
WHERE Order_Number NOT = ALL (123585, 123456);
English: The above example will SELECT all columns WHERE the Order_Number does NOT = 123585 or 123456. This syntax is the same as
NOT IN.
Hint - Man Be careful NOT to use NOT = ANY. This is because all rows will be returned unless they Are NULL. This is because the
instance a value is not equal to any one in the list, it is automatically returned.
Issues:

Missing the '=' sign is a possible problem.


3707: Syntax Error, expected something like an 'IN' keyword or a 'LIKE' keyword between the 'NOT' keyword and the 'ALL' keyword.

Solutions:

Add the equal sign before the 'ANY' keyword, or after the 'NOT' keyword.

BETWEEN
The BETWEEN statement is another technique to request multiple values for a column that are all in a specific range. The key item to
remember is that BETWEEN is inclusive and most widely used with numeric values. If you write WHERE AGE is BETWEEN 13 and 15 then
the answer set would contain individuals whose ages are 13, 14, or 15.
SELECT <column-name>
[...,<column-name> ]
FROM
<table-name>
WHERE <column-name> BETWEEN <low-value> AND <high-value>;

SELECT * FROM Sales_Table


WHERE Daily_Sales
BETWEEN 25000 AND 42000;
English: Select all columns where the Daily_Sales is between 25000 and 42000. This includes 25000 exactly and 42000 exactly.
SELECT Last_Name, First_Name, Grade_Pt
FROM Student_Table
WHERE Last_Name
BETWEEN 'Delaney' and 'Phillips';
English: Select three columns where the Last_Name is between Delaney and Phillips. This includes Delaney, Phillips and any name
alphabetically greater than Delaney and Less than Phillips.
Hint - Man BETWEEN is a command to look for ranges. BETWEEN works well with dates. If you index a date field in a table you can use
the ORDER BY VALUES syntax when creating the date index. Then BETWEEN and DATE ranges work in tandem. To see if

Page 6 / 9
Reprintedforibm\mc.sekhar@in.ibm.com,IBM

CoffingDataWarehousing,CoffingPublishing(c)2006,CopyingProhibited

TeradataSQLQuickReferenceGuide:SimplicitybyDesign,SecondEdition

a date is an index ORDERED BY VALUES run the SHOW TABLE <Tablename> command.

LIKE Clause
The LIKE Command searches character data strings and can use wildcards to find data that is similar. For example, a user can use the
LIKE command to request rows where the last_name starts with 'SM'.
SELECT <column-list>
FROM <table-name>
WHERE <column-name> LIKE '[<wildcard(s)>]<search-string>[<wildcard(s)>]';
The wildcard characters are:
Wildcard symbol

What it does

_ (underscore)

matches any single character, but a character must be present

% (percent sign)

matches any single character, a series of characters or the absence of characters

SELECT Course_Name, Course_Id FROM Course_Table


WHERE Course_Name LIKE '%SQL';
English: Select two columns from the rows in the course table if Course_Name has SQL at the end of the string.
SELECT * FROM Student_Table
WHERE Last_Name LIKE '_m%';
English: Select all columns from the rows in the Student table if Last_Name has an m as the second character.
Hint - Man LIKE works on Character Data. If I have a name that is CHAR(10) and a name such as Smith then the system sees the name
as 'Smith '. Notice the 5 extra spaces. You can use the TRIM function with the LIKE function to find anyone whose name ended
in h.
SELECT * FROM Student_Table
WHERE TRIM(Last_Name) LIKE '% h';
Issues:

The LIKE statement is not returning all the rows expected to be in the result set. More than likely you are dealing with Character strings of CHAR
data type. Remember 'Smith' in the eyes of Teradata is 'Smith+ empty space'. This empty space resides in the rest of the fixed data space on the
system.

Solutions:

There are two solutions to this problem. The first solution is to place a '%' at the end of the <search-string>, as in the second example. The second
solution would be to place the <column-name> in a TRIM function as so: TRIM(<column-name>. Either solution will take care of the problem.

Aliasing Columns
You create an ALIAS on a column for the purpose of giving the column a new name. You might do this to shorten the name or to better
describe a title you want to see as a column header. If you ALIAS and use a reserved word such as SELECT place double quotes around it.
In giving a column an alias, there are two options:
ANSI Standard:
SELECT <column-name> AS <alias-name>
FROM
<table-name>;
Teradata Standard:
SELECT <column-name> <alias-name>
FROM
<table-name>;
SELECT Dept_No
AS DEPT
,Dept_Name
AS "Department Name"
,Mgr_No
Manager
FROM Department_Table
ORDER BY "Department Name";
English: We have aliased three columns. The first column does not need double quotes. The second column needs them because there is a
space between Department and Name. The third ALIAS does not have the word AS. The word AS is optional when aliasing. Also notice we
are sorting by "Department Name". We once again use the double quotes.
Hint - Man If a user desires to assign an alias with a space like "Department Name", be sure to use double quotes around the alias
name, otherwise you don't need the quotes. For example, Department_Name does not need quotes.
Issues:

A common error is using a Teradata Reserved Word for an alias.


3707: Syntax Error, expected something like a name between the {'AS' | 'NAMED'} keyword and the '<reserved-word>' keyword.

Page 7 / 9
Reprintedforibm\mc.sekhar@in.ibm.com,IBM

CoffingDataWarehousing,CoffingPublishing(c)2006,CopyingProhibited

TeradataSQLQuickReferenceGuide:SimplicitybyDesign,SecondEdition

Solutions:

You can place double quotes around the ALIAS name and it is no longer considered a keyword in the query. For example, if you had an ALIAS
named MAX you could place double quotes around it to become "MAX".

ALIAS using NAMED


Teradata Extension that is used to alias a column. Once you use the NAMED command you must refer to the column with its new name. You
can also sort by the new name.
SELECT <column-name>
FROM
<table-name> ;

( NAMED <alias-name> )

SELECT Dept_No, Dept_Name (NAMED "Department Name")


FROM Department_Table;
English: The above example is aliasing Dept_Name as "Department Name". Notice the double quotes. This is because there is a space
between Department and Name. If the alias had been Department_Name we would not need the double quotes.
Hint - Man Some time after Teradata V2R5 this function will no longer be available. Remember to place double quotes around any
aliases with spaces in them, or if they are Teradata Reserved Words.
Issues:

A common error is using a Teradata Reserved Word for an alias.


3707: Syntax Error, expected something like a name between the {'AS' | 'NAMED'} keyword and the '<reserved-word>' keyword.

Solutions:

For reserved word errors place double quotes around the ALIAS name and Teradata will accept the ALIAS. For example, if you had an ALIAS named
MAX you could place double quotes around it to become "MAX".

ORDER BY Clause
Teradata brings back data unsorted unless you use the ORDER BY statement. The ORDER BY statement will sort the given <columnname> in the desired order. The default for Teradata is ascending order.
SELECT <column-name>
[...,<column-name>]
FROM
<table-name>
ORDER BY { <column-name> | <relative-column-number> } [ ASC | DESC ]
{, <column-name> | <relative-column-number> } [ ASC | DESC ] ;

SELECT Course_Id, Course_Name FROM Course_Table


ORDER BY 1;
English: The above will sort by the first column in the list which is the same thing as stating ORDER BY Course_Id.
SELECT Customer_Number, Order_Number, Order_Total
FROM Order_Table
ORDER BY Customer_Number DESC, Order_Number;
English: The above will sort by the Customer_Number in Descending order as the first sort key and then Order_Number as the second order
key. ASC is the default.
Hint - Man Teradata allows the ORDER BY statement to use a column name or number. If you ORDER BY 1 for example Teradata will
order by the first column in your select list. If you said ORDER BY 1 and your select list was SELECT * then Teradata will
ORDER BY the 1st column in the table.
Issues:

3637: Invalid ORDER BY constant. This error occurs when using the number of a column rather than its name in the ORDER BY clause. In most
cases the number used is larger than the actual count of columns involved in the query.

Solutions:

Identifying how many columns should be returned to the result set is the first thing to do. Next, find the proper number for the column, or columns
desired in the ORDER BY and adjust the SQL.

DISTINCT
If there are duplicate values in <column-name> Teradata will return all rows. Distinct allows the user to eliminate all the duplicates and only
return one instance of that value.
SELECT DISTINCT <column-name>
[, <column-name> ]
FROM <table-name>;

SELECT DISTINCT Student_Id

Page 8 / 9
Reprintedforibm\mc.sekhar@in.ibm.com,IBM

CoffingDataWarehousing,CoffingPublishing(c)2006,CopyingProhibited

TeradataSQLQuickReferenceGuide:SimplicitybyDesign,SecondEdition

FROM Student_Course_Table;
English: SELECT every distinct Student_Id from the Student_Course_Table. No duplicate Student_Ids will be returned.
SELECT DISTINCT First_Name, Dept_No
FROM Employee_Table ;
English: SELECT every distinct combination of First_Name and Dept_No. For example, Mary in Dept_No 10 is different than Mary in
Dept_No 20. Both would be returned.
Hint - Man This is a useful function but this may cause inaccurate results. The issue with DISTINCT is that it affects all the columns
desired in the result set. If there are two columns in the query, Teradata will search for a unique combination of both. In the
second example, the rows returned will be any distinct combinations of First_Name and Dept_No.
Hint - Man Often users will either use DISTINCT or GROUP BY for the same purpose. DISTINCT Is faster when there are only a few
duplicates and GROUP BY is faster when there are Many duplicates.

Page 9 / 9
Reprintedforibm\mc.sekhar@in.ibm.com,IBM

CoffingDataWarehousing,CoffingPublishing(c)2006,CopyingProhibited

Você também pode gostar