AI Prompts for SQL Queries

Top-rated AI prompts for SQL Queries. Copy any prompt and get instant results.

Your complete step-by-step AI guide for SQL Queries. Copy, paste, and get results.

AI Prompts for SQL Queries

Top-rated AI prompts for SQL Queries. Copy any prompt and get instant results.

Scroll to explore

This collection of tested AI prompts for SQL Queries covers write queries from scratch, optimize slow queries, debug sql errors, and more. Each prompt is copy-paste ready and free to use. Copy any prompt, add your specifics, and get professional SQL Queries results in seconds.

Stage 1

Write Queries from Scratch

Whether you need a simple lookup or a complex multi-table analysis, these prompts help you write correct SQL the first time.

Write SQL query from plain description

Write a SQL query that does the following: [DESCRIBE WHAT YOU WANT IN PLAIN ENGLISH]. My database has these tables: [DESCRIBE TABLE NAMES AND KEY COLUMNS]. The database is [MYSQL/POSTGRESQL/SQLITE/OTHER]. Include the query and explain each part.

Write Queries from Scratch

Write JOIN query across multiple tables

Write a SQL query that joins these tables: [TABLE 1 STRUCTURE], [TABLE 2 STRUCTURE], [TABLE 3 STRUCTURE]. I want to retrieve: [DESCRIBE OUTPUT]. Use the correct join type for each relationship and explain why you chose each join type.

Write Queries from Scratch

Write aggregation query with grouping

Write a SQL query that groups [TABLE NAME] by [COLUMN] and calculates [METRICS, e.g. sum, average, count, max]. Filter results to [CONDITIONS]. Include a HAVING clause if needed. Database: [DATABASE TYPE]. Table structure: [PASTE SCHEMA OR DESCRIBE]

Write Queries from Scratch

Write subquery or CTE

I need to write a query where I first calculate [INTERMEDIATE RESULT] and then use that result to find [FINAL RESULT]. Write this as a subquery and also as a CTE. Explain the difference and recommend which approach is more readable for this case. Tables: [DESCRIBE TABLES]

Write Queries from Scratch

Write window function query

I need a SQL query that uses window functions to calculate [DESCRIBE CALCULATION, e.g. running total, rank, lag/lead comparison] over [DESCRIBE PARTITION AND ORDER]. Write the query and explain what each part of the window function does. Table: [DESCRIBE TABLE]

Write Queries from Scratch

Stage 2

Optimize Slow Queries

A query that works but takes 30 seconds is not production-ready. These prompts help you understand why queries are slow and make them fast.

Optimize slow SQL query

This query is running too slowly. Analyze it and suggest specific optimizations: [PASTE QUERY]. Here is the table structure and approximate row counts: [PASTE SCHEMA AND SIZES]. Here is the EXPLAIN output if available: [PASTE EXPLAIN OUTPUT]. What are the main bottlenecks and how would you rewrite this to be faster?

Optimize Slow Queries

Add appropriate indexes

Suggest indexes I should add to improve query performance. Here are the most common query patterns against this table: [DESCRIBE QUERIES OR PASTE THEM]. Here is the current table structure: [PASTE SCHEMA]. What indexes would have the most impact, what is the trade-off for each one, and are there any existing indexes I should remove?

Optimize Slow Queries

Eliminate N+1 query pattern

I am running this query in a loop and it is causing an N+1 query problem: [DESCRIBE THE PATTERN]. Here is the code: [PASTE CODE]. Rewrite this as a single efficient SQL query that fetches all the data at once. Explain the performance difference.

Optimize Slow Queries

Rewrite query to avoid full table scan

The EXPLAIN plan for this query shows a full table scan. Here is the query: [PASTE QUERY]. Here is the schema: [PASTE SCHEMA]. How can I rewrite this query or add indexes to avoid the full scan? What is causing the optimizer to choose a full scan and what will make it use an index instead?

Optimize Slow Queries

Optimize query with many JOINs

This query joins [NUMBER] tables and is performing poorly. Here is the query: [PASTE QUERY]. Here are the table sizes: [DESCRIBE SIZES]. Suggest ways to reduce the join cost: better join order, pre-filtering, materializing subsets, or restructuring the query logic entirely.

Optimize Slow Queries

Stage 3

Debug SQL Errors

SQL errors can be cryptic. These prompts help you understand what went wrong and fix it without trial and error.

Debug SQL error message

I am getting this SQL error: [PASTE ERROR]. Here is the query that produced it: [PASTE QUERY]. Here is the relevant schema: [PASTE SCHEMA]. Explain what is causing this error in plain language and provide the corrected query.

