Skip to main content
Back to Library
Prompt Engineering Guide

Mastering Write SQL query
on Llama 3.1 8B

Stop guessing. See how professional prompt engineering transforms Llama 3.1 8B's output for specific technical tasks.

The "Vibe" Prompt

"Write a SQL query to get the top 5 customers by total order amount from the 'orders' table and the 'customers' table. Join them on customer_id."
Low specificity, inconsistent output

Optimized Version

STABLE
You are a SQL expert. Your task is to write a SQL query. Think step-by-step to ensure correctness. ### Database Schema: `customers` table: `customer_id` INT, `customer_name` VARCHAR(255) `orders` table: `order_id` INT, `customer_id` INT, `total_amount` DECIMAL(10, 2) ### Goal: Retrieve the top 5 customers who have the highest total order amount. Include `customer_name` and their `total_order_amount`. ### Constraints: - Use an INNER JOIN. - Order the results in descending order of `total_order_amount`. - Limit the results to 5. ### Step-by-step thinking: 1. Identify the tables needed: `customers` and `orders`. 2. Determine the join condition: `customers.customer_id = orders.customer_id`. 3. Decide which columns to select: `customer_name` from `customers` and the sum of `total_amount` from `orders`. 4. Group the results by `customer_id` and `customer_name` to aggregate the total order amount per customer. 5. Order the aggregated results by the sum of `total_amount` in descending order. 6. Limit the final result set to 5 rows. ### SQL Query: ```sql
Structured, task-focused, reduced hallucinations

Engineering Rationale

The optimized prompt leverages several techniques to improve performance for Llama 3.1 8B specifically. Firstly, it explicitly states `You are a SQL expert. Your task is to write a SQL query.` which primes the model for the specific task and role. Secondly, it provides a `Database Schema` which is crucial for generating accurate and valid SQL, eliminating guesswork. Thirdly, it breaks down the `Goal` into clear, actionable `Constraints` which guides the model's output. Most importantly, the `Step-by-step thinking` section acts as a Chain-of-Thought (CoT) prompt, explicitly outlining the logical steps to arrive at the solution. This internal monologue guides the model's reasoning, reducing the chances of errors and leading to more robust outputs. The final `SQL Query:` header with the triple backticks explicitly tells the model to output only the SQL, avoiding conversational filler. For a smaller model like Llama 3.1 8B, this structured guidance is essential for high-quality, reliable output.

0%
Token Efficiency Gain
The optimized prompt explicitly defines the database schema.
The optimized prompt uses a 'Chain of Thought' approach (`Step-by-step thinking`).
The optimized prompt clearly outlines the desired output columns and aggregation.

Ready to stop burning tokens?

Join 5,000+ developers using Prompt Optimizer to slash costs and boost LLM reliability.

Optimize My Prompts