Union

2 snippets across 2 stacks — Python, SQL

Also written as Union · union all

PYPython

typing Module Essentials

PY · Common Standard Library
syntax
from typing import Optional, Union, TypeVar, Generic
example
from typing import TypeVar, Generic

T = TypeVar("T")

class Stack(Generic[T]):
    def __init__(self) -> None:
        self._items: list[T] = []

    def push(self, item: T) -> None:
        self._items.append(item)

    def pop(self) -> T:
        return self._items.pop()

stack = Stack[int]()
stack.push(42)
print(stack.pop())
output
42

Note Since 3.10, use X | Y instead of Union[X, Y]. Since 3.12, use the type parameter syntax: class Stack[T]: instead of TypeVar + Generic.

SQLSQL

UNION / UNION ALL

SQL · Advanced
syntax
SELECT columns FROM table1
UNION [ALL]
SELECT columns FROM table2;
example
SELECT first_name, email, 'customer' AS source
FROM customers
UNION ALL
SELECT first_name, email, 'employee' AS source
FROM employees;
output
-- Combined list of customers and employees

Note UNION removes duplicates (slower, requires sorting). UNION ALL keeps all rows (faster). Use UNION ALL unless you specifically need deduplication. Both queries must have the same number of columns with compatible types.