# Macros

Altertable catalogs support scalar and table macros created with standard `CREATE MACRO` syntax. Macros are stored in catalog metadata and can be referenced from queries, view definitions, and sort-order expressions.

Macros participate in [time travel](/docs/lakehouse/features/time-travel.md) — querying a catalog at an earlier snapshot reflects the macros that existed at that point.

Run the statements below through Altertable's [SQL engine](/docs/lakehouse/sql-engine.md) against an [Altertable catalog](/docs/lakehouse.md) you own.

## Scalar macros

Scalar macros return a single value:

```sql
CREATE MACRO margin_pct(price, cost) AS (price - cost) / price * 100;

SELECT margin_pct(49.99, 31.50);
```

## Table macros

Table macros return a table:

```sql
CREATE MACRO high_stock_skus(min_qty) AS TABLE
  SELECT sku, warehouse_id, on_hand
  FROM my_catalog.main.inventory_levels
  WHERE on_hand >= min_qty;

SELECT * FROM high_stock_skus(500);
```

## Default parameters

Macros can define default values for parameters:

```sql
CREATE MACRO apply_discount(price, pct := 10) AS price * (1 - pct / 100.0);

SELECT apply_discount(120.00);
```

## Typed parameters

Macros can specify types for their parameters:

```sql
CREATE MACRO pallet_count(units INTEGER, units_per_pallet INTEGER) AS ceil(units / units_per_pallet);
```

## Drop macros

Drop scalar macros with `DROP MACRO` and table macros with `DROP MACRO TABLE`:

```sql
DROP MACRO margin_pct;
DROP MACRO TABLE high_stock_skus;
```

## When to use macros

Use macros to centralize repeated expressions — date bucketing, unit conversions, or shared filter logic — so queries stay readable and changes propagate from one definition.

For sort orders and views that depend on a macro, define the macro before referencing it in `SET SORTED BY` or `CREATE VIEW`.

## Learn more

- **[Sorted Tables](/docs/lakehouse/features/sorted-tables.md)**: Use macros in expression-based sort keys
- **[Views](/docs/lakehouse/features/views.md)**: Encapsulate queries behind stable names
- **[SQL Engine](/docs/lakehouse/sql-engine.md)**: DuckDB dialect and federated queries