Grafana with PostgreSQL for business and operational dashboards

Grafana's built-in PostgreSQL data source charts business and operational data with a visual builder or raw SQL, time series macros and alerts. This page covers the setup, read-only access and failure points.

On this page

Grafana with PostgreSQL: how the built-in data source works

Business and operations data often sits in PostgreSQL, and teams want dashboards on it without exporting copies into another store. The starting point is Grafana's preinstalled PostgreSQL data source, which ships with Grafana OSS and Enterprise, so no separate install is needed to connect. It supports PostgreSQL 9.0 and newer, and it works against self-managed clusters as well as Amazon RDS, Aurora PostgreSQL, Azure Database for PostgreSQL and Google Cloud SQL. Confirm the exact provider variant and version you run against the Grafana PostgreSQL data source documentation before you commit to a design.

Each query can be built in the visual query builder or written as raw SQL. The builder suits simple table and column selections, while raw SQL is needed for joins, window functions and business logic that analysts already maintain. The same connection also drives time grouping macros for time series panels, annotations that mark events such as deployments or batch runs on a graph, and alert rules that evaluate SQL results. Because these features share one connection, the database user you create determines what every panel, annotation and alert can read, so access design should happen before the first dashboard is built.

The data source is packaged as a standalone plugin that can update independently of Grafana releases. That separation is useful, but it also means your change control needs two tracks: one for the Grafana server and one for the PostgreSQL plugin. Record both versions in your deployment inventory, and check the plugin release notes whenever you upgrade Grafana. Your PostgreSQL server has its own support window, so confirm that the major version you run is still supported under the PostgreSQL versioning policy before you plan dashboards that will depend on it for years.

What you need before connecting PostgreSQL to Grafana

Connecting Grafana to PostgreSQL touches three systems: the Grafana instance, the database that stores its configuration, and the business database you want to chart. Each card below lists what you must confirm in your own environment before the first query runs, so that dashboards do not depend on an unsupported database version, an exposed network path or a role with more rights than it needs.

Grafana configuration database

Grafana keeps its users, dashboards and alert state in a configuration database. SQLite is the default, but the Grafana installation docs say it does not scale for production, so plan for PostgreSQL 12 or later or MySQL 8.0 or later for any production or high availability setup. Confirm which engine you will use, who operates it, and how it is backed up, because this database is separate from the business database you are about to chart.

Supported PostgreSQL version

Check that the business database runs a version still inside its support window. PostgreSQL 14 is supported until November 12, 2026, while 15, 16, 17 and 18 run later. Confirm the exact major version in production, the date your organization plans to retire it, and whether a major upgrade is already scheduled. A version that falls out of support during the dashboard project will create rework.

Network path from Grafana

Grafana must reach the PostgreSQL listener on its port, usually 5432, through any firewall, security group or routing layer between them. Confirm which subnet or host the Grafana servers use, whether traffic crosses a zone boundary, and whether a connection pooler such as PgBouncer sits in front of the database. Ask the database team to allow only the Grafana addresses rather than an open range.

TLS certificates and encryption in transit

Dashboard queries can carry customer, financial or patient fields, so the connection should be encrypted. Confirm that the PostgreSQL server has a certificate trusted by the Grafana host, that the certificate chain and hostname match what Grafana connects to, and that the team knows who renews it and when. Decide whether certificate verification is required, and document the CA bundle Grafana will use.

Dedicated read-only database role

Create a separate PostgreSQL login for Grafana that holds only the SELECT privileges its dashboards need, on named schemas and views. Do not reuse an application account or an administrator role. Confirm with the database owner which tables are exposed, whether views should hide sensitive columns, and how the password is stored and rotated. Grafana queries run as this role, so its grants define what every dashboard viewer can see.

Owners and a change path

Name who owns the Grafana server, the database role, the network rules and the dashboards that query production tables. Confirm who approves a new query that scans a large table, and where dashboard and data source definitions will be kept, for example as provisioning files under version control. Clear ownership before go-live prevents a dashboard built by one team from breaking after a database change made by another.

How to configure the PostgreSQL data source in order

