

# Connect to a PostgreSQL data source
<a name="using-postgresql-in-AMG"></a>

 You can use the PostgreSQL data source to query and visualize data from your Amazon Aurora PostgreSQL databases. 

**Important**  
*Grafana version 8 *changes the underlying data structure for data frames for the Postgres, MySQL, and Microsoft SQL Server data sources. As a result, a time series query result is returned in a wide format. For more information, see [Wide format](https://grafana.com/developers/plugin-tools/introduction/data-frames#wide-format) in the Grafana data frames documentation. To make your visualizations work as they did before version 8, you might have to do some manual migrations. One solution is documented on Github at [Postgres/MySQL/MSSQL: Breaking change in v8.0 related to time series queries and ordering of data column](https://github.com/grafana/grafana/issues/35534).  
In *Grafana version 9*, the PostgreSQL data source sets up the root certificate for connecting to your database differently than in previous versions. If you update your workspace from version 8 to 9, you might need to change how you connect. See [Troubleshooting issues with updated workspaces](AMG-workspace-version-update-troubleshoot.md) for more information.

## Adding the data source
<a name="postgresql-adding-the-data-source"></a>

1.  Open the side menu by choosing the Grafana icon in the top header. 

1.  In the side menu under the **Configuration** icon, you should find a **Data Sources** link. 

1.  Choose the **\+ Add data source** button in the top header. 

1.  Select **PostgreSQL** from the **Type** dropdown list. 

### Data source options
<a name="postgresql-data-source-options"></a>


|  Name  |  Description  | 
| --- | --- | 
|  Name  |  The data source name. This is how you see the data source in panels and queries.  | 
|  Default  |  Default data source means that it will be pre-selected for new panels.  | 
|  Host  |  The IP address/hostname and optional port of your PostgreSQL instance. Do not include the database name. The connection string for connecting to Postgres will not be correct and will cause errors.  | 
|  Database  |  Name of your PostgreSQL database.  | 
|  User  |  Database user’s login/username. | 
|  Password  |  Database user’s password  | 
|  SSL Mode  |  This option determines whether or with what priority a secure SSL TCP/IP connection will be negotiated with the server.  | 
|  Max open  |  The maximum number of open connections to the database, default unlimited (Grafana v5.4\+).  | 
|  Max idle  |  The maximum number of connections in the idle connection pool, default 2 (Grafana v5.4\+).  | 
|  Max lifetime  |  The maximum amount of time in seconds a connection can be reused, default 14400/4 hours (Grafana v5.4\+).  | 
|  Version  |  This option determines which functions are available in the query builder (only available in Grafana 5.3\+).  | 
|  TimescaleDB  |  TimescaleDB is a time-series database built as a PostgreSQL extension. If enabled, Grafana will use time\_bucket in the $\_\_timeGroup macro and display TimescaleDB specific aggregate functions in the query builder (only available in Grafana 5.3\+).  | 

### Min time interval
<a name="postgresql-min-time-interval"></a>

 A lower limit for the `$_interval` `$_interval_ms` variables. Recommended to be set to write frequency, for example `1m` if your data is written every minute. This option can also be overridden/configured in a dashboard panel under data source options. This value **must** be formatted as a number followed by a valid time identifier; for example, `1m` (1 minute) or `30s` (30 seconds). The following time identifiers are supported.


|  Identifier  |  Description  | 
| --- | --- | 
|  y  |  Year  | 
|  M  |  Month  | 
|  w  |  Week  | 
|  d  |  Day  | 
|  h  |  Hour  | 
|  m  |  Minute  | 
|  s  |  Second  | 
|  ms  |  Millisecond  | 

### Database user permissions
<a name="postgresql-database-user-permissions-important"></a>

**Important**  
 The database user that you specify when you add the data source should only be granted SELECT permissions on the specified database and tables you want to query. Grafana does not validate that the query is safe. The query could include any SQL statement. For example, statements such as `DELETE FROM user;` and `DROP TABLE user;` would be run. To protect against this, we highly recommend that you create a specific PostgreSQL user with restricted permissions. 

The following example code shows creating a specifice PostgreSQL user with restricted permissions. 

```
 CREATE USER grafanareader WITH PASSWORD 'password';
 GRANT USAGE ON SCHEMA schema TO grafanareader;
 GRANT SELECT ON schema.table TO grafanareader;
```

 Make sure that the user does not get any unwanted permissions from the public role. 

## Query editor
<a name="postgresql-query-editor"></a>

 You find the PostgreSQL query editor in the metrics tab in Graph or Singlestat panel’s edit mode. You enter edit mode by choosing the panel title, then edit. 

 The query editor has a **Generated SQL** link that shows up after a query has been run, while in panel edit mode. Choose it, and it will expand and show the raw interpolated SQL string that was run. 

### Select table, time column, and metric column (FROM)
<a name="postgresql-select-table-time-column-and-metric-column-from"></a>

 When you enter edit mode for the first time or add a new query, Grafana will try to prefill the query builder with the first table that has a timestamp column and a numeric column. 

 In the FROM field, Grafana will suggest tables that are in the `search_path` of the database user. To select a table or view not in your ,`search_path` you can manually enter a fully qualified name (schema.table) such as `public.metrics`. 

 The Time column field refers to the name of the column holding your time values. Selecting a value for the Metric column field is optional. If a value is selected, the Metric column field will be used as the series name. 

 The metric column suggestions will only contain columns with a text data type (char,varchar,text). To use a column with a different data type as metric column, you can enter the column name with a cast: `ip::text`. You can also enter arbitrary SQL expressions in the metric column field that evaluate to a text data type such as `hostname || ' ' || container_name`. 

### Columns, window, and aggregation functions (SELECT)
<a name="columns-window-and-aggregation-functions-select"></a>

 In the `SELECT` row, you can specify what columns and functions you want to use. In the column field, you can write arbitrary expressions instead of a column name such as `column1 * column2 / column3`. 

 The available functions in the query editor depend on the PostgreSQL version you selected when configuring the data source. If you use aggregate functions, you must group your result set. If you add an aggregate function, the editor will automatically add a `GROUP BY time`. 

The editor tries to simplify and unify this part of the query. 

You can add further value columns by choosing the plus button and selecting **Column** from the menu. Multiple value columns will be plotted as separate series in the graph panel. 

### Filtering data (WHERE)
<a name="postgresql-filter-data-where"></a>

 To add a filter, choose the plus icon to the right of the `WHERE` condition. You can remove filters by choosing the filter and selecting **Remove**. A filter for the current selected time range is automatically added to new queries.

### Group By
<a name="postgresql-group-by"></a>

 To group by time or any other columns choose the plus icon at the end of the GROUP BY row. The suggestion dropdown list will only show text columns of your currently selected table but you can manually enter any column. You can remove the group by choosing the item and then selecting **Remove**. 

 If you add any grouping, all selected columns must have an aggregate function applied. The query builder will automatically add aggregate functions to all columns without aggregate functions when you add groupings. 

#### Gap filling
<a name="postgresql-gap-filling"></a>

 Amazon Managed Grafana can fill in missing values when you group by time. The time function accepts two arguments. The first argument is the time window that you want to group by, and the second argument is the value you want Grafana to fill missing items with. 

### Text editor mode (RAW)
<a name="postgresql-text-editor-mode-raw"></a>

 You can switch to the raw query editor mode by choosing the hamburger icon and selecting **Switch editor mode** or by choosing **Edit SQL** below the query. 

**Note**  
 If you use the raw query editor, be sure that your query at minimum has `ORDER BY time` and a filter on the returned time range. 

## Macros
<a name="postgresql-macros"></a>

 Macros can be used within a query to simplify syntax and allow for dynamic parts. 


|  Macro example  |  Description  | 
| --- | --- | 
|  $\_\_time(dateColumn)  |  Will be replaced by an expression to convert to a UNIX timestamp and rename the column to time\_sec. For example, UNIX\_TIMESTAMP(dateColumn) as time\_sec.  | 
|  $\_\_timeEpoch(dateColumn)  |  Will be replaced by an expression to convert to a UNIX timestamp and rename the column to time\_sec. For example, UNIX\_TIMESTAMP(dateColumn) as time\_sec. | 
|  $\_\_timeFilter(dateColumn)  |  Will be replaced by a time range filter using the specified column name. For example, dateColumn BETWEEN FROM\_UNIXTIME(1494410783) AND FROM\_UNIXTIME(1494410983).  | 
|  $\_\_timeFrom()  |  Will be replaced by the start of the currently active time selection. For example, FROM\_UNIXTIME(1494410783). | 
|  $\_\_timeTo()  |  Will be replaced by the end of the currently active time selection. For example, FROM\_UNIXTIME(1494410983).  | 
|  $\_\_timeGroup(dateColumn,'5m')  |  Will be replaced by an expression usable in GROUP BY clause. For example, cast(cast(UNIX\_TIMESTAMP(dateColumn)/(300) as signed)300 as signed),\*  | 
|  $\_\_timeGroup(dateColumn,'5m', 0)  |  Same as the preivious row, but with a fill parameter so missing points in that series will be added by grafana and 0 will be used as value.  | 
|  $\_\_timeGroup(dateColumn,'5m', NULL)  |  Same as above but NULL will be used as value for missing points.  | 
|  $\_\_timeGroup(dateColumn,'5m', previous)  |  Same as above but the previous value in that series will be used as fill value if no value has been seen yet NULL will be used (only available in Grafana 5.3\+).  | 
|  $\_\_timeGroupAlias(dateColumn,'5m')  |  Will be replaced identical to $\_\_timeGroup but with an added column alias  | 
|  $\_\_unixEpochFilter(dateColumn) |  Will be replaced by a time range filter using the specified column name with times represented as Unix timestamp. For example, \*dateColumn > 1494410783 AND dateColumn < 1494497183\* | 
| $\_\_unixEpochFrom()`  | \| Will be replaced by the start of the currently active time selection as Unix timestamp. For example, \*1494410783\* | 
| $\_\_unixEpochTo() | Will be replaced by the end of the currently active time selection as Unix timestamp. For example, \*1494497183\* | 
| $\_\_unixEpochNanoFilter(dateColumn) | Will be replaced by a time range filter using the specified column name with times represented as nanosecond timestamp. For example, \*dateColumn > 1494410783152415214 AND dateColumn < 1494497183142514872\* | 
| $\_\_unixEpochNanoFrom() | Will be replaced by the start of the currently active time selection as nanosecond timestamp. For example, \*1494410783152415214\* | 
| $\_\_unixEpochNanoTo() | Will be replaced by the end of the currently active time selection as nanosecond timestamp. For example, \*1494497183142514872\* | 
| $\_\_unixEpochGroup(dateColumn,"5m", [fillmode]) | Same as $\_\_timeGroup but for times stored as Unix timestamp. | 

## Table queries
<a name="postgresql-table-queries"></a>

 If the query option is set to **Format as Table**, you can basically do any type of SQL query. The table panel will automatically show the results of whatever columns and rows your query returns. 

 You can control the name of the Table panel columns by using regular `as` SQL column selection syntax. 

## Time series queries
<a name="postgresql-time-series-queries"></a>

 If you set **Format as** to `Time series`, for use in a graph panel for example, the query must return a column named `time` that returns either a SQL datetime or any numeric data type representing Unix epoch. Any column except `time` and `metric` is treated as a value column. You can return a column named `metric` that is used as metric name for the value column. If you return multiple value columns and a column named `metric`, this column is used as prefix for the series name. 

 Result sets of time series queries must be sorted by time. 

 The following example code shows a `metric` column. 

```
SELECT
  $__timeGroup("time_date_time",'5m'),
  min("value_double"),
  'min' as metric
FROM test_data
WHERE $__timeFilter("time_date_time")
GROUP BY time
ORDER BY time
```

 The folowing code example shows using the fill parameter in the $\_\_timeGroup macro to convert null values to be zero instead. 

```
SELECT
  $__timeGroup("createdAt",'5m',0),
  sum(value) as value,
  measurement
FROM test_data
WHERE
  $__timeFilter("createdAt")
GROUP BY time, measurement
ORDER BY time
```

 The following example code shows multiple columns. 

```
SELECT
  $__timeGroup("time_date_time",'5m'),
  min("value_double") as "min_value",
  max("value_double") as "max_value"
FROM test_data
WHERE $__timeFilter("time_date_time")
GROUP BY time
ORDER BY time
```

## Templating
<a name="postgresql-templating"></a>

 Instead of hardcoding things such as server, application and sensor name in your metric queries you can use variables in their place. Variables are shown as dropdown select boxes at the top of the dashboard. You can use these dropdown boxes to change the data being displayed in your dashboard. 

 For more information about templating and template variables, see [Templates](templates-and-variables.md#templates). 

### Query variable
<a name="postgresql-query-variable"></a>

 If you add a template variable of the type `Query`, you can write a PostgreSQL query that can return things such as measurement names, key names, or key values that are shown as a dropdown select box. 

 For example, you can have a variable that contains all values for the `hostname` column in a table if you specify a query such as this in the templating variable *Query* setting. 

```
SELECT hostname FROM host
```

 A query can return multiple columns and Grafana will automatically create a list from them. For example, the following query will return a list with values from `hostname` and `hostname2`. 

```
SELECT host.hostname, other_host.hostname2 FROM host JOIN other_host ON host.city = other_host.city
```

 To use time range dependent macros such as `$__timeFilter(column)` in your query, the refresh mode of the template variable must be set to *On Time Range Change*. 

```
SELECT event_name FROM event_log WHERE $__timeFilter(time_column)
```

 Another option is a query that can create a key/value variable. The query should return two columns that are named `__text` and `__value`. The `__text` column value should be unique (if it is not unique, the first value is used). The options in the dropdown list will have a text and value that allows you to have a friendly name as text and an id as the value. An example query with `hostname` as the text and `id` as the value: 

```
SELECT hostname AS __text, id AS __value FROM host
```

 You can also create nested variables. Using a variable named `region`, you could have the hosts variable show only hosts from the current selected region. The following code example shows a query such as this (if `region` is a multi-value variable, use the `IN` comparison operator rather than `=` to match against multiple values). 

```
SELECT hostname FROM host  WHERE region IN($region)
```

#### Using `__searchFilter` to filter results in Query Variable
<a name="postgresql-using-__searchfilter-to-filter-results-in-query-variable"></a>

 Using `__searchFilter` in the query field will filter the query result based on what the user types in the dropdown select box. When nothing has been entered by the user, the default value for `__searchFilter` is `%`. 

**Note**  
 Important that you surround the `__searchFilter` expression with quotes as Grafana does not do this for you. 

 The following example shows how to use `__searchFilter` as part of the query field to enable searching for `hostname` while the user types in the dropdown select box. 

```
SELECT hostname FROM my_host  WHERE hostname LIKE '$__searchFilter'
```

### Using variables in queries
<a name="postgresql-using-variables-in-queries"></a>

 Template variable values are only quoted when the template variable is a `multi-value`. 

 If the variable is a multi-value variable, use the `IN` comparison operator rather than `=` to match against multiple values. 

 There are two syntaxes: 

 `$<varname>` Example with a template variable named `hostname`: 

```
SELECT
  atimestamp as time,
  aint as value
FROM table
WHERE $__timeFilter(atimestamp) and hostname in($hostname)
ORDER BY atimestamp ASC
```

 `[[varname]]` Example with a template variable named `hostname`: 

```
SELECT
  atimestamp as time,
  aint as value
FROM table
WHERE $__timeFilter(atimestamp) and hostname in([[hostname]])
ORDER BY atimestamp ASC
```

#### Turning off quoting for multi-value variables
<a name="postgresql-disabling-quoting-for-multi-value-variables"></a>

 Amazon Managed Grafana automatically creates a quoted, comma-separated string for multi-value variables. For example: if `server01` and `server02` are selected then it will be formatted as: `'server01', 'server02'`. To turn off quoting, use the csv formatting option for variables. 

 `${servers:csv}` 

 For more information about variable formatting options, see [Templates and variables](templates-and-variables.md). 

## Annotations
<a name="postgresql-annotations"></a>

 Use annotations to overlay rich event information on top of graphs. You add annotation queries via the Dashboard menu / Annotations view. For more information, see [Annotations](dashboard-annotations.md). 

 The following example code shows a query using a time column with epoch values. 

```
SELECT
  epoch_time as time,
  metric1 as text,
  concat_ws(', ', metric1::text, metric2::text) as tags
FROM
  public.test_data
WHERE
  $__unixEpochFilter(epoch_time)
```

 The following example code shows a region query using time and timeend columns with epoch values. 

**Note**  
 This is available only in Grafana v6.6\+. 

```
SELECT
  epoch_time as time,
  epoch_time_end as timeend,
  metric1 as text,
  concat_ws(', ', metric1::text, metric2::text) as tags
FROM
  public.test_data
WHERE
  $__unixEpochFilter(epoch_time)
```

 The following example code shows a query using a time column of native SQL date/time data type. 

```
SELECT
  native_date_time as time,
  metric1 as text,
  concat_ws(', ', metric1::text, metric2::text) as tags
FROM
  public.test_data
WHERE
  $__timeFilter(native_date_time)
```


|  Name  |  Description  | 
| --- | --- | 
|  time  |  The name of the date/time field. Could be a column with a native SQL date/time data type or epoch value.  | 
|  timeend  |  Optional name of the end date/time field. Could be a column with a native SQL date/time data type or epoch value (Grafana v6.6\+). | 
|  text  |  Event description field.  | 
|  tags  |  Optional field name to use for event tags as a comma-separated string.  | 

## Alerting
<a name="postgresql-alerting"></a>

 Time series queries should work in alerting conditions. Table formatted queries are not yet supported in alert rule conditions. 