Teradata set operators provide ways to combine similar datasets from two or more queries into a single dataset. There are many SET operators available in teradata and they work in similar way as the mathematical SET operations. These can also be used to compare 2 tables.
Some of the available operators in Teradata.
Table 1
CREATE MULTISET VOLATILE TABLE setoperators_1(
id INTEGER,
name VARCHAR(100)
)
PRIMARY INDEX(id)
ON COMMIT PRESERVE ROWS;
Table 2
CREATE MULTISET VOLATILE TABLE setoperators_2(
id INTEGER,
name VARCHAR(100)
)
PRIMARY INDEX(id)
ON COMMIT PRESERVE ROWS;
Table 1:
INSERT INTO setoperators_1 VALUES(1,'Teradata');
INSERT INTO setoperators_1 VALUES(1,'Teradata');
INSERT INTO setoperators_1 VALUES(2,'Database');
INSERT INTO setoperators_1 VALUES(3,'Oracle');
INSERT INTO setoperators_1 VALUES(4,'Vertica');
INSERT INTO setoperators_1 VALUES(4,'Vertica');
Table 2:
INSERT INTO setoperators_2 VALUES(1,'Teradata');
INSERT INTO setoperators_2 VALUES(1,'Teradata');
INSERT INTO setoperators_2 VALUES(2,'Database');
INSERT INTO setoperators_2 VALUES(5,'DB2');
INSERT INTO setoperators_2 VALUES(6,'MYSQL');
SELECT id,name from setoperators_1
UNION
SELECT id,name from setoperators_2;
Output:
id name
--- -------------
1 Teradata
2 Database
3 Oracle
4 Vertica
5 DB2
6 MYSQL
→ Problem with UNION in Teradata
SELECT 'A' FROM setoperators_2
UNION
SELECT 'AB' FROM setoperators_2;
Output:
'A'
---
A
SELECT CAST('A' AS VARCHAR(10)) FROM setoperators_2
UNION
SELECT CAST('AB' AS VARCHAR(10)) FROM setoperators_2;
Output:
'A'
----------
A
AB
SELECT id,name from setoperators_1
UNION ALL
SELECT id,name from setoperators_2;
Output:
id name
--- -------------
3 Oracle
1 Teradata
1 Teradata
4 Vertica
4 Vertica
2 Database
5 DB2
1 Teradata
1 Teradata
6 MYSQL
2 Database
SELECT id,name from setoperators_1
INTERSECT
SELECT id,name from setoperators_2;
Output:
id name
--- -------------
1 Teradata
2 Database
SELECT id,name from setoperators_1
INTERSECT ALL
SELECT id,name from setoperators_2;
Output:
id name
--- -------------
1 Teradata
1 Teradata
2 Database
Example 1:
SELECT id,name from setoperators_1
MINUS
SELECT id,name from setoperators_2;
Output:
id name
--- -------------
3 Oracle
4 Vertica
Example 2:
SELECT id,name from setoperators_2
MINUS
SELECT id,name from setoperators_1;
Output:
id name
--- -------------
5 DB2
6 MYSQL
Example 1:
SELECT id,name from setoperators_1
MINUS ALL
SELECT id,name from setoperators_2;
Output:
id name
--- -------------
3 Oracle
4 Vertica
4 Vertica