Generate Sql Query

LangChain Hub prompt: reply-next/generate-sql-query

R
reply-next
·May 3, 2026·
210 0 68
$7.99
Prompt
843 words

Dada la consulta en lenguaje natural:{question} y teniendo en cuenta el historico de conversacion genera únicamente la consulta SQL que devuelve los resultados correspondientes de acuerdo con la siguiente estructura de tablas: TABLE public.product ( id serial PRIMARY KEY, title varchar NOT NULL, promt varchar, "accountId" uuid REFERENCES public.account ON DELETE SET NULL, "apiKeyId" integer REFERENCES public.api_key ON DELETE SET NULL, type product_type_enum NOT NULL, "externalId" varchar NOT NULL UNIQUE, status product_status_enum DEFAULT 'off' NOT NULL, "languageCode" varchar, temperature integer, "createdAt" timestamp DEFAULT now() NOT NULL, "onlyFuture" boolean DEFAULT true NOT NULL, "reviewIds" text, "totalReviews" integer DEFAULT 0 NOT NULL, "starsBreakdown" text DEFAULT '0text' NOT NULL, "countryCode" varchar, link varchar, "storageUri" varchar, total_reply integer DEFAULT 0 NOT NULL, "updatedAt" timestamp DEFAULT now() NOT NULL, r_only_text boolean DEFAULT true NOT NULL, active_start timestamp DEFAULT 'date' NOT NULL, auto_reply boolean DEFAULT true NOT NULL, is_execlude_low_star boolean DEFAULT false NOT NULL, is_execlude_words boolean DEFAULT false NOT NULL, execlude_words text DEFAULT '' NOT NULL ); TABLE public.review ( id serial PRIMARY KEY, review_id varchar, "reviewType" varchar NOT NULL, review_content text DEFAULT '' NOT NULL, reply_content text DEFAULT '' NOT NULL, review_date varchar NOT NULL, review_update varchar NOT NULL, "createdAt" timestamp DEFAULT now() NOT NULL, "updatedAt" timestamp DEFAULT now() NOT NULL, "productId" integer REFERENCES public.product ON DELETE CASCADE, reply_gen_text text DEFAULT '' NOT NULL, alert_sent boolean DEFAULT false NOT NULL, author_name text, author_url text DEFAULT '' NOT NULL, rating integer, version_app varchar, reply_date varchar, status varchar ); TABLE public.account ( id uuid DEFAULT uuid_generate_v4() NOT NULL PRIMARY KEY, name varchar NOT NULL, "createdAt" timestamp DEFAULT now() NOT NULL, "ownerId" uuid UNIQUE REFERENCES public."user" ON DELETE SET NULL, status account_status_enum DEFAULT 'active' NOT NULL, "has_low_Star" boolean DEFAULT false NOT NULL, keywords text ); Requisitos de la Tarea: 1. Dependencia de la Pregunta: La consulta SQL generada debe responder específicamente a la pregunta en lenguaje natural proporcionada, utilizando las relaciones y campos relevantes de las tablas. 2. Filtros de Fecha: Ajusta la consulta para incluir filtros de fechas basados en la interpretación de la consulta en lenguaje natural. Utiliza ::date al comparar el campo review_date. 3. Limita la cantidad de resultados: Utiliza LIMIT cuando creas conveniente (segun la pregunta) para limitar la cantidad de registros devueltos. 3. Formato de Respuesta: Devuelve solo la consulta SQL ajustada en una sola línea sin ningún tipo de formato adicional, explicación, ni delimitadores. Evita incluir ```sql. 4. Filtros por Autor: Si la pregunta solicita comentarios de una persona en particular, utiliza la cláusula WHERE con el campo review_author_name empleando LIKE '%nombre a buscar%' para filtrar adecuadamente.

Consulta SQL Base (Referencia de Relaciones de Datos): SELECT concat('product: ', p.title) as product, concat('review from: ', r."reviewType") as review_from, concat('rating: ', r.rating), concat('review: ', r.review_content) as review, concat('review author name: ', r.author_name) as review_author_name, concat('review date: ', r.review_date), concat('reply content: ', r.reply_content), concat('review date: ', r.review_date), concat('version app: ', r.version_app), '⟨END_OF_REGISTER⟩' as end FROM product p INNER JOIN account a ON p."accountId" = a.id INNER JOIN review r ON p.id = r."productId" WHERE a.id = '{account_id}' ORDER BY r.review_date DESC;

Requisitos Obligatorios de la Tarea • Ajusta la fecha actual a {current_date}. • Siempre colocar el WHERE a.id = '{account_id}' • Ajusta esta consulta para incluir filtros adicionales de fechas basados en la interpretación de la consulta en lenguaje natural. • Asegúrate de que la consulta SQL generada sea precisa y eficiente. • Cuando compares la fecha review_date utiliza ::date para convertir el tipo de dato • No incluyas ningún contexto adicional, solo la consulta SQL completa en una sola línea, sin ningún formato adicional, explicación, ni delimitadores. • Si solicitan información relacionadas a reviews positivas, considera positivas las que tienen un rating superior a 3. • Si consultan sobre android (Play), ios o maps, estan haciendo referencia a la plataforma y esta se encuentra en el atributo reviewType de la tabla review, compara todo en lower case para evitar errores. • Si preguntan por los comentarios de una persona en particular utiliza la clausula "where" y el campo review_author_name para filtrar, recomiendo que utilices LIKE '%nombre a buscar%' ya que el nombre puede no venir completo. • Ten en cuenta que el motor de base de datos es postgres, agrega de forma obligaria comillas dobles a todos los nombres de las columnas cuando generes la consulta. • Considera un review como negativa cuando es menor a 4, y positiva cuando es mayor a 3.

IMPORTANTE: Si no existe una consulta como tal, sino mas bien una interacción de saludo o algo similar, realiza la consulta sobre las reviews de este mes, desde el día 1, teniendo en cuenta que hoy es {current_date}. La consulta SQL generada debe adaptarse dinámicamente a la pregunta proporcionada, utilizando las relaciones y campos de las tablas de manera eficiente y precisa. Agrega un LIMIT (si lo crees necesario) al final para adaptar la respuesta a la consulta realizada evitando tener un gran volumen de datos para generar la respuesta. Devuelve solo la consulta SQL ajustada en una sola línea sin ningun tipo de formato, evita poner ```sql.


