Skip to content
Notifications
Clear all

Walkthrough: Using Claude to generate and test SQL queries from plain English

1 Posts
1 Users
0 Reactions
1 Views
(@grafana_knight_shift_2)
Estimable Member
Joined: 2 months ago
Posts: 110
Topic starter   [#13199]

I've been pulling a lot of night shifts lately, and one recurring task is helping the dev team debug data issues by querying our application database. The problem? I'm a Prometheus/Grafana person—my SQL is functional, but writing complex joins or window functions from scratch at 3 AM is a recipe for errors. I started using Claude to bridge the gap between "what I need to know" and "the SQL to get it."

Here's my workflow: I describe the table schema and my question in plain English. Claude generates the query, and then I test it directly in our staging environment. The key is providing precise context.

Example: I needed to find user sessions that started but never completed a specific action last week. I fed Claude this:

```
Tables:
- users: id, created_at
- sessions: id, user_id, started_at, ended_at
- events: id, session_id, event_type, occurred_at

Question:
Give me a query to find all sessions from the last 7 days where the session started (exists in sessions table) but the event_type 'checkout_completed' does NOT exist for that session_id in the events table. Return the user_id, session_id, and session start time.
```

Claude generated:

```sql
SELECT
s.user_id,
s.id AS session_id,
s.started_at
FROM
sessions s
WHERE
s.started_at >= NOW() - INTERVAL '7 days'
AND NOT EXISTS (
SELECT 1
FROM events e
WHERE
e.session_id = s.id
AND e.event_type = 'checkout_completed'
)
ORDER BY
s.started_at DESC;
```

I ran it, got the list, and it was spot-on. What I appreciate is that Claude usually explains *why* it wrote the query that way, which helps me learn.

**My takeaways for making this work:**
* Be exhaustive with your schema description. Column names and relationships are critical.
* Always run generated queries in a safe, non-production environment first. I have a read-only replica for this.
* For complex logic, ask Claude to add explanatory comments in the SQL itself. This helps the next person on shift.

It's not perfect—sometimes it misinterpreds a vague relationship—but as a tool to get from zero to a working first draft, it's cut down my query-writing time significantly. Has anyone else tried a similar approach for observability or operational data exploration?

zzz


Sleep is for the weak


   
Quote