Debug SQL Errors

Debug wrong query results

My query runs without error but returns wrong results. I expect [DESCRIBE EXPECTED RESULTS] but get [DESCRIBE ACTUAL RESULTS]. Here is the query: [PASTE QUERY]. Here is sample data: [PASTE SAMPLE DATA]. Walk through the query logic and identify where it diverges from my intention.

Debug SQL Errors

Fix GROUP BY or aggregate error

I am getting an error related to GROUP BY or aggregation: [PASTE ERROR]. Here is my query: [PASTE QUERY]. Explain why this error occurs and rewrite the query correctly. Also explain the general rule about what columns can appear in a SELECT when using GROUP BY.

Debug SQL Errors

Debug JOIN producing duplicate rows

My JOIN query is returning duplicate rows. Here is the query: [PASTE QUERY]. Here is sample data from each table: [PASTE SAMPLES]. Explain why duplicates are occurring, whether this is a data issue or a query logic issue, and how to fix it.

Debug SQL Errors

Fix NULL handling in query

My query is not handling NULL values correctly. The issue is: [DESCRIBE PROBLEM]. Here is the query: [PASTE QUERY]. Explain how SQL handles NULLs in comparisons, aggregations, and joins, and rewrite the query to handle NULLs correctly for my use case.

Debug SQL Errors

Stage 4

Design Schemas and Data Models

Good queries become easy when the schema is well-designed. These prompts help you think through data modeling decisions before writing code.

Design database schema for use case

Design a database schema for [DESCRIBE APPLICATION OR USE CASE]. I need to store [DESCRIBE DATA ENTITIES AND RELATIONSHIPS]. Provide the CREATE TABLE statements, explain your primary and foreign key choices, and identify any design decisions I should think carefully about. Database: [DATABASE TYPE]

Design Schemas and Data Models

Evaluate schema design

Review this database schema for design issues. Look for: normalization problems, missing indexes, poor naming conventions, problematic data types, and any design choices that will make future queries difficult: [PASTE SCHEMA]. Suggest specific improvements and explain the trade-offs.

Design Schemas and Data Models

Design for many-to-many relationship

I need to model a many-to-many relationship between [ENTITY A] and [ENTITY B]. Walk me through the correct way to design this in SQL: the junction table structure, the indexes needed, and how to write the most common queries against this structure.

Design Schemas and Data Models

Choose between normalization approaches

I am deciding how to normalize this data: [DESCRIBE DATA STRUCTURE]. Should I normalize it into [OPTION A] or keep it denormalized as [OPTION B]? Walk me through the trade-offs for each approach in terms of: storage, query complexity, update anomalies, and performance for my expected query patterns.

Design Schemas and Data Models

Plan schema migration

I need to change my database schema from [CURRENT STRUCTURE] to [NEW STRUCTURE]. This is a production database with live data. Write the migration SQL and explain: how to do this safely without downtime, what the rollback plan is if something goes wrong, and whether the migration needs to be done in multiple steps.

Design Schemas and Data Models

Frequently asked questions

What is the difference between WHERE and HAVING?+

WHERE filters rows before grouping and aggregation. HAVING filters groups after aggregation. Use WHERE when filtering on non-aggregated columns and HAVING when filtering on the result of an aggregate function like COUNT(), SUM(), or AVG().

When should I use a subquery versus a JOIN?+

JOINs are generally faster and more readable for combining related data from multiple tables. Use subqueries when you need to reference an aggregate result in your filter, when the subquery logic is clearer than the equivalent JOIN, or when you need to reference the same intermediate result multiple times (in which case, use a CTE).

Why does my query run slowly even with indexes?+

Common causes: the query optimizer is not using the index because it estimates a full scan is cheaper (often due to stale statistics), the index does not match the query's filter order, the query uses functions on indexed columns (which disables the index), or the data distribution makes indexes less effective. Use EXPLAIN to see which indexes the optimizer is choosing.

What is SQL injection and how do I prevent it?+

SQL injection occurs when user-supplied input is concatenated directly into SQL strings, allowing attackers to modify the query. Prevent it by always using parameterized queries or prepared statements rather than string concatenation, and by validating and sanitizing all user input at the application layer.

What is a CTE and when should I use it?+

A Common Table Expression (CTE) is a temporary named result set defined with the WITH keyword. Use CTEs when you need to reference an intermediate result multiple times, when breaking a complex query into readable steps, or when you need a recursive query. They improve readability without a performance cost in most modern databases.