Historico: {chat_history}

{question}

This prompt contains variables shown as ⟨variable_name⟩. Replace them with your own values before using.

How to Use

Use with LangChain: hub.pull("reply-next/generate-sql-query")

Need help?

Connect with verified experts who can help you succeed.

Related Prompts

More prompts in Coding & Development

View All
Coding & Development
Universal

This Prompt Ads Sequential Function Calling To Models Other Than GPT 0613

This prompt ads sequential function calling to models other than GPT-0613

H
homanp$2.99
39,910 89,588
Coding & Development
Universal

Create a personalized workout routine

Tailor a workout routine specifically designed for individual fitness goals

K
Kay Tam$2.99
23,370 23,405
Coding & Development
Universal

GODMODE CHEATCODE

God Writes You a Letter Today. This is will help you find the perfect Bible Scripture that will guide you through a current problem you're facing.

D
digitaljeff$3.99
13,574 13,622
Coding & Development
Universal

Creating a Personal Finance Tracker with [Technology/Tool]

Learn to create a personal finance tracker using [Technology/Tool]. Get code samples and budgeting tips.

B
BowTiedThinkerFree
376 385
Coding & Development
ChatGPT

Build an entire application using bubble.io with ChatGPT4

Build an entire app with bubble.io, assisted by chatGPT4, that knows bubble very well and is accurate 95% of the time. This prompt will help you maximize the quality of chatGPT assistance. Having detailed and step-by-step instructions is essential to progress fast with Bubble. This initial prompt will help you get started on a good basis. Follow it because I will make it even better.

T
Tristanyway$5.99
1,280 1,300
Coding & Development
Universal

Become LawyerGPT

Are you in a legal bind? This prompt can help you gain knowledge about how to handle your legal proceedings. DISCLAIMER: Please meet with a real lawyer to discuss your options.

C
Chase Curtis$2.99
1,063 1,076