This sequence takes a self-hosted Grafana instance from no database access to a tested PostgreSQL data source, a first time series panel, annotations and an alert rule, with a check at each stage so you can confirm the work before moving on.

  1. Create a read-only database role

    The PostgreSQL administrator creates a dedicated login role for Grafana, grants CONNECT on the target database, USAGE on only the schemas that hold dashboard data, and SELECT on the specific tables or views the panels need. Do not grant write privileges or superuser rights, and do not reuse an application account. The check is a manual login with that role: it should read the approved tables and fail on an insert or on a table outside the grant list.

  2. Confirm network reachability from the Grafana host

    The network or platform team confirms that the Grafana server, or each container or pod running it, can reach the PostgreSQL port through firewall rules, security groups or private routing. Run a basic connectivity test from the Grafana host itself, not from a workstation, because the host is the one that opens the connection. The check is a successful TCP connection to the database host and port from the Grafana host. Confirm the database host name resolves the same way from that host.

  3. Add the data source with TLS settings

    In Grafana, an administrator opens Connections, adds a PostgreSQL data source, and enters the host and port, database name, the read-only role and its password. Set the TLS/SSL mode to match your database policy and attach the CA certificate where the database uses a private certificate authority. Store the password as a secret field, not in a shared note. Confirm the version setting matches your server, and check the data source's documented options for your PostgreSQL edition before saving. The check is that the form saves without validation errors and the settings show the expected host and mode.

  4. Test the connection

    Use the Save and test action on the data source page. A successful result confirms that Grafana reached the server, authenticated the read-only role and could run a basic query. If the test fails, separate the causes: a timeout points to network or firewall rules, an authentication error points to the role or password, and a TLS error points to the mode or CA certificate. Re-run the test after each change. The check is a green success message, and you should also record which role and host the test used.

  5. Build a first time series panel with macros

    Create a dashboard panel, switch the query editor to the visual builder or raw SQL, and select a timestamp column and a numeric value. Use the time filter macros and the time grouping macro so the query returns one row per time bucket within the dashboard range. Start with a narrow time range and a single metric so results are easy to verify. The check is that the panel returns rows whose timestamps fall inside the selected range and whose counts or sums match a direct query you run with the same role in a SQL client.

  6. Add annotations from SQL

    Add an annotation query to the dashboard that returns a time column and a text column from an event table, such as deployments or maintenance windows. Keep the query limited to the same read-only grants. Annotations show as markers on time series panels, so they help explain changes in the data. The check is that the markers appear on the panel at the expected timestamps and that the text matches a sample row from the source table.

  7. Create an alert rule from a SQL query

    Create an alert rule on a SQL query that returns a numeric value for a recent window, set the condition and evaluation interval, and choose a contact point for a test notification. Confirm that the query runs within the database load you have agreed with the database owner, and that the rule does not hold a long transaction. Trigger the condition with a known test value, or use a test notification, to confirm the route. The check is a fired test alert that reaches the contact point, followed by a resolved state once the value returns to normal.

Visual query builder or raw SQL: choosing the query method

Use the visual query builder for simple table and aggregate panels, and move to raw SQL once a panel needs joins, window functions or custom time bucketing. The Grafana PostgreSQL data source offers both a visual query builder and raw SQL on the same connection, so the choice is made per panel rather than per instance. The query shape decides the load that each panel places on the database, and that load lands on the same production server that runs your business applications.

The visual builder produces straightforward selects with a time column, a grouping and an aggregate, which is usually enough for counts per day, totals per branch or queue depth over time. Raw SQL is needed when a panel joins several tables, uses window functions such as running totals or rankings, or buckets timestamps in a way the builder does not express. Time grouping macros cover the common time series case, but a custom bucket, a timezone-specific day boundary or a calculation across rows usually means writing the query yourself. Review every raw query with the database owner before it reaches a shared dashboard, since a panel refreshed every few seconds multiplies the cost of an expensive query.

For heavy dashboards, review the query plan with EXPLAIN ANALYZE against production-sized data and confirm that the filter columns used by the time range variable are indexed. Where a dashboard repeatedly scans large tables, consider a view or a materialized summary table that a scheduled job refreshes, so Grafana reads a small result instead of recomputing it on every refresh. This is a design choice to confirm with the database owner, who decides the refresh schedule, the ownership of the summary objects and whether the read load can run against a standby. Recording the agreed refresh interval next to each dashboard makes later troubleshooting much faster.

Mapping database fields to panels, time and alerts

This table shows how each kind of PostgreSQL column becomes a time axis, a series value, a series name or an alert input in the Grafana PostgreSQL data source. Read each row as a rule you should confirm against your own schema before a dashboard goes to business users, because a wrong type or time zone assumption shifts every chart built on it.

