20.3. DuckDB Macros #

This section describes how to create and delete DuckDB macros using the axe.raw_query stored procedure. A macro is a shortcut with a name for an expression or an analytical query. Once created, the macro can be used in the subsequent queries.

20.3.1. Creating a DuckDB Macro #

Required privileges: The Postgres Pro AXE administrator.

For more information about access management, refer to Chapter 12.

Execute the following command on the Postgres Pro AXE server:

  SELECT axe.raw_query('CREATE [OR REPLACE] MACRO [IF NOT EXISTS] macro_name(parameters) AS expression');

Where:

  • OR REPLACE: Overwrites an existing macro with the same name.

    Optional clause.

  • IF NOT EXISTS: Does not create the macro if a macro with the same name already exists.

    Optional clause.

  • macro_name: The name of the macro that must be created.

  • parameters: The comma-separated list of parameters that the macro must accept. Each parameter can have a type (e.g., a INTEGER) and a default value (e.g., b := 5).

  • AS: Returns a single value. To return a table instead, use the AS TABLE clause.

  • expression: The expression or analytical query that the macro must expand to.

Example 20.3. Creating and Using DuckDB Macros

Creating a macro that converts a string to a date:

  SELECT axe.raw_query('CREATE OR REPLACE MACRO to_date(d, fmt) AS strptime(d, fmt)::DATE');

Using the macro in a query:

  SELECT * FROM axe.query($$ SELECT to_date('2026-01-15', '%Y-%m-%d') $$) r;

  2026-01-15

Creating a macro with a default parameter:

  SELECT axe.raw_query('CREATE MACRO add_default(a, b := 5) AS a + b');

Using the macro with and without the default parameter:

  SELECT * FROM axe.query($$ SELECT add_default(10) AS x $$) r;

  15

  SELECT * FROM axe.query($$ SELECT add_default(10, 20) AS x $$) r;

  30

Creating a table macro:

  SELECT axe.raw_query('CREATE MACRO dynamic_table(col1_value, col2_value) AS TABLE SELECT col1_value AS column1, col2_value AS column2');

Using the table macro in a query:

  SELECT * FROM axe.query($$ SELECT * FROM dynamic_table('Hello', 'World') $$) r;

   column1 | column2
  ---------+---------
   Hello   | World

20.3.2. Deleting a DuckDB Macro #

Required privileges: The Postgres Pro AXE administrator.

For more information about access management, refer to Chapter 12.

Execute the following command on the Postgres Pro AXE server:

  SELECT axe.raw_query('DROP MACRO [TABLE] macro_name');

Where macro_name is the name of the macro that must be deleted.

To delete a table macro, specify the TABLE keyword.

FAQ