What are the actual top skills or specific prompting techniques for getting Claude Code to optimize really messy SQL queries without it constantly hallucinating table structures? I am honestly starting to panic a bit because I am at a small logistics startup here in Chicago and I have this massive deadline by Friday to get our main reporting dashboard running faster. The queries I am dealing with are absolute monsters, like 300 to 400 lines of nested CTEs and joins that look like spaghetti and my boss is breathing down my neck because the reports are timing out for our biggest client. I did some research and read that providing the EXPLAIN ANALYZE output is supposed to help but when I try that with the Claude CLI it just seems to get overwhelmed and starts suggesting indexes that I already have in place or it tries to use columns that don't even exist in our Postgres schema. I also saw some people saying you should use the system prompt to define the schema first but our schema is so huge it hits the token limit or just gets some of the foreign key relationships backwards and then the whole thing is useless. I really need to know if there is a way to get it to better understand the execution plan or if I should be breaking the queries down into smaller chunks for it to analyze one by one though that feels like it might miss the big picture of why the query is slow in the first place. I dont have the budget to bring in a consultant so I am basically banking on the AI to help me survive this week. Are there specific flags or a way to pipe the database metadata more effectively so it stops guessing? I feel like I am missing some secret sauce here...
I have been really happy with being more surgical about what I feed the CLI lately. I was so satisfied when I stopped dumping the whole schema and just used DBeaver Ultimate Edition v24.1 to grab the DDL for only the tables in that specific CTE.
> I also saw some people saying you should use the system prompt to define the schema first but our schema is so huge it hits the token limit Man, I've been in that exact spot back when I was managing a warehouse database that felt like it was basically held together with duct tape. In my experience, throwing the whole schema at Anthropic Claude 3.5 Sonnet is a recipe for disaster because it starts hallucinating relationships once the context window gets crowded. What worked for me was using a tool like SchemaCrawler Database Discovery Tool to extract only the relevant DDL for the tables actually used in those nested CTEs. Dont let it see the whole world. I found that piping just the DDL for the specific tables—not the whole DB—into the Claude CLI prevents those phantom column errors. I once tried to optimize a 500-line monster by just pasting it all, and it literally invented a column that cost me three hours of debugging. Honestly, feed it the schema for just the tables in the query and ask it to look at predicate pushdown first. Its way safer.