
- Teradata Tutorial
- Teradata - Home
- Teradata Basics
- Teradata - Introduction
- Teradata - Installation
- Teradata - Architecture
- Teradata - Relational Concepts
- Teradata - Data Types
- Teradata - Tables
- Teradata - Data Manipulation
- Teradata - SELECT Statement
- Logical & Conditional Operators
- Teradata - SET Operators
- Teradata - String Manipulation
- Teradata - Date/Time Functions
- Teradata - Built-in Functions
- Teradata - Aggregate Functions
- Teradata - CASE & COALESCE
- Teradata - Primary Index
- Teradata - Joins
- Teradata - SubQueries
- Teradata Advanced
- Teradata - Table Types
- Teradata - Space Concepts
- Teradata - Secondary Index
- Teradata - Statistics
- Teradata - Compression
- Teradata - Explain
- Teradata - Hashing Algorithm
- Teradata - Join Index
- Teradata - Views
- Teradata - Macros
- Teradata - Stored Procedure
- Teradata - JOIN Strategies
- Teradata - Partitioned Primary Index
- Teradata - OLAP Functions
- Teradata - Data Protection
- Teradata - User Management
- Teradata - Performance Tuning
- Teradata - FastLoad
- Teradata - MultiLoad
- Teradata - FastExport
- Teradata - BTEQ
- Teradata Useful Resources
- Teradata - Questions & Answers
- Teradata - Quick Guide
- Teradata - Useful Resources
- Teradata - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Teradata - SubQueries
A subquery returns records from one table based on the values from another table. It is a SELECT query within another query. The SELECT query called as inner query is executed first and the result is used by the outer query. Some of its salient features are −
A query can have multiple subqueries and subqueries may contain another subquery.
Subqueries doesn't return duplicate records.
If subquery returns only one value, you can use = operator to use it with the outer query. If it returns multiple values you can use IN or NOT IN.
Syntax
Following is the generic syntax of subqueries.
SELECT col1, col2, col3,… FROM Outer Table WHERE col1 OPERATOR ( Inner SELECT Query);
Example
Consider the following Salary table.
EmployeeNo | Gross | Deduction | NetPay |
---|---|---|---|
101 | 40,000 | 4,000 | 36,000 |
102 | 80,000 | 6,000 | 74,000 |
103 | 90,000 | 7,000 | 83,000 |
104 | 75,000 | 5,000 | 70,000 |
The following query identifies the employee number with highest salary. The inner SELECT performs the aggregation function to return the maximum NetPay value and the outer SELECT query uses this value to return the employee record with this value.
SELECT EmployeeNo, NetPay FROM Salary WHERE NetPay = (SELECT MAX(NetPay) FROM Salary);
When this query is executed, it produces the following output.
*** Query completed. One row found. 2 columns returned. *** Total elapsed time was 1 second. EmployeeNo NetPay ----------- ----------- 103 83000