Let AI Find the Code Behind a SQL Query

Aug 22, 2025

2 mins read

I work with performance optimization, often around SQL. I often see a slow query and need to find where the application builds it. In the past I did this by hand with tools like Visual Studio and Ctrl+F. It works, but it takes time - especially in big repositories.

I didn’t come up with this myself - a colleague showed me a quick example. I tried it on my projects, and now I use it a lot. The idea is simple:

Let a local AI agent search the repo instead of doing this work manually.

I run the agent on my machine. I give it the SQL text and, if needed, a couple of hints. In a few minutes it usually points me to the right file—and even the exact lines. This works well with the ORMs I use.


About the example in this post

For the sake of writing and showing screenshots, I wanted a small project that anyone can understand quickly.
I picked AdventureWorks.Web for the example here. It’s simple, but the same method works on much larger repositories I deal with every day.

As a side test while preparing this post, I also asked the agent to update the project from .NET Core 2.1 to .NET 8. It handled the migration (project file, packages, hosting model changes) in about five minutes, and additionally fixed a post-migration exception. I also asked the agent to change some entity and property names to make the example more challenging:

Agent updating entities

Obfuscated class


Why this method helps

  • Saves time: usually just a few minutes.
  • Understands patterns: can match tables/joins even when the query is generated by an ORM.
  • Less context switching: I can focus on the actual fix (indexes, plan shape, N+1, etc.).

What I usually tell the agent

Very short and direct:

Here is a SQL query. Find where the app generates it. List all possible occurances.


Screenshots

Generating the response takes a few minutes, and in very complex cases, 2-3 follow-ups:

Agent result: matching file and lines


This is not a big “AI project.” It’s just a small trick that removes boring work. I found it useful - feel free to try it.

If you like this article, please share it via your social media: