
Databases usually fail quietly: an orders table stops growing, an error-rate spikes, a queue backs up, or a critical integration starts writing zeros. If you only notice these issues when users complain or dashboards are checked, you’re already late. The simplest prevention is a query threshold alert: run a read-only query on a schedule and notify you when a result crosses a boundary.
This guide explains how to set up query threshold alerts on iPhone in a way that’s secure, low-impact, and reliable—whether you’re checking PostgreSQL/MySQL counts, MongoDB aggregates, or business KPIs. You’ll learn how to choose thresholds, write safe queries, schedule checks, reduce false alarms, and route notifications.
What is a query threshold alert?
A query threshold alert is a rule like:
- Run a database query every N minutes
- Extract a numeric value (count, sum, max, average, error rate)
- If the value is >, <, or outside a range, send a notification
Examples:
- Order pipeline: Alert if new paid orders in the last 15 minutes < 3
- Data quality: Alert if null email ratio > 0.5%
- Operational health: Alert if job queue depth > 5,000
- Fraud/anomaly: Alert if refunds today > 2× daily baseline
Step 1: Pick the metric and define the threshold
Start with one metric that is both meaningful and measurable via a cheap, read-only query. Then decide what “bad” looks like. Thresholds fall into a few common patterns:
| Pattern | When to use | Example threshold |
|---|---|---|
| Lower bound | Something stops happening | Paid orders last 30 min < 1 |
| Upper bound | Runaway growth / backlog | Queue depth > 10,000 |
| Range | Healthy band is known | Error rate 0%–1% |
| Change detection | Sudden deltas matter | Count drops > 30% vs yesterday |
Rule of thumb: prefer thresholds tied to user impact (payments, signups, API errors) over purely internal metrics. The alert should tell you “this hurts” not just “this is interesting.”
Choose a time window that matches reality
Most false alarms come from mismatched windows. For example, “orders last 5 minutes” will oscillate at low volume. Use a longer window (15–60 minutes) for low-traffic systems, and a shorter window for high-traffic systems.
Step 2: Write a low-impact, read-only query
The safest mobile-driven monitoring is read-only, using indexed filters and minimal returned data (one row, one number). A good threshold query has these properties:
- Uses an indexable predicate (e.g.,
created_atrange, status) - Avoids scanning huge tables without filters
- Returns a single numeric result
- Does not lock rows (no
FOR UPDATE, no writes)
PostgreSQL example: “paid orders in the last 30 minutes”
SELECT COUNT(*) AS paid_orders_30m
FROM orders
WHERE status = 'paid'
AND paid_at >= NOW() - INTERVAL '30 minutes';
Index tip: if the table is large, consider an index like (status, paid_at) or a partial index on paid orders.
MySQL example: “error logs in the last 10 minutes”
SELECT COUNT(*) AS errors_10m
FROM api_logs
WHERE level = 'error'
AND created_at >= (NOW() - INTERVAL 10 MINUTE);
MongoDB example: “failed payments today”
[
{ "$match": {
"status": "failed",
"createdAt": { "$gte": ISODate("2026-01-01T00:00:00Z") }
}},
{ "$count": "failed_payments_today" }
]
In practice, you’ll generate “start of day” dynamically. If your alerting tool supports parameters/macros, use them; otherwise, monitor a rolling window (e.g., last 24 hours) to avoid date math.
Step 3: Decide the schedule (and be realistic about iPhone constraints)
To set up query threshold alerts on iPhone, you typically rely on a scheduled check that runs in the cloud or via a service that can execute reliably even when your phone is asleep. iOS background execution is intentionally limited; your phone is best as a notification endpoint and control plane, not the worker that runs database checks 24/7.
Choose a frequency based on:
- Urgency: payments/errors might be 1–5 minutes; analytics drift might be hourly
- Query cost: heavier queries should run less often
- Noise tolerance: faster checks can produce more flapping
Suggested starting points
- Critical revenue paths: every 2–5 minutes
- Queues, ETL health, ingestion: every 5–15 minutes
- Data quality checks: every 1–6 hours
Step 4: Define the alert condition and message
When a threshold triggers, you want an actionable notification that answers:
- What happened? (“Paid orders in 30m dropped below 1”)
- How bad is it? (current value and threshold)
- Where? (environment, region, service name)
- What to do next? (link to runbook/dashboard if available)
Example message template:
[PROD] Orders alert: paid_orders_30m=0 (threshold < 1)
Next: check payment provider status + recent deploys + order worker logs
Step 5: Reduce false positives (hysteresis, consecutive failures, and time windows)
Threshold alerts often “flap” around the boundary. Three techniques reduce noise dramatically:
1) Require consecutive breaches
Alert only if the condition is true for 2–3 checks in a row.
- Example: check every 5 minutes, alert after 3 consecutive breaches = 15 minutes of persistence
2) Use hysteresis (separate trigger and recovery thresholds)
Instead of triggering at > 100 and recovering at <= 100, use:
- Trigger: > 100
- Recover: < 80
3) Prefer rolling windows over point-in-time counts
“Count in last 30 minutes” is usually more stable than “count right now.” Rolling windows also map better to user impact.
Step 6: Keep database access secure (minimum privileges)
Any alerting setup that can reach production data must be treated like a production integration. Follow these security basics:
- Create a dedicated read-only user with access only to required schemas/collections
- Use TLS for database connections
- Allowlist network access (IP allowlists, VPN, or private networking when possible)
- Avoid secrets in screenshots/notes; use a secret manager if the tool supports it
- Audit and rotate credentials on a schedule
PostgreSQL: minimal read-only role (example)
-- create user
CREATE ROLE alert_reader LOGIN PASSWORD '...';
-- allow connect
GRANT CONNECT ON DATABASE appdb TO alert_reader;
-- allow schema usage + read tables
GRANT USAGE ON SCHEMA public TO alert_reader;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO alert_reader;
-- ensure future tables are readable
ALTER DEFAULT PRIVILEGES IN SCHEMA public
GRANT SELECT ON TABLES TO alert_reader;
Adjust schemas and permissions to the smallest possible footprint.
Step 7: Validate with test data and a rollout checklist
Before relying on an alert, force it to trigger safely (in staging, or with a temporary threshold) and confirm the notification arrives on your iPhone.
- Sanity check the query: returns one numeric value and runs fast
- Check explain plan (SQL): ensure indexes are used
- Set an intentionally easy threshold to verify delivery
- Confirm timezone assumptions (especially “today” queries)
- Decide ownership: who responds, and what’s the escalation path?
- Write a tiny runbook: 3–5 steps to investigate
Common examples you can adapt
Inventory: “low stock SKUs”
SELECT COUNT(*) AS low_stock_skus
FROM inventory
WHERE on_hand <= 5 AND is_active = TRUE;
Pipeline: “stuck jobs older than 20 minutes”
SELECT COUNT(*) AS stuck_jobs
FROM jobs
WHERE status = 'running'
AND started_at < NOW() - INTERVAL '20 minutes';
Data quality: “null email ratio”
SELECT
(SUM(CASE WHEN email IS NULL THEN 1 ELSE 0 END)::float / COUNT(*)) AS null_email_ratio
FROM users
WHERE created_at >= NOW() - INTERVAL '1 day';
Troubleshooting: when alerts don’t match reality
- The query is correct but noisy: widen the time window, add consecutive breaches, or add hysteresis.
- The query is slow: add/adjust indexes, filter earlier, or pre-aggregate into a summary table.
- Timezone bugs: use UTC consistently; avoid “midnight local time” unless required.
- Missing notifications: verify notification permissions on iOS, and ensure your alerting service retries on transient failures.
- High cardinality tables: avoid unbounded scans; consider materialized views or incremental counters.
Putting it all together: a practical pattern
A strong “mobile-first” monitoring pattern looks like this:
- One read-only query per alert, returning a single number
- Schedule based on urgency (5–15 minutes is a common baseline)
- Trigger after 2–3 consecutive breaches
- Alert text includes current value + threshold + environment
- Read-only credentials, TLS, and minimal access
If you want an iOS-centered workflow where you can manage these checks and receive push notifications on your phone, tools such as Query Alert provide a purpose-built way to turn database queries into scheduled threshold alerts without building a custom monitoring stack.