Download presentation
Presentation is loading. Please wait.
1
Introduction to Teradata SQL
2
Introduction to Teradata SQL - I
Naming Convention of database Objects Data Types Teradata Vs ANSI Teradata SQL Extension Logical and Conditional Expression Arithmetic Operators Arithmetic Functions Arithmetic and Comparison Operation on NULL LIKE operator String function
3
INTRODUCTION SQL Commands :
SQL statements commonly are divided into three categories: Data Definition Language (DDL) - Used to define and create database objects such as tables, views, macros, databases, and users. 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.
4
3. Data Control Language (DCL) - Used for administrative tasks such as granting and revoking privileges to database objects or controlling ownership of those objects. DDL Examples: SQL statement Function 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.
5
DML Examples: DCL Examples: SQL statement Function 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. DCL Examples: SQL statement Function GRANT Give user privileges. REVOKE Remove user privileges. GIVE Transfer database ownership.
6
Naming Convention Database Objects
Teradata rules about how database objects can be named are summarized in the following table: Names are composed of: a-z A-Z 0-9 _ (underscore) $ # Names must start with: _(underscore) Names are limited to 30 characters. NOTE: Teradata is not case-sensitive.
7
Naming Rules Naming Syntax
>Database names and User names must be unique within the Teradata RDBMS. >Table, view, macro, trigger, index and stored procedure names must be unique within a Database or User . >Column names must be unique within a Table. >The syntax for fully qualifying a column name is: databasename.tablename.columnname Example: NAME (unqualified) EMPLOYEE.NAME (partially qualified) PAYROLL.EMPLOYEE.NAME (fully qualified)
8
Data Types Character Data CHAR - has fixed-length character strings.
Holds Character data Character Strings Byte data Binary Data Strings Numeric data Numbers Date/Time data Dates,Times,Timestamps,Time Intervals Character Data CHAR - has fixed-length character strings. VARCHAR - has variable-length character strings.
9
Character Data Description Example CHAR (size) Fixed length string Max: 64,000 characters last_name CHAR(20) Sample contents: 'Ryan__________' VARCHAR (size) CHAR VARYING (size) CHARACTER VARYING (size) Variable length string Max: 64,000 characters first_name VARCHAR(30) Sample contents: 'Loretta' LONG VARCHAR Equivalent to VARCHAR (64000) NOTE: VARCHAR (size), CHAR VARYING (size), and CHARACTER VARYING (size) are all equivalent synonyms. LONG VARCHAR is equivalent to a maximum VARCHAR.
10
Byte Data Teradata supports two data types for holding binary data:
VARBYTE BYTE is for fixed length binary strings. VARBYTE is for variable length binary strings. Note: BYTE columns are not convertible to other data types. Byte Data Description BYTE (size) Fixed length Binary string Default: (1) Max: 64,000 bytes VARBYTE (size) Variable length Binary string Default: (1) Max: 64,000 bytes
11
Numeric and Date Data The following numeric data types are available: SMALLINT, INTEGER, DECIMAL ,FLOAT Data Type Description Examples SMALLINT BYTEINT Whole number Range: -32,768 to 32,767 Storage: 2 bytes a signed binary integer area_code SMALLINT range of -128 to +127 INTEGER Whole number Range: -2,147,483,648 to 2,147,483,647,Storage: 4 bytes phone INTEGER DEC(m, n) 'm' is total number of digits. 'n' is precision places to the right of decimal point. Max Size =18 digits Storage: 2 to 8 bytes salary_amount DEC (10,2) FLOAT Floating Point Format (IEEE) 2x to 2x Storage: 8 bytes salary_factor FLOAT E-001
12
DATE data type Data Type Description Examples DATE
Specially formatted integer: YYMMDD thru YYYMMDD from 2000 onward hire_date DATE DATE is stored as an integer, using the following formula: (year ) * (month * 100) + day The recommended display format for DATE values is ‘YYYY-MM-DD’ formatted as ‘YY-MM-DD’ is , which is also the representation of
13
Teradata versus ANSI Extensions
Modes of Operation Teradata SQL allows two different modes of session operation: ANSI mode Teradata (BTET) mode Choice of mode affects: Transaction protocol behavior Case sensitivity defaults Collating sequences Data conversions Display functions The same SQL statement might perform differently in each mode based on the above considerations.
14
Teradata SQL Extensions
Here is a list of Teradata extensions ADD_MONTHS BEGIN/ END TRANSACTION COLLECT/ DROP STATISTICS COMMENT ON CONCATENATION EXPLAIN FALLBACK FORMAT HELP INDEX LOCKING MACRO Facility • CREATE • REPLACE • DROP • EXECUTE NULLIFZERO/ZEROIFNULL NAMED SUBSTR SHOW TRIM TITLE WITH WITH BY
15
Logical and Conditional Expressions
Logical Operators Types of Operators in Logical Expressions = equal <> not equal > greater than < less than >= greater than or equal to <= less than or equal to BETWEEN <a> AND <b> inclusive range [NOT] IN <expression> is in a list or <expression> is not in a list IS [NOT] NULL <expression> is null or <expression> is not null [NOT] EXISTS table contains at least 1 row or table contains no rows LIKE partial string operator
16
BETWEEN -- Numeric Range Testing
Select the name and the employee's manager number for all employees whose job codes are in the range. SELECT first_name ,last_name ,manager_employee_number FROM employee WHERE job_code BETWEEN AND ;
17
BETWEEN -- Character Range Testing
SELECT last_name FROM employee WHERE last_name BETWEEN 'r' AND 's'; last_name Ryan
18
Set Operator IN SELECT first_name ,last_name ,department_number
FROM employee WHERE department_number IN (401, 403); first_name last_name department_number Darlene Johnson Loretta Ryan Armando Villegas James Trader
19
Set Operator NOT IN SELECT first_name ,last_name ,department_number
FROM employee WHERE department_number NOT IN (401, 403) ; first_name last_name department_number Carol Kanieski John Stein
20
Arithmetic Operators Operator Definition ** exponentiation * Multiply
/ Divide MOD Modulos (remainders) + Add - Subtract
21
Arithmetic Functions Function Result ABS (arg) Absolute value
EXP (arg) Raises e to the power of arg e ** arg LOG (arg) Base 10 logarithm LN (arg) Base e (natural) logarithm SQRT (arg) Square root Arg is any constant or variable numeric argument.
22
Computed Values SELECT last_name ,first_name ,salary_amount/12
FROM employee WHERE department_number = 401 ORDER BY last_name ; last_name first_name salary_amount/12 Johnson Darlene Trader James
23
SELECTing System Variables
SELECT can be used to query the system for current information, including current: System DATE. System TIME. Logged-on USER. Current default DATABASE. Examples: SELECT DATE; Date 99/10/17 SELECT TIME; Time 09:15:37 SELECT USER; User SQL01 SELECT DATABASE; Database CUSTOMER_SERVICE
24
Literal, Constant, and Calculator Features
Character Literals You may add character literals to your SELECT statement: SELECT 'Employee' ,last_name ,first_name FROM employee ; Result Employee last_name first_name Employee Stein John Employee Kanieski Carol Employee Ryan Loretta Numeric Constants: You may also add numeric constants to your SELECT statement: SELECT 12345 ,last_name ,first_name FROM employee ; 12345 last_name first_name 12345 Stein John 12345 Kanieski Carol 12345 Ryan Loretta
25
We can use numeric expressions to do calculations:
Calculator Mode: We can use numeric expressions to do calculations: SELECT 2*250; Simple multiplication SELECT ; Uses greatest possible precision SELECT 10/3.000; Rounds off SELECT 10/6.000; Rounds up MOD Operator Example 7 ÷ 4 = 1 remainder of 3 Therefore 7 MOD 4 = 3
26
Arithmetic and Comparison Operation on NULL
Col A Operation Col B Result NULL NULL NULL NULL * NULL NULL / NULL NULL > NULL UNKNOWN < NULL UNKNOWN > = NULL UNKNOWN < = NULL UNKNOWN = NULL UNKNOWN <> NULL UNKNOWN NULL > NULL UNKNOWN NULL < NULL UNKNOWN NULL > = NULL UNKNOWN NULL < = NULL UNKNOWN NULL = NULL UNKNOWN NULL < > NULL UNKNOWN
27
Using NULL in a Select Use NULL in a SELECT statement, to define that a range of values either IS NULL or IS NOT NULL. To list employee numbers in this table with unknown extensions: SELECT employee_number FROM employee_phone WHERE extension IS NULL; employee_number 1025 1005
28
LIKE Operator The LIKE operator searches for patterns matching character data strings. Here are some examples using the LIKE operator: String pattern example: Meaning: LIKE 'JO%‘ begins with 'JO‘ LIKE '%JO%‘ contains 'JO' anywhere LIKE '__HN‘ contains 'HN' in 3rd and 4th position LIKE '%H_‘ contains 'H' in next to last position
29
LIKE Operator -- Partial String
CASESPECIFIC operator: SELECT first_name ,last_name FROM employee WHERE last_name (CASESPECIFIC) LIKE '%Ra%'; NOTE: In the default, the comparison is not case-specific. Use the Teradata extension (CASESPECIFIC) to force case-specific comparison.
30
LIKE Operator -- Using Quantifiers
There are three such quantifiers: ANY — any single condition must be met (OR logic) SOME — same as ANY ALL — all conditions must be met (AND logic) ANY and SOME are synonyms. Using LIKE ANY and LIKE SOME will give the same result.
31
Logical NOT Select the name and employee number of employees NOT in department 301. Solution for NOT Operator SELECT first_name ,last_name ,employee_number FROM employee WHERE department_number NOT = 301; Solution for NOT Condition SELECT first_name WHERE NOT (department_number = 301); Results first_name last_name employee_number Arnando Villegas James Trader Loretta Ryan Darlene Johnson
32
String Functions String Operator Description | |
| | Concatenates (combines) character strings together. SUBSTRING Obtains a section of a character string. String Functions INDEX Locates a character position in a string. TRIM Trims blanks from a string. UPPER Converts a string to uppercase.
33
SUBSTRING Function The SUBSTRING function is intermediate-level ANSI compliant. Teradata continues to support the alternate SUBSTR syntax as well. Examples SELECT SUBSTRING ('catalog' FROM 5 for 3); Result 'log' SELECT SUBSTR ('catalog', 5,3);
34
INDEX Function The INDEX function locates a character position in a string. SELECT INDEX ('cat', 't'); returns 3 SELECT INDEX ('Adams', 'a'); returns 1 SELECT INDEX ('dog', 'e'); returns 0
35
Introduction to Teradata SQL - II
DATE OPERATIONS Time Related Data Attributes and Functions FORMAT Phrase Attribute Functions Aggregate Operator Primary Key / Index Assential Set Operations CASE Expression /NULLIFZERO/COALESCE
36
DATE Data Type The Teradata DATE data type is used to store calendar dates representing year, month and day. It is stored internally as a four-byte integer. The Teradata database performs basic DATE handling functions including: Month-to-month conversions. Year-to-year conversions. Leap-year conversions. Dates prior to 1900. Dates after 2000. The database treats the DATE data type as an INTEGER value but does not permit invalid calendar dates.
37
The system encodes dates using the formula:
((YEAR ) * 10000) + MONTH * 100) + DAY For March 31, 1997 the calculation is: YEAR =( ) * = MONTH =(3 * 100)= 300 DAY = 31 DATE = For March 31, 2002 the calculation is: YEAR =( ) * = DATE =
38
DATE Arithmetic For January 1, 1900 the result is For dates before Jan 1, 1900, the integer calculation returns a negative number. This is only how the date is stored, not how it is represented in a query output. SQL permits us to perform arithmetic calculations on DATE. When the DATE keyword is SELECTed it is a system variable which represents the current date. (CURRENT_DATE may also be used and is the preferred ANSI standard). Syntax for finding The date 30 days from today is SELECT DATE + 30; Syntax for finding the date 1 year from now is SELECT DATE + 365; Exercise: Find out your age (in rounded years)?
39
Date Function ADD_MONTHS
The ADD_MONTHS function allows the addition of a specified number of months to an existing date, resulting in a new date. The format of the function is: ADD_MONTHS (date, n) where n is a number or an expression representing the number of months to be added to the date. The following examples demonstrate its usage. Query Result SELECT DATE; /* March 20, 2001 */ /03/20 SELECT ADD_MONTHS (DATE, 2) SELECT ADD_MONTHS (DATE, 12*14) SELECT ADD_MONTHS (DATE, -3) Note: The results of the ADD_MONTH function are always displayed in YYYY-MM-DD format.
40
Comparison of ADD_MONTHS and simple DATE arithmetic
Problem Show the date two month from today (March 20, 2001) using both ADD_MONTHS and simple arithmetic methods. SELECT DATE ,ADD_MONTHS(DATE, 2) ,DATE + 60; Date ADD_MONTHS (Date, 2) Date /03/20 01/05/19
41
Time Related Data Teradata supports two data types for holding time-related data: TIME (WITH ZONE) TIMESTAMP (WITH ZONE) TIMESTAMP is a data type which combines both DATE and TIME into a single data type. Both TIME and TIMESTAMP have a WITH ZONE option.
42
Time Data Description TIME TIME WITH ZONE Single column - representing 3 fields 6 Bytes Length: - Hour - Byteint - Min - Byteint - Secs. - Dec(8,6) Single column - representing 5 fields 6 Bytes TIME: - Hour - Byteint - Min - Byteint - Secs. - Dec(8,6) 2 Bytes ZONE: - Hour - Byteint - Minute - Byteint
43
Timestamp Data Description TIMESTAMP TIMESTAMP WITH ZONE Single column - representing 6 fields 10 Bytes Length: - Date = 4 Bytes - Time = 6 Bytes Single column - representing 8 fields 12 Bytes Length: - Date = 4 Bytes - Time = 6 Bytes - Zone = 2 Bytes
44
Interval Data Types SECOND
Interval data types represent a displacement between two points in time There are two general categories of INTERVAL data types: Year-Month Intervals Day-Time Intervals The following Year-Month interval data types are available: YEAR YEAR TO MONTH MONTH The following Day-Time interval data types are also available: DAY DAY TO HOUR DAY TO MINUTE DAY TO SECOND HOUR HOUR TO MINUTE HOUR TO SECOND MINUTE MINUTE TO SECOND SECOND
45
Data Conversions Using CAST
The CAST function allows you to convert a value or expression from one data type to another. For example: Numeric to Numeric Conversion SELECT CAST ( AS INTEGER); Result: 50500 (truncated), SELECT CAST ( AS DEC (6,0)); Result: (rounded). Decimal to Decimal Conversions SELECT CAST(6.74 AS DEC(2,1)); Result: 6.7 (Drops precision) SELECT CAST(6.75 AS DEC(2,1)); Result: 6.8 (Rounds up to even number) SELECT CAST(6.85 AS DEC(2,1)); Result: 6.8 (Rounds down to even number)
46
Character to Character Conversions
SELECT CAST (last-name AS CHAR (5)) FROM employee WHERE department_number = 401; last_name Johns Trade
47
Attributes and Functions
Attributes for columns and expressions AS Provides a new name for a column ANSI TITLE Provides a title for a column. Teradata Extension FORMAT Provides formatting for a column. Functions for columns and expressions CHARACTERS Count the number of characters in a column. Teradata Extension TRIM Trim the trailing or leading blanks or binary zeroes from a column. ANSI
48
AS: Naming a Column or Expression
SELECT last_name ,first_name ,salary_amount / 12 AS monthly_salary FROM employee WHERE department_number = 401 ORDER BY monthly_salary; last_name first_name monthly_salary Johnson Darlene Trader James
49
Teradata Extensions SELECT last_name ,first_name ,salary_amount / 12 (NAMED monthly_salary) FROM employee WHERE department_number = 401 ORDER BY monthly_salary ; TITLE Attribute ,salary_amount / 12 (TITLE 'MONTHLY // SALARY') ORDER BY 3; MONTHLY last_name first_name SALARY Johnson Darlene Trader James
50
CHARACTERS Function To find all employees who have more than five characters in their first name. Solution SELECT first_name FROM employee WHERE CHARACTERS (first_name) > 5; first_name Loretta Darlene Arnando
51
TRIM Function Use the TRIM function to suppress leading and/or trailing blanks in a CHAR column or leading and/or trailing binary zeroes in a BYTE or VARBYTE column. TRIM is most useful when performing string concatenations. There are several variations of the TRIM function: TRIM ([expression]) leading and trailing blanks/binary zeroes TRIM (BOTH FROM [expression]) leading and trailing blanks/binary zeroes TRIM (TRAILING FROM[expression]) trailing blanks/binary zeroes TRIM (LEADING FROM[expression]) leading blanks/binary zeroes Problem List the employees who have exactly four characters in their last name. The data type of last_name is CHAR(20).
52
Solution 1 SELECT first_name ,last_name (TITLE 'last') FROM employee
WHERE CHAR (TRIM (TRAILING FROM last_name)) = 4; Solution 2 SELECT first_name ,last_name(TITLE 'last') WHERE CHAR(TRIM(last_name))=4; Results of either solution: first_name last Loretta Ryan James Daly
53
Using TRIM with Concatenation Operator
The || (double pipe) symbol is the concatenation operator that creates a new string from the combination of the first string followed by the second. Example 1: Concatenating of literals without the TRIM function: SELECT ‘ Jones '||','||‘ Mary 'AS Name; Name Jones , Mary
54
FORMAT Phrase The FORMAT phrase can be used to format column output and override the default format. For example: SELECT salary_amount (FORMAT '$$$,$$9.99') FROM employee WHERE employee_number = 1004; salary_amount $36,300.00
55
Examples using the format (FORMAT '$$$,$$9.99)
Amount Display Notes ********* Mask cannot be applied - value covers format completely. $6,300.00 Dollar sign appears to left of the most significant digit. .63 $0.63 Leading zero, because the 9's in the mask force the display of a digit (or a zero, if there is not one). 3,336,300.00 ********** Fails, because this number is too large for the mask.
56
Problem: Management has decided to give employee 1004 a $1,000 raise and wants to know what percent the increase will be: SELECT (1000/salary_amount) * 100 (FORMAT 'ZZ9%')(TITLE 'Increase Percentage') FROM employee WHERE employee_number = 1004; Increase Percentage 3%
57
FORMAT Characters The following FORMAT characters are available:
$ Fixed or floating dollar sign. 9 Decimal digit (no zero suppress). Z Zero-suppressed decimal digit. , Comma. Inserted where specified. . Decimal point position. - Dash character. Inserted where specified. / Slash character. Inserted where specified. % Percent character. Inserted where specified. X Character data. Each X represents one character. G Graphic data. Each G represents one logical (double byte) character. B Blank data. Insert a space at this point. Examples FORMAT '999999' Data: Result: FORMAT 'ZZZZZ9' Data: Result: 8777 FORMAT ' ' Data: Result: FORMAT 'X(3)' Data: 'Smith' Result: Smi FORMAT '$$9.99' Data: Result: $85.65 FORMAT '999.99' Data: Result: FORMAT 'X(3)' Data: Result: Error
58
DATE Formats When dates are displayed as character strings, appropriate formats are applied. The Teradata default format is: YY/MM/DD The ANSI display format is: YYYY-MM-DD The recommended display format eliminates uncertainty about the century. For example, in the case of: 02/04/29 It is unclear whether this format represents April 29, 1902 or April 29, 2002.
59
FORMATing DATE in a SQL SELECT Statement
SELECT last_name ,first_name ,hire_date (FORMAT 'mmmBdd,Byyyy') FROM employee ORDER BY last_name; last_name first_name hire_date Johnson Darlene Oct 15, 1976 Kanieski Carol Feb 01, 1977 Ryan Loretta Oct 15, 1976 Stein John Oct 15, 1976 Trader James Jul 31, 1976 Villegas Arnando Jan 02, 1977
60
Extracting Portions of DATEs
SELECT last_name ,first_name ,birthdate (FORMAT 'mmdd') AS birthday ,birthdate AS whole_date FROM employee WHERE department_number = 401 ORDER BY3; last_name first_name birthday whole_date Rogers Frank /04/23 Brown Alan /08/09
61
SELECT last_name ,first_name ,birthdate MOD (FORMAT '9999') AS birthday ,birthdate AS whole_date FROM employee WHERE department_number = 401 ORDER BY3; last_name first_name birthday whole_date Johnson Darlene /04/23 Rogers Frank /04/23
62
Using the EXTRACT Function
Extracting From Current Date Query Result SELECT DATE; /* March 20,2001 */ /03/20 (Default format) SELECT EXTRACT(YEAR FROM DATE); SELECT EXTRACT(MONTH FROM DATE); SELECT EXTRACT(DAY FROM DATE); SELECT EXTRACT(YEAR FROM DATE + 365); 2002 SELECT EXTRACT(MONTH FROM DATE + 30); 04 SELECT EXTRACT(DAY FROM DATE + 12); Extracting From Current Time Query Result SELECT TIME; /* 2:42 PM */ :42:32 (Default format) SELECT EXTRACT(HOUR FROM TIME); SELECT EXTRACT(MINUTE FROM TIME);
63
Truncating CHARACTER Columns
SELECT last_name ,first_name first_name (FORMAT 'X') FROM employee WHERE last_name = 'Brown' ORDER BY3; last_name first_name first_name Brown Alan A Brown Allen A
64
Attribute Functions The functions available for attribute information are the following: TYPE TITLE FORMAT NAMED CHARACTERS Query Results SELECT DISTINCT TYPE (job_code) FROM job; INTEGER SELECT DISTINCT TITLE (job_code)FROM job; job_code SELECT DISTINCT FORMAT (job_code)FROM job; (10)9 SELECT DISTINCT NAMED (job_code)FROM job; job_code SELECT DISTINCT CHARACTERS(last_name) FROM employee;
65
Accidental Cartesian Products
SELECT employee.employee_number ,d.department_name FROM employee e INNER JOIN department d ON e.department_number = d.department_number; SELECT e.employee_number ON 3 = 3;
66
Aggregating Groups Aggregate Operators
Aggregate operators perform computations on values in a specified group. The five aggregate operators are: ANSI Standard Teradata Supported COUNT SUM AVG AVERAGE, AVG MAX MAXIMUM, MAX MIN MINIMUM, MIN AGGREGATE operations ignore NULLs and produce ONLY single-line answers.
67
Example SELECT COUNT ( salary_amount ) (TITLE 'COUNT') ,SUM ( salary_amount ) (TITLE 'SUM SALARY') ,AVG ( salary_amount ) (TITLE 'AVG SALARY') ,MAX ( salary_amount ) (TITLE 'MAX SALARY') ,MIN ( salary_amount ) (TITLE 'MIN SALARY') FROM employee ; Result COUNT SUM SALARY AVG SALARY MAX SALARY MIN SALARY
68
GROUP BY and the WHERE Clause
The WHERE clause eliminates some rows before GROUP BY puts them into desired groupings. Problem Compute total salaries by department for departments 401 and 403. Solution SELECT department_number ,SUM (salary_amount) FROM employee WHERE department_number IN (401, 403) GROUP BY department_number ; department_number Sum (salary_amount)
69
GROUP BY and HAVING Condition
HAVING is just like WHERE , except that it applies to groups rather than rows. HAVING qualifies and selects only those groups that satisfy a conditional expression. Problem Determine which departments have average salaries of less than $36,000. Generate the report using the HAVING clause: SELECT department_number AS DEPT ,COUNT (*) AS #_EMPS ,CAST ( SUM (salary_amount) AS FORMAT 'zz,zzz,zz9.99') AS TOTAL ,CAST ( MAX (salary_amount) AS FORMAT 'zz,zzz,zz9.99') AS HIGHEST ,CAST ( MIN (salary_amount) AS FORMAT 'zz,zzz,zz9.99') AS LOWEST ,CAST ( AVG (salary_amount) AS FORMAT 'zz,zzz,zz9.99') AS MEAN FROM employee GROUP BY department_number HAVING AVG (salary_amount) < ; DEPT #_EMPS TOTAL HIGHEST LOWEST MEAN , , , ,082.14
70
GROUP BY Summary Here is the order of evaluation within a SQL statement if all four clauses are present: WHERE Eliminates some or all rows immediately based on condition. Only rows which satisfy a WHERE condition are eligible for inclusion in groups. GROUP BY Puts qualified rows into desired groupings. HAVING Eliminates some (or all) of the groupings based on condition. ORDER BY Sorts final groups for output. (ORDER BY is not implied by GROUP BY)
71
Primary Key vs. Primary Index
Primary Key (PK) - is defined as one or more columns used to uniquely identify each row in a table. PKs are used in conjunction with foreign keys to define the important column relationships in a database. PKs are always unique and cannot be null. PKs are not known to the Teradata RDBMS as such. The Teradata RDBMS implements a primary key as a unique index. Primary Index - is defined as one or more columns used to distribute and locate rows in a table. Choice of primary index will affect distribution, access and performance. Oftentimes, but not always, the Primary Index and Primary Key are the same. Indexes (primary or secondary) may be used to enforce uniqueness (as in a PK) or to improve access. They may be unique or non-unique.
72
Every table must have exactly one primary index.
Indexes may be: Primary Secondary UNIQUE UPI USI NON-UNIQUE NUPI NUSI Every table must have exactly one primary index.
73
Between 0-N where N = any number > 0
#AMPS #ROWS UPI 1 0 or 1 NUPI Between 0-N where N = any number > 0 USI 2 Between 0-1 NUSI All Between 0-N Full table scan
74
INSERT INSERT allows you to add a new row to a table. Example
There are two types of insert: Insert a new employee into the employee table: INSERT INTO employee VALUES (1210, NULL, 401, , 'Smith', 'James', , , 41000); Insert a new employee with only partial data: INSERT INTO employee (last_name, first_name, hire_date,birthday, salary_amount, employee_number) VALUES ('Garcia', 'Maria', , , , 1291);
75
INSERT SELECT Use INSERT SELECT to copy rows from one table to another. The syntax is as follows: INSERT INTO target_table SELECT * FROM source_table; Simple INSERT SELECT: INSERT INTO emp_copy SELECT * FROM emp; Assumes: emp and emp_copy have same definition. a complete replica of emp is desired.
76
UPDATE UPDATE allows to modify one or many columns of one or many rows in a single table. The WHERE condition can include: Columns from the table being updated. Joins with columns from other tables. Subqueries. UPDATE Using Subqueries or Joins Problem Update the employee table to give everyone in all support departments a 10% raise. Department numbers for all of the support departments are not known.
77
Solution 1 Using Subquery UPDATE employee SET salary_amount=salary_amount *1.10 WHERE department_number IN (SELECT department_number FROM department WHERE department_name LIKE '%Support%'); Solution 2 Using Join: UPDATE employee SET salary_amount=salary_amount * 1.10 WHERE employee.department_number = department.department_number AND department_name LIKE '%Support%';
78
DELETE DELETE allows you to delete rows from a single table. If no WHERE clause is specified, then all rows are deleted. The WHERE condition can reference: Column values in the target table. Column values based on a subquery against another table. Column values based on a join with another table. Problem Remove all employees in department 301 from the employee table. DELETE FROM employee WHERE department_number = 301;
79
DELETE Using Subqueries or Joins
Problem Remove all employees assigned to a temporary department for which the department name is "Temp". Solution 1 Using Subquery: DELETE FROM employee WHERE department_number IN (SELECT department_number FROM department WHERE department_name ='Temp'); Solution 2 Using Join: WHERE employee.department_number=department.department_number AND department.department_name='Temp';
80
INTERSECT, UNION and EXCEPT.
Set Operations Set Operators INTERSECT, UNION and EXCEPT. INTERSECT The INTERSECT operator returns rows from multiple sets which share some criteria in common. UNION The UNION operator returns all rows from multiple sets, displaying duplicate rows only once. EXCEPT The EXCEPT operator subtracts the contents of one set from the contents of another.
81
INTERSECT Operator Problem
Create a list all department managers who are assigned subordinate employees. Note that not all department managers have subordinates and not all managers with subordinates are department managers. Solution SELECT manager_employee_number FROM employee INTERSECT FROM department ORDER BY 1 ; Results manager_employee_number 801 1003 1005 1011 1017 1019 1025
82
EXCEPT Operator synonym for EXCEPT is MINUS Problem
To list all department managers who do not have subordinates. Solution SELECT manager_employee_number FROM department EXCEPT FROM employee ORDER BY 1 ; Result manager_employee_number 1016 1099
83
UNION Operator Problem
Show manager 1019 identifying him as the manager, show his employees and identify each of them as an employee. Solution SELECT first_name ,last_name ,'employee‘ (TITLE 'employee//type') FROM employee WHERE manager_employee_number = 1019 UNION ,' manager ‘ WHERE employee_number = 1019 ORDER BY 2 ; Results Employee first_name last_name type Carol Kanieski employee Ron Kubic manager John Stein employee
95
Introduction to Teradata SQL - III
MACROS VIEWS
96
Macro A macro is a Teradata extension to ANSI SQL that contains prewritten SQL statements. The actual text of the macro is stored in a global repository called the Data Dictionary (DD). Macros are database objects and thus they belong to a specified user or database. They may contain one or more SQL statements. CREATE MACRO Example Create a macro to generate a birthday list for department 201: CREATE MACRO birthday_list AS (SELECT last_name ,first_name ,birthdate FROM employee WHERE department_number =201 ORDER BY birthdate;);
97
EXECUTE Macro To execute a macro, simply precede its name with the EXEC command. EXEC birthday_list; last_name first_name birthdate Morrissey Jim /04/29 Short Michael /07/07 DROP Macro Use the DROP MACRO command to delete a macro. DROP MACRO birthday_list;
98
REPLACE Macro Need to resubmit the entire contents of a macro to modify it. REPLACE MACRO birthday_list AS (SELECT last_name ,first_name ,birthdate FROM employee WHERE department_number = 201 ORDER BY birthdate, last_name;);
99
Parameterized Macros Macros contain one or more prewritten SQL statements that are stored in the Teradata Data Dictionary. They can be executed from any viable SQL front-end, including: Queryman. BTEQ. Preprocessor. CLI. LOGON Startup. Another macro. Other key points to note about Macros: Macros are a Teradata extension to SQL. Macros can only be executed with the EXEC privilege. Macros can provide column level security. NOTE: If a user has EXEC privileges, it doesn't matter whether or not he has privileges for the underlying tables or views that the macro uses.
100
Simple Parameterized Macros
Parameterized macros allow substitutable variables. Values for these variables are supplied at runtime. Example CREATE MACRO dept_list (dept INTEGER)AS( SELECT last_name FROM employee WHERE department_number = :dept; ); To Execute EXEC dept_list (301);
101
Macros with Multiple Parameters
Macros may have more than one parameter. Each name and its associated type are separated by a comma from the next name and its associated type. The order is important. The first value in the EXEC of the macro will be associated with the first value in the parameter list. The second value in the EXEC is associated with the second value in the parameter list, and so on. Example 1 CREATE MACRO emp_check (dept INTEGER ,sal_amt DEC(9,2)) AS (SELECT employee_number from employee WHERE department_number = :dept AND salary_amount < :sal_amt;) ; To Execute EXEC emp_check (301, 50000);
102
Using a Parameterized Macro to Insert Data
CREATE MACRO new_dept ( dept INTEGER ,budget DEC(10,2) DEFAULT 0 ,name CHAR(30) ,mgr INTEGER) AS ( INSERT INTO department ( department_number , department_name , budget_amount , manager_employee_number) VALUES ( :dept , :name , :budget , :mgr ) ; SELECT department_number (TITLE ‘Number’) ,department_name (TITLE ‘Name’) ,budget_amount (TITLE ‘Budget’) ,manager_employee_number (TITLE ‘Manager’) FROM department WHERE department_number = :dept; );
103
Views A view is like a 'window' into a table.
It provides customized access to base tables by: Restricting which columns are visible from the base table. Restricting which rows are visible from the base table. Combining columns and rows from several base tables. Creating and Using Views Problem Create a view of the employees in department 403 to use for both read and update. Limit the view to an employee’s number, last name, and salary.
104
Solution CREATE VIEW emp_403 AS SELECT employee_number ,last_name ,salary_amount FROM employee WHERE department_number = 403; To Read From This View SELECT * FROM emp_403; Results employee_number last_name salary_amount 1009 Lombardo 1007 Villegas 1012 Hopkins 1005 Ryan 1024 Brown 1020 Charles
105
What is a Join View? A Join View consists of columns from more than one table. Example Create a Join View of the employee and call_employee tables for call dispatch use. CREATE VIEW employee_call AS SELECT employee.employee_number ,last_name ,first_name ,call_number ,call_status_code ,assigned_date ,assigned_time ,finished_date ,finished_time FROM employee INNER JOIN call_employee ON call_employee.employee_number = employee.employee_number;
106
Replacing a View REPLACE VIEW shortcut (emp, dept, last, first, sal) AS SELECT employee_number ,department_number ,last_name ,first_name ,salary_amount FROM employee WHERE department_number = 301;
107
Aggregate Views You may create a view that summarizes information by using aggregates. CREATE VIEW deptsals AS SELECT department_number AS department ,SUM (salary_amount)AS salary_total ,AVG (salary_amount)AS salary_average ,MAX (salary_amount)AS salary_max ,MIN (salary_amount) AS salary_min FROM employee GROUP BY department_number; NOTE: Aggregate and derived columns must be assigned names.
108
Joins on Views with Aggregates
Problem: Create a view showing the the aggregate salaries by department number. Solution CREATE VIEW dept_salaries (deptnum, salaries) AS SELECT department_number, SUM(salary_amount) FROM employee GROUP BY 1;
109
Problem Show by department name which departments have aggregate salaries greater than $100,000. Solution SELECT deptnum ,department_name ,salaries FROM dept_salaries ds INNER JOIN department de ON ds.deptnum = de.department_number WHERE salaries > ORDER BY 1; Results deptnum department_name salaries research and development customer support education marketing sales
110
Views WITH CHECK OPTION
In a view, the WITH CHECK OPTION limits the abilities of users with update and insert privileges on the view. A user may not insert or update a row if the resulting row will violate the constraints of the WHERE clause. For example, let's replace a view using the WITH CHECK OPTION: REPLACE VIEW dept_budget AS SELECT department_number AS Dept ,department_name AS Name ,budget_amount AS Budget ,manager_employee_number AS Mgr FROM department WHERE Budget <= WITH CHECK OPTION;
111
Restrictions and Advantages With Views
Restrictions When Using Views An index cannot be created on a view. A view cannot contain an ORDER BY clause. Derived and aggregated columns must be assigned a name. A view cannot be used to UPDATE if it contains: Data from more than one table (Join View). The same column twice. Derived columns. A DISTINCT clause. A GROUP BY clause. Advantages When Using Views An additional level of security. Help in controlling read and update privileges. Simplify end-user's access to data. Are unaffected if a column is added to a table; and Are unaffected if a column is dropped, unless the dropped column is referenced by the view.
112
THANK YOU
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.