Many businesses run on an app that writes to a SQL database: an order portal, a booking system, a stock tool someone built years ago. The numbers the board wants are in there. Getting them out usually means asking the one developer who knows the schema to run a query, paste the result into a spreadsheet and send it on. That works once. It does not work every Monday, and it gets risky when the query runs against the live database while customers are using the app.
Reporting from a SQL database without a BI team comes down to four jobs. Get safe, read-only access. Reach the database over the network without opening it to the internet. Model the raw tables into figures the business agrees on. Then send the output on a schedule, with checks that stop a wrong number going out. This page takes each in turn, with sample SQL for PostgreSQL and MySQL.
Step 1: read-only access, away from production
The first rule is that reporting should never be able to change data, and should never slow down the app. Both are settings, not promises.
A role that can only read
Create a dedicated login for reporting and grant it SELECT on the tables the report needs, nothing more. In PostgreSQL that means USAGE on the schema and SELECT on named tables, as set out in the GRANT reference:
CREATE ROLE reporting_ro LOGIN PASSWORD '...';
GRANT USAGE ON SCHEMA sales TO reporting_ro;
GRANT SELECT ON sales.orders, sales.order_lines,
sales.credit_notes, sales.customers TO reporting_ro;
ALTER ROLE reporting_ro SET default_transaction_read_only = on;
ALTER ROLE reporting_ro SET statement_timeout = '60s';
PostgreSQL also has a predefined role, pg_read_all_data, which reads every table, view and sequence (predefined roles). That is broader than most reports need. An app database often holds things like password hashes and personal details that a sales report has no reason to touch, so naming the tables is the tighter choice.
The last two lines are guardrails. ALTER ROLE ... SET makes a setting the default each time that role logs in. default_transaction_read_only starts every transaction as read-only, and statement_timeout aborts any statement that runs past the limit (client settings). A badly written join then fails after a minute instead of running for an hour.
In MySQL the pattern is the same, using CREATE USER and a GRANT SELECT on the database, as in the examples on the GRANT statement page:
CREATE USER 'reporting_ro'@'10.0.4.%' IDENTIFIED BY '...';
GRANT SELECT ON sales.* TO 'reporting_ro'@'10.0.4.%';
SELECT /*+ MAX_EXECUTION_TIME(60000) */ ...; -- per-query limit, milliseconds
The host part of the account limits where that login can connect from. MySQL's max_execution_time is a timeout in milliseconds for read-only SELECT statements. A query can set its own limit with the MAX_EXECUTION_TIME hint, as above, which avoids changing the setting for every other session on the server.
Query a replica, not the primary
A role that can only read can still run a heavy query. The safer target is a replica: a copy kept up to date from the main database. PostgreSQL calls a queryable replica a hot standby, and its hot standby documentation says every connection to one is strictly read-only. MySQL's replication scale-out page describes sending reads to replicas and writes to the source.
Two points from the PostgreSQL docs are worth knowing before you rely on a replica. First, a long report query can conflict with changes arriving from the primary, and the standby will cancel the query once it has held those changes back for longer than max_standby_streaming_delay. The docs suggest a higher delay may suit a standby used for reporting, at the cost of that standby showing older data while it waits. Second, a replica can lag. pg_last_xact_replay_timestamp() returns the time of the last transaction replayed, so a scheduled job can check it before reading and hold the report if the copy is too far behind.
If there is no replica, run reports outside trading hours, keep the timeout short and read only rows changed since the last run.
Step 2: network access without opening the database
Most production databases are not reachable from the internet, and should stay that way. There are two common routes in.
- Allowlisting. The database, or the firewall in front of it, accepts connections only from fixed IP addresses. In PostgreSQL,
pg_hba.confmatches each connection on type, database, user and client address, and ahostsslline accepts only encrypted connections. A reporting service with a fixed outbound IP can be let in by that address alone. - SSH tunnel. The reporting service logs in to a host inside your network and forwards a local port to the database. The PostgreSQL page on SSH tunnels shows the pattern with
ssh -L. The database sees the connection arrive from inside, so its own login rules still apply.
Either way, write down who owns the credentials and how to revoke them. Removing one IP address or one SSH key should end access within minutes.
Step 3: model the tables into business figures
Raw tables reflect how the app works, not how finance counts. An order table includes cancelled orders, staff purchases and test accounts. Credit notes live in their own table and are dated when they are raised, not when the original order was placed. A raw SUM over the orders table will give a number, and it will be wrong.
Modelling fixes this in two layers. A staging layer cleans each table: correct types, consistent time zones, and flags for rows to exclude. A business definitions layer then states each figure once, in SQL that anyone can read.
Fields used
| Table | Fields | Notes |
|---|---|---|
sales.orders |
id, customer_id, status, created_at |
created_at stored in UTC; status includes cancelled |
sales.order_lines |
order_id, qty, unit_price, unit_cost |
Cost captured on the line at the time of sale |
sales.credit_notes |
id, order_id, created_at, amount_net |
Dated when raised |
sales.customers |
id, name, account_type |
trade, internal or test |
These names are an example schema. Yours will differ, and the first piece of work is always mapping the real column names and their quirks.
Joins
| From | To | Key |
|---|---|---|
order_lines |
orders |
order_lines.order_id = orders.id |
orders |
customers |
orders.customer_id = customers.id |
credit_notes |
orders |
credit_notes.order_id = orders.id, then to customers through the order |
Definitions
| Figure | Definition |
|---|---|
| Report week | Monday to Sunday, using created_at converted to Europe/London |
| Gross trade sales | Σ qty × unit_price on orders not cancelled, for trade customers |
| Credits | Σ amount_net on credit notes raised in the week, for trade customers |
| Net trade sales | gross trade sales − credits |
| Cost of sales | Σ qty × unit_cost on the same order lines as gross trade sales |
| Gross margin | net trade sales − cost of sales |
| Margin % | gross margin ÷ net trade sales |
Two choices in that table are judgement calls for the business, not facts the database can supply. Credits count in the week they are raised, even when the order was placed earlier. And credits reduce sales but not cost, which treats them as price reductions rather than returned stock. If your returns go back on the shelf, you would reverse the cost too. Writing these choices down is most of the value of modelling.
Sample SQL
CREATE VIEW reporting.trade_lines AS
SELECT o.id AS order_id, o.customer_id,
(o.created_at AT TIME ZONE 'Europe/London')::date AS order_day,
l.qty * l.unit_price AS line_sales,
l.qty * l.unit_cost AS line_cost
FROM sales.orders o
JOIN sales.order_lines l ON l.order_id = o.id
JOIN sales.customers c ON c.id = o.customer_id
WHERE o.status <> 'cancelled'
AND c.account_type = 'trade';
SELECT c.name,
SUM(t.line_sales) - COALESCE(cr.credits, 0) AS net_sales,
SUM(t.line_cost) AS cost_of_sales
FROM reporting.trade_lines t
JOIN sales.customers c ON c.id = t.customer_id
LEFT JOIN (
SELECT o.customer_id, SUM(n.amount_net) AS credits
FROM sales.credit_notes n
JOIN sales.orders o ON o.id = n.order_id
WHERE (n.created_at AT TIME ZONE 'Europe/London')::date
BETWEEN :week_start AND :week_end
GROUP BY o.customer_id
) cr ON cr.customer_id = t.customer_id
WHERE t.order_day BETWEEN :week_start AND :week_end
GROUP BY c.name, cr.credits
ORDER BY net_sales DESC;
The view holds the exclusions, so every report built on it inherits them. A customer with credits but no orders that week drops out of this query, which is one more case the full model has to handle. A read replica will not let you create views, so the staging layer usually lives in a separate reporting database or warehouse that the replica feeds.
Sent 9 November 2026 · 07:00
Weekly trade sales and margin · Dellacott Trade Supplies (fictional)
£26,433 net trade sales,
2 Nov to 8 Nov.
Read from a replica of the order database with a SELECT-only role, modelled to the agreed definitions, then sent on a schedule.
- Net trade sales
- £26,433
- 32 trade orders
- Gross margin
- 35.1%
- £9,266
- vs prior week
- −30.4%
- Prior £37,970
- Raw SUM would say
- £34,224
- Before definitions applied
Connection
- Target
- Read replica (hot standby) of the order database
- Role
- reporting_ro
- Grants
- SELECT on sales.orders, sales.order_lines, sales.credit_notes, sales.customers
- Network
- SSH tunnel through a bastion host; bastion allowlists one fixed IP
- Guardrail
- statement_timeout = 60s (set on the role)
From raw total to reported figure
| Step | Rows | £ |
|---|---|---|
| Raw SUM of order value, all orders created in the week | 38 | £34,223.75 |
| Less cancelled orders | 4 | −£4,957.00 |
| Less internal and test accounts | 2 | −£2,358.75 |
| Less credit notes raised in the week | 3 | −£475.34 |
| Net trade sales | 32 | £26,432.66 |
Bridge agrees to the modelled total to the penny.
Output: net sales and margin by customer
| Customer | Orders | Net sales | Margin | vs prior wk |
|---|---|---|---|---|
| Danecroft Kitchensafter £13.31 credit | 9 | £7,515.69 | 35.8% | +6.7% |
| Dorrel & Pike Builders | 7 | £6,137.00 | 35.9% | −36.8% |
| Daskin Bathroomsafter £280.80 credit | 6 | £5,218.95 | 29.6% | +29.7% |
| Derrin Property Maintenance | 3 | £3,437.25 | 39.7% | +15.6% |
| Delphyn Interiorsafter £181.23 credit | 4 | £2,578.77 | 33.4% | −77.3% |
| Duxwell Shopfitting | 3 | £1,545.00 | 38.7% | −46.3% |
| Total | 32 | £26,432.66 | 35.1% | −30.4% |
Margin = (net sales − cost of goods on the order lines) ÷ net sales. Credit notes reduce sales in the week they are raised. Gold marks a fall of more than 25% on the prior week, sent to the sales lead for a look rather than read as a trend.
Scheduled run · log
PostgreSQL replica · reporting_ro
- 07:00:02Open tunnel to bastion, connect as reporting_roReplica · read-only sessionConnected
- 07:00:03Check replica lag before readingpg_last_xact_replay_timestamp() 6 s behindDone
- 07:00:05Read orders, credit notes, customers changed since last run38 orders · 3 credit notesSynced
- 07:00:09Apply staging rules and business definitions32 trade orders keptDone
- 07:00:10Reconcile modelled net sales to raw order total£34,223.75 → £26,432.66, all steps explainedDone
- 07:00:11Flag customers down more than 25% on prior week3 flaggedFor review
- 07:00:14Send weekly sales and margin report to finance and sales leadsEmail + PDFDelivered
- 07:00:14Write to the source databaseNot possible: role has SELECT onlySkipped
Worked example (illustrative, fictional)
Dellacott Trade Supplies is a fictional builders' merchant. Its trade customers order through a web portal backed by PostgreSQL. The weekly report covers Monday 2 to Sunday 8 November 2026 and is sent at 07:00 on Monday 9 November.
Start with what a quick query would give, then apply each definition:
| Step | Rows | Amount |
|---|---|---|
Raw SUM of order value, all orders created in the week |
38 orders | £34,223.75 |
| Less cancelled orders | 4 orders | −£4,957.00 |
| Less internal and test accounts | 2 orders | −£2,358.75 |
| = Gross trade sales | 32 orders | £26,908.00 |
| Less credit notes raised in the week | 3 notes | −£475.34 |
| = Net trade sales | £26,432.66 |
- Cancelled: £471.00 + £1,438.00 + £1,548.25 + £1,499.75 = £4,957.00. Two of those were placed five minutes apart by the same customer and both cancelled, the kind of pattern a raw total counts without comment.
- Internal and test: the staff counter account £1,980.75 plus a web checkout test order £378.00 = £2,358.75.
- Credits: £181.23 + £280.80 + £13.31 = £475.34. The £181.23 note was raised this week against an order placed the week before. Under the definition above it reduces this week.
- Cost of sales on the 32 trade orders: £17,166.97.
- Gross margin: £26,432.66 − £17,166.97 = £9,265.69.
- Margin %: £9,265.69 ÷ £26,432.66 = 35.1%.
- Prior week net trade sales were £37,970.31, so the change is (£26,432.66 − £37,970.31) ÷ £37,970.31 = −30.4%.
The raw total was £7,791.09 higher than the agreed figure. None of that gap is an error in the database. It is the difference between what the app stores and what the business means by sales.
The fall on the prior week is the line people will ask about. Three of the six customers were down more than 25%, so the report flags them to the sales lead rather than presenting a trend. With a handful of orders per customer each week, one large order landing a week later can swing a percentage a long way.
Step 4: send the output on a schedule
A scheduled report is a query plus a set of checks plus a delivery. The checks matter most, because nobody reads a routine email closely enough to spot that it is wrong.
| Check before sending | Why |
|---|---|
| Replica lag under a set limit | A stale copy gives a confident but old number |
| Row counts in line with recent weeks | An empty table or a failed load shows up here first |
| Bridge from raw total to reported total agrees | Every pound excluded is explained |
| Sharp moves flagged, not hidden | A person looks before anyone acts on a swing |
Delivery can be an email with a PDF, a link to a page, or a file in a shared folder. If people rebuild the numbers in a spreadsheet afterwards, see how that fits with connecting Excel files rather than emailing exports around. If the same question needs sales from the database alongside invoices from your accounts, automated reporting from Xero covers that side. Teams moving off a CRM's built-in reports run into a different set of limits, covered in the guide to Salesforce reporting limitations.
How IVP.ai runs this
The IVP.ai Data Layer connects to any SQL database using a read-only login you create, and pulls the tables you name into a governed warehouse on a schedule. How the connection reaches your network, by allowlisting or a tunnel, is agreed with whoever runs your database. The staging rules and business definitions above live there, written once, so the weekly report, a board pack and any one-off question all use the same figure for net sales. Because the modelling happens in the warehouse, the source database is only ever read, and it can be a replica.
Reports then run from the Data Layer on a schedule. A Deskless by IVP.ai agent can sit on the same data and flag the customers that moved sharply, drafting a note for the sales lead to review. It does not change anything in your systems unless you configure it to. More on how Deskless works, and on other sources in the integrations hub.
To see this on your own database, start with the free 48-hour pilot. Give us read-only access to up to three sources, such as your order database plus your accounts, and we clean the data and set one report or agent running on it within 48 hours. You then have 14 days of access to choose a plan or walk away.