Column or resultGrafana conceptWhat to verifyCommon failure
Timestamp columnTime axis, used by time-range macrosDeclared type (timestamp with or without time zone) and the zone the values were written inValues stored as local time without a zone shift by hours when read by a server in another zone
Time-grouping outputTime series x-axis from a grouping macroThe macro output matches the bucket size you intend and the query orders by timeUnordered rows produce lines that zigzag across the panel
Numeric columnSeries value on the y-axisNumeric type (integer, numeric, double precision) and units set on the panelText-typed numbers plot as zero or fail to plot at all
Text label columnSeries name, from the alias or the label columnLow cardinality, since every distinct value creates a seriesHigh-cardinality IDs create hundreds of unreadable series
NULL values in numeric columnsGaps or zero, depending on panel settingsHow the panel treats missing points and whether NULL should mean no data or zeroMissing rows read as zero and suggest a false drop in activity
Query result rows for alertsInput to a reduce and threshold expressionExactly one numeric value or a labeled set of series, and the time range the query coversAlert query returns no rows, which may resolve silently or go to no data state
Read-only database roleConnection used by every panel and alert ruleGrants limited to the needed schemas and tables, with no write privilegesShared admin credentials expose the database to dashboard editors

Securing the PostgreSQL connection and access

A Grafana dashboard is only as safe as the database account, connection and instance settings behind it. The cards below cover the controls that sit between Grafana and PostgreSQL, from the database role and transport encryption to where credentials live and who can change them.

Read-only database role with minimal grants

Create a dedicated PostgreSQL role for Grafana that holds only CONNECT on the target database, USAGE on the schemas, and SELECT on the specific tables or views its panels read. Keep write privileges and ownership out of this role, so a leaked credential or a careless query cannot change business data. Ask the database team to confirm whether row-level security policies are needed for tables that hold data some viewers must not see, and test the role with the exact queries your dashboards run.

TLS between Grafana and PostgreSQL

Set the PostgreSQL data source TLS/SSL mode so that traffic between the Grafana server and the database is encrypted, and confirm with the database team which mode is appropriate for the network path. Where the database enforces client certificates, plan how the certificate and key files are delivered to the Grafana host and rotated. Verify the setting by checking that connections without encryption are rejected on the server side.

SCRAM instead of MD5 passwords

PostgreSQL 18 deprecated MD5 password authentication in favor of SCRAM. Ask the database team to confirm that password_encryption is set to SCRAM, that the Grafana role's password was re-set after the change, and that pg_hba.conf does not allow MD5 for the Grafana network. Also confirm which other methods are in use for the database, since PostgreSQL documents password, GSSAPI, SSPI, LDAP, RADIUS, certificate, PAM and OAuth options.

Credentials kept out of dashboards

Enter the database password in the data source configuration, where Grafana stores it encrypted, rather than in a panel query, a dashboard variable or a dashboard JSON export. Use provisioning files only with secrets injected from your secret store, not with plaintext passwords committed to Git. Review dashboards before sharing or exporting them, since exported JSON can expose connection details if they were placed in the wrong field.

Limiting who can edit data sources

Changing a data source's host, user or TLS settings changes what every dashboard can reach, so restrict data source administration to a small group. Confirm which roles can create, edit or delete data sources on your edition, and use folder and dashboard permissions so that viewers can read panels without seeing or editing the connection. Team sync and SCIM provisioning are Enterprise and Grafana Cloud features, so check what your edition can enforce.

Authentication options to confirm

Review with the database team which client authentication methods the PostgreSQL server accepts for the Grafana role, such as password with SCRAM, certificate, LDAP or GSSAPI. Each option changes who manages the credential and how it rotates, so record the choice in the design. Treat this list as options to confirm, not as a recommendation for your environment, because the server's pg_hba.conf rules and your directory setup decide what is possible.

Grafana instance hardening settings

Apply the Grafana security hardening settings that cover the instance serving these dashboards, including secure and SameSite cookies, a Content Security Policy, hiding the version from unauthenticated users, and requiring authentication for the metrics endpoint. Check these settings after each upgrade, because a database dashboard exposes business data to anyone who can reach the login page. Confirm the exact configuration keys against the version you run.

Connecting to managed PostgreSQL services such as RDS and Cloud SQL

The Grafana PostgreSQL data source works with Amazon RDS, Aurora PostgreSQL, Azure Database for PostgreSQL and Google Cloud SQL, but each service sets its own rules for who can reach the database and how the connection is secured. Start by confirming the network path before touching Grafana. Each managed service controls access through its own mechanism, such as security groups and VPC placement on AWS, firewall rules or private networking on Azure, and authorized networks or private IP on Google Cloud SQL. The Grafana server's outbound address or subnet has to be allowed, and the same instance should be tested with a plain psql client from the Grafana host before the data source is configured. Confirm the exact options for your service and region with the provider documentation, since these settings change over time.

