---
title: Create and manage NRQL macros
source: https://docs.newrelic.com/docs/nrql/nrql-macros/create-manage-nrql-macros
---

Before you create a macro, review the [macro permissions](https://docs.newrelic.com/docs/nrql/nrql-macros/nrql-macros-overview/#macro-permissions) and the naming and expression rules below. A macro that doesn't follow these rules fails validation when you try to save it.

## Macro rules and limitations [#macro-rules]

> #### ⚠️ IMPORTANT
>
> Macros are visible to all users in your organization. Don't include sensitive or account-specific information when you create or update a macro.

**Naming rules**

Macro names must follow these rules:

-   Must be unique within the organization
-   Must not be a non-negative integer, such as `3`
-   Must not contain the `.` character
-   Must be 500 characters or less
-   Must not start with the `$` character
-   Must not be wrapped within backticks at creation time.
-   If a macro name contains special characters, it must be wrapped in backticks. For example `` $`my#Macro` ``.

**Expression rules**

Macro expressions must follow these rules:

-   Must be a valid NRQL expression or list of expressions

-   Must be 3,000 characters or less

-   Must be an expression, not a clause. For example, `count(*)` is valid, but `SELECT count(*)` isn't valid.

-   Must be a subquery wrapped in parentheses, not a standalone query. For example, `(FROM Transaction SELECT uniques(userId))` is valid, but `FROM Transaction SELECT uniques(userId)` isn't valid.

-   Must return specific attributes, not an attribute list containing `*`

    Valid expression examples:

-   `count(*)`

-   `(1, 2, 3)`

-   `(FROM Transaction SELECT uniques(userId))`

**Limitations**

NRQL macros have the following limitations:

-   **Alerts**: Macros aren't supported in alert conditions.
-   **Autocomplete**: The query builder doesn't suggest macros or use macro expressions to refine suggestions.
-   **Template variables**: You can't use template variables within macros.
-   **Nested macros**: Macros can't be nested. A macro's expression can't contain a reference to another macro.
-   **Region-specific**: Macros are region-specific and can only be used within your organization's primary region.
-   **Time clauses**: Clauses related to time, including `TIMESERIES`, `PREDICT`, `BY`, `USING`, `SINCE`, `UNTIL`, and `COMPARE WITH`, don't support macros.

## Access macros [#macros-access]

In the New Relic platform, go to **Administration > NRQL Macros**. From this page, you can view, create, edit, and delete macros.

## Create a macro [#create-macro]

### UI

From the **NRQL Macros** page, create a macro by providing a unique name and an expression. Follow the [naming](#macro-naming-rules) and [expression](#macro-expression-rules) rules. Don't prefix the name with the `$` character. For example, to save a `WHERE` clause condition, enter `appName = 'ProductionApp' AND environment = 'prod'` without the `WHERE` keyword.

After you create a macro, it appears in the **NRQL Macros** list. You can use it in any NRQL query throughout New Relic.

### NerdGraph

You can also create, update, and query macros programmatically using the [NerdGraph API](https://docs.newrelic.com/docs/apis/nerdgraph/get-started/introduction-new-relic-nerdgraph/). Before creating or updating macros, review the [naming rules](#macro-naming-rules), [expression rules](#macro-expression-rules), and [limitations](#macro-limitations).

To get started, go to the [NerdGraph API explorer](https://one.newrelic.com/nerdgraph-graphiql). If you need help using the NerdGraph API explorer, refer to the [NerdGraph API explorer tutorial](https://docs.newrelic.com/docs/apis/nerdgraph/get-started/nerdgraph-explorer/).

Use the `entityManagementCreateNrqlMacro` mutation:

````graphql
mutation CreateMacro($name: String!, $expression: String!, $orgId: ID!) {
  entityManagementCreateNrqlMacro(
    nrqlMacroEntity: {
      expression: $expression
      name: $name
      scope: { type: ORGANIZATION, id: $orgId }
    }
  ) {
    entity {
      id
      name
      expression
    }
  }
}
```

Example variables:

```json
{
  "name": "prod_filter",
  "expression": "(appName = 'ProductionApp' AND environment = 'prod')",
  "orgId": "your-organization-id"
}
```

To find your organization ID, refer to [Find your organization or macro ID](#find-ids).

````

## Use a macro in a query [#use-macro]

To use a macro in your NRQL queries, type `$` followed by the macro name in the query builder. For example, suppose you have a macro named `prod_filter` with the expression `appName = 'ProductionApp' AND environment = 'prod'`. You can use it in a query like this:

```sql
SELECT count(*) FROM Transaction WHERE $prod_filter SINCE 1 hour ago
```

When the query executes, New Relic replaces the macro with its expression:

```sql
SELECT count(*) FROM Transaction WHERE appName = 'ProductionApp' AND environment = 'prod' SINCE 1 hour ago
```

> #### 💡 TIP
>
> Wrap macro names containing special characters in backticks at query time. For example: `` $`my#Macro` ``.

> #### ⚠️ IMPORTANT
>
> Macros are inlined prior to execution, which affects binary operator precedence. For example, a macro named `five` defined as `1 + 4` and used as `$five * 3` evaluates to `13`, not `15`, because the expression becomes `1 + 4 * 3`. To avoid this, wrap the expression in parentheses when you define the macro, as in `(1 + 4)`, or wrap the macro in parentheses when you use it, as in `($five) * 3`. Either approach correctly evaluates to `15`.

The following examples show macros solving common query problems:

**Example: Simplify a query**

A query with multiple conditions, like this one, can be difficult to read and maintain:

````sql
SELECT * FROM Log WHERE entityGuid = '...' AND appId NOT IN (...) AND ...
```

Save the conditions after `WHERE` as a macro named `macro1`, and the query simplifies to:

```sql
SELECT * FROM Log WHERE $macro1
```

````

**Example: Update multiple dashboard widgets from one place**

Dashboards with many widgets often share repeated query logic. For example, most widgets in a dashboard might use:

````sql
SELECT count(*) FROM Transaction WHERE http.statusCode NOT IN (400, 404)
```

If you save the `WHERE` condition as a macro named `macro2`, each widget's query looks like:

```sql
SELECT count(*) FROM Transaction WHERE $macro2
```

To exclude a test app from every widget, update the `macro2` expression once, from `http.statusCode NOT IN (400, 404)` to `http.statusCode NOT IN (400, 404) AND appId NOT IN (12345)`. Every widget that uses `$macro2` reflects the change, and you don't have to edit each widget individually.

````

**Example: Solve the attribute alias problem**

Data from different agents doesn't always use the same attribute name for the same concept. A host name, for example, can be ingested as `host.name`, `hostName`, or `host_name` depending on the source.

Save a macro named `host_alias` with the expression:

````sql
(host.name OR hostName OR host_name)
```

Then reference it in your queries:

```sql
FROM Log SELECT $host_alias
```

If another alias, such as `host-name`, comes up later, update the `host_alias` macro once and every query that uses it picks up the change.

````

## Manage macros [#manage-macros]

### Edit a macro [#edit-macro]

#### UI

From the **NRQL Macros** page, select the macro and update its expression, following the [expression rules](#macro-expression-rules).

#### NerdGraph

You can also update a macro's expression programmatically using [NerdGraph](https://docs.newrelic.com/docs/apis/nerdgraph/get-started/introduction-new-relic-nerdgraph/). Review the [expression rules](#macro-expression-rules) before you update it.

Use the `entityManagementUpdateNrqlMacro` mutation.

````graphql
mutation UpdateMacro($expression: String!, $macroId: ID!) {
  entityManagementUpdateNrqlMacro(
    id: $macroId
    nrqlMacroEntity: { expression: $expression }
  ) {
    entity {
      id
      name
      expression
    }
  }
}
```

Example variables:

```json
{
  "expression": "(appName = 'ProductionApp' AND environment = 'prod' AND region = 'us-east-1')",
  "macroId": "your-macro-id"
}
```

To find a macro's ID, refer to [Find your organization or macro ID](#find-ids).

````

> #### ⚠️ IMPORTANT
>
> When you edit a macro, all queries using that macro automatically use the updated version. Review your changes to make sure they don't break existing queries. Due to caching, there may be a slight delay before the update takes effect. You can't update a macro's name after creation. If you need to change the name, delete the macro and create a new one.

## Find your organization or macro ID [#find-ids]

**Find your organization ID**

````graphql
query MyOrganizationId {
  actor {
    organization {
      id
    }
  }
}
```

````

**List all macros and their IDs**

````graphql
query GetMacros($cursor: String) {
  actor {
    entityManagement {
      entitySearch(query: "type = 'NRQL_MACRO'", cursor: $cursor) {
        entities {
          ... on EntityManagementNrqlMacroEntity {
            id
            name
            expression
          }
        }
        nextCursor
      }
    }
  }
}
```

````

## Related topics

[NRQL macros](https://docs.newrelic.com/docs/nrql/nrql-macros/nrql-macros-overview)

Learn what NRQL macros are, what you can do with them, and who can use them.

[NRQL reference](https://docs.newrelic.com/docs/nrql/nrql-syntax-clauses-functions)

Explore NRQL syntax, clauses, and functions.
