SQL
Syntax
<div id="rrdiagram"></div>  
Macros allow you to create shortcuts for combinations of expressions.  
```sql
CREATE MACRO add(a) AS a + b;
```  
```console
Binder Error: Referenced column "b" not found in FROM clause!
```  
This works:  
```sql
CREATE MACRO add(a, b) AS a + b;
```  
Usage example:  
```sql
SELECT add(1, 2) AS x;
```  
| x |
|--:|
| 3 |  
However, this fails:  
```sql
SELECT add('hello', 3);
```  
```console
Binder Error: Could not choose a best candidate function for the function call "+(STRING_LITERAL, INTEGER_LITERAL)". In order to select one, please add explicit type casts.
Candidate functions:
+(DATE, INTEGER) -> DATE
+(INTEGER, INTEGER) -> INTEGER
```  
Macros can have default parameters.
Unlike some languages, default parameters must be named
when the macro is invoked.  
`b` is a default parameter:  
```sql
CREATE MACRO add_default(a, b := 5) AS a + b;
```  
The following will result in 42:  
```sql
SELECT add_default(37);
```  
The following will throw an error:  
```sql
SELECT add_default(40, 2);
```  
```console
Binder Error: Macro function 'add_default(a)' requires a single positional argument, but 2 positional arguments were provided.
```  
Default parameters must used by assigning them like the following:  
```sql
SELECT add_default(40, b := 2) AS x;
```  
| x  |
|---:|
| 42 |  
However, the following fails:  
```sql
SELECT add_default(b := 2, 40);
```  
```console
Binder Error: Positional parameters cannot come after parameters with a default value!
```  
The order of default parameters does not matter:  
```sql
CREATE MACRO triple_add(a, b := 5, c := 10) AS a + b + c;
```  
```sql
SELECT triple_add(40, c := 1, b := 1) AS x;
```  
| x  |
|---:|
| 42 |  
When macros are used, they are expanded (i.e., replaced with the original expression), and the parameters within the expanded expression are replaced with the supplied arguments. Step by step:  
The `add` macro we defined above is used in a query:  
```sql
SELECT add(40, 2) AS x;
```  
Internally, add is replaced with its definition of `a + b`:  
```sql
SELECT a + b; AS x
```  
Then, the parameters are replaced by the supplied arguments:  
```sql
SELECT 40 + 2 AS x;
```