TLS settings are the second area where managed services differ. Most providers require encrypted connections and publish their own certificate chains, so the data source's TLS mode and root certificate fields must match what the provider issues. Verify the chain on the Grafana host and set the TLS mode to verify the server certificate rather than disabling verification. Read replicas deserve a deliberate decision. Dashboard panels run frequent queries, and pointing them at a read replica endpoint keeps that load away from transactional workloads. PostgreSQL hot standby servers serve read-only queries, but replicas on managed services can lag behind the primary, so agree with the data owners how stale a dashboard may be. Create the Grafana role on the replica with read-only privileges, and confirm with your provider whether replica endpoints accept the same credentials.

Finally, decide how Grafana authenticates to the database. Password authentication with a read-only role is the common starting point and works on every service listed above. Some providers also offer cloud IAM database authentication, where short-lived tokens replace stored passwords. Whether the PostgreSQL data source can use these tokens directly, and how they are refreshed, depends on the Grafana version and the provider, so confirm both before planning around them. Whichever method you choose, store the credentials in Grafana's secure settings or your secrets manager, not in dashboard JSON, and rotate them on the schedule your security team requires.

Common PostgreSQL and Grafana connection failures

This table lists the failures most often seen when Grafana reads from PostgreSQL, with the likely cause and the first fix for each. Work through the rows in order, since network and TLS problems hide the permission and query problems below them.

SymptomLikely causeFix
Connection refused or timeout from the Grafana hostPostgreSQL is not listening on the interface Grafana uses, or a firewall or security group blocks the port between the Grafana host and the databaseCheck the listen_addresses setting and the pg_hba.conf entry on the server, then test the port from the Grafana host with a plain client before editing the data source
TLS handshake error on save or queryThe data source requests SSL but the server certificate is not trusted, its name does not match the host, or the server does not offer TLSSet the TLS mode to match the server, upload the correct CA certificate, and confirm the host name in the data source matches the certificate subject or alternative names
Authentication failed for the Grafana userWrong password, a role without LOGIN, or a pg_hba.conf rule that uses a different authentication method than the one Grafana sendsReset the role password, confirm the role can log in, and check which method the matching pg_hba.conf line requires
Permission denied for schema or tableThe read-only role has no USAGE on the schema or no SELECT on the table, or the table was created after the grant was madeGrant USAGE on the schema and SELECT on existing tables, then set default privileges so future tables are readable by the same role
Query hangs or times out on large time rangesThe query scans a full table with no time filter, or a missing index on the timestamp column forces a sequential scan on every panel refreshUse the time filter macro in every query, add an index on the timestamp column, and limit the range or use a summary table for long-range views
Panels show no data or the wrong totalsThe time zone of the database session differs from the Grafana display, or a timestamp stored without time zone is read with an offsetStore timestamps as timestamptz where possible, set the data source time zone deliberately, and compare the query output in a SQL client against the panel
Panels show no data after editing a macroThe time column in the macro does not match the column name in the table, or the query uses a column type the macro does not expectConfirm the column name and type in the query, check the rendered SQL in the query inspector, and correct the macro argument
Alert fires on stale or empty resultsThe alert query returns no rows, which some alert configurations treat as normal or as no data, or the query reads a time range that ends before the latest data arrivesSet an explicit no-data state in the alert rule, anchor the time range to now with a lag that covers ingestion delay, and test the rule against a known empty range

Questions buyers ask about Grafana and PostgreSQL integration

What drives the effort and cost of a Grafana and PostgreSQL setup?

The main drivers are how many dashboards and panels you need, how complex the SQL behind them is, and how many databases and schemas are involved. Access design matters as much: read-only roles, row-level filtering for different teams, and a review of which queries are allowed against production tables. One-time work covers discovery, the data source configuration, query design, dashboard build, provisioning files and acceptance checks. Recurring work covers dashboard changes as the business asks new questions, credential rotation, plugin and Grafana upgrades, and periodic query reviews. Ask any quote to split one-time and recurring costs and to list which environments and databases are in scope.

How long does a first Grafana PostgreSQL integration take?

Duration depends mostly on the data model and the access rules, not on the Grafana setup itself. A clean, well-indexed schema with a few agreed metrics is far quicker to chart than a legacy database with inconsistent timestamps, time zones and duplicated business keys. Access approvals, change windows and the number of teams who must sign off also add elapsed time. No duration figure applies here without a scoped review. A written scope should state the deliverables and dependencies, so you can compare timelines across proposals on the same basis.

What does the work need from our database and security teams?

Your database team needs to create a dedicated read-only role, confirm which schemas and views Grafana may read, and agree on connection encryption and network paths from the Grafana host. Ideally they also provide a replica or reporting endpoint so dashboards do not compete with transactional load. Your security team should review the authentication method for that role, where credentials are stored, and who can edit queries in Grafana. Expect to confirm whether the database uses password, certificate or another method supported by PostgreSQL, since that choice affects secret handling. Ask both teams to name an owner for access requests after go-live.

Can an internal team build this without a partner?

Yes, a capable internal team can build simple dashboards without outside help, especially if they already operate PostgreSQL and Grafana. The gap usually appears in the less visible parts: least-privilege roles, query load control, provisioning the data source as code, alerting on SQL results, and documenting who owns each dashboard. A partner is most useful when you need a fixed-scope build with written deliverables, handover material and a review of access design. Decide by comparing your team's capacity and skills against the scope list, then ask for a written breakdown either way.

How do PostgreSQL upgrades affect Grafana dashboards?

Minor PostgreSQL releases do not change the storage format, so dashboards usually keep working after an executable replacement and restart. Major upgrades need more planning because queries, views, data types and planner behavior can change. PostgreSQL offers pg_dumpall with restore, pg_upgrade, and logical replication, and logical replication can keep downtime to several seconds. Plan a check of every dashboard query against the new major version before cutover. Grafana plugin updates are separate: the PostgreSQL data source can update independently of Grafana releases, so test dashboards after either upgrade. Confirm your supported PostgreSQL version timeline in the PostgreSQL versioning policy before scheduling work.

What changes when we use a managed PostgreSQL service?

The Grafana PostgreSQL data source supports Amazon RDS, Aurora PostgreSQL, Azure Database for PostgreSQL and Google Cloud SQL, so connection setup is similar in principle. Managed services change who handles patching, backups, failover and major upgrades, and they often limit superuser access and some extensions. You will also need to confirm network routing from Grafana to the service, certificate handling, and whether read replicas are available for reporting queries. Pricing and feature sets vary by provider and tier, so ask your provider and any partner to state these in writing rather than assuming parity with self-managed PostgreSQL.

Can Grafana alert on SQL query results from PostgreSQL?

Yes, the PostgreSQL data source can drive alerts from the same connection used for dashboards. The query must return a clean time series or numeric result, so design it with a fixed time window, explicit null handling and an index that supports the filter. Expensive queries run on every evaluation, so schedule evaluation intervals with database load in mind. Test alert behavior with known data before relying on it, and document who receives notifications and how silences are handled. Alerting in an HA Grafana setup needs extra configuration to avoid duplicate notifications.

How DeployOpen works on this

DeployOpen plans, implements, hardens, documents and supports self-hosted Grafana connected to your PostgreSQL databases, inside your own cloud accounts, data centers or air-gapped networks. Each engagement starts from a written scope that defines which dashboards, queries and alerts are in and out before any build work begins.

How we scope

  • Inventory the PostgreSQL databases, schemas and tables that dashboards and alerts will read, and who owns each one.
  • Agree which panels, time series queries and SQL-based alert rules are in the written scope and which are excluded.
  • Define the read-only database roles, network paths and managed PostgreSQL service details that the connection will use.
  • Confirm the PostgreSQL major version in use and the Grafana edition, deployment target and database backing Grafana itself.

How we build

  • Configure the PostgreSQL data source with read-only credentials and document how time macros and query limits are applied.
  • Build dashboards in the visual query builder where it fits, and in reviewed raw SQL where business logic needs it.
  • Test queries against representative data volumes and check their load on production databases before go-live.
  • Define data source, dashboard and alert resources as provisioning files so the setup can be reviewed and repeated.

How we hand over

  • Deliver a written runbook covering data source configuration, credential rotation, query ownership and dashboard change steps.
  • Document each dashboard and alert rule with its SQL source, refresh expectations and the business owner who approves changes.
  • Walk your operations and database teams through the setup, the access model and how to add a new panel safely.
  • Record the final scope, versions and open items so later changes can be measured against the original agreement.

How we support

  • Offer ongoing support, upgrades and continuous testing as a retainer after handover, scoped in writing.
  • Plan Grafana patch and minor upgrades and check the PostgreSQL data source plugin version against each change.
  • Review read-only role permissions and query performance when schemas change or new dashboards are requested.
  • Agree in the retainer how PostgreSQL major upgrades, failover and backup changes will be coordinated with your database team.

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.