W3. SQL Union Flashcards

1
Q

Q: What does the SQL UNION operator do?

A

A: It combines the result sets of two or more SELECT statements into a single result set.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Q: What requirements must be met for UNION to work?

A

A: Each SELECT statement must have the same number of columns, with similar data types, and the columns must be in the same order.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Q: Write the syntax for a basic UNION.

A

SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Q: What does UNION ALL do differently than UNION?

A

A: UNION ALL includes duplicate values, whereas UNION only returns distinct values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Q: Write the syntax for UNION ALL.

A

SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Q: Write a query to return distinct cities from both “Customers” and “Suppliers”.

A

SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Q: How can you modify a UNION to include duplicate values?

A

A: Use UNION ALL instead of UNION.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Q: Write a query to return German cities (distinct) from both “Customers” and “Suppliers”.

A

SELECT City, Country FROM Customers
WHERE Country = ‘Germany’
UNION
SELECT City, Country FROM Suppliers
WHERE Country = ‘Germany’
ORDER BY City;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Q: Write a query to list all customers and suppliers, labeling each as “Customer” or “Supplier”.

A

SELECT ‘Customer’ AS Type, ContactName, City, Country
FROM Customers
UNION
SELECT ‘Supplier’, ContactName, City, Country
FROM Suppliers;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Q: What is the purpose of using AS Type in the last example?

A

A: It creates an alias, Type, to indicate whether each record is a “Customer” or a “Supplier”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly