Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

LangChain blueprint · Retail analytics

Text-to-SQL analytics assistant

An agent writes SQL from a plain-English question, behind read-only guardrails, and shows its query.

Steps
7
Subjective questions
32
Objective questions
32

The problem and the outcome

Problem: Business teams wait days for an analyst to write each one-off report.

Outcome: Self-serve answers in seconds, with the query shown so it can be trusted.

Architecture

Manager askssales by region?01SQL agenttool-calling02Schema & examplestables · columns03Write SQLquery tool04Guardrailsread-only · LIMIT05Warehouseread replica06Answer + chartSQL shown07relevant tablesrunrowserror · retry

How it works, step by step

  1. A manager asks a business question in plain English.
  2. A tool-calling agent plans how to answer it.
  3. Only the relevant table schemas, column notes and a few example queries are retrieved into the prompt.
  4. The agent writes a SQL query with its query tool.
  5. Guardrails run first: a read-only database user, an allow-list of tables and a row LIMIT; a failing query goes back to the agent with the error.
  6. The query runs on a read replica, never on the production primary.
  7. The answer comes back as a sentence and a chart, with the SQL shown so an analyst can check it.

Tech stack

  • LangChain SQL toolkit / custom query tool
  • Warehouse read replica (Postgres, BigQuery, Snowflake)
  • Read-only database role
  • Schema and example-query retrieval
  • Chart rendering

Key design decisions

  • A read-only database user and an allow-list of tables, enforced by the database, not the prompt.
  • Retrieve only the relevant table schemas and example queries, so large warehouses fit in the prompt.
  • Show the SQL with every answer, so analysts can verify it.

Common mistakes

  • Connecting the agent with a role that can write or drop tables.
  • Queries without LIMIT or time filters that scan billions of rows.
  • Ambiguous business terms (revenue, active user) the model guesses at.

What to measure

  • Execution accuracy on a test set of questions
  • Query error and retry rate
  • Warehouse cost per question
  • Analyst corrections

Most-asked interview questions

Subjective questions 32

1How do you make a text-to-SQL agent safe?Asked almost every time

Least privilege first: a read-only role limited to approved tables or views, statement timeouts and row limits, and a read replica. Validate the SQL before running it (parse it, block anything but SELECT), and never let model output become part of a command without those checks.

2Design a text-to-SQL analytics assistant.Asked almost every time

The user asks a question; the assistant retrieves relevant tables, columns, business definitions and example queries from a semantic layer, generates SQL with the schema in context, validates it (parse, allow only SELECT, check tables and columns, add limits), runs it on a read replica with a read-only role and timeouts, then summarises results with the SQL shown and a chart, and asks for clarification when the question is ambiguous.

3How do you give the model the right schema context?Asked almost every time

Do not paste the whole warehouse: retrieve only relevant tables by embedding table and column descriptions, include column types, keys, sample values and join paths, and add curated example question–SQL pairs for common metrics.

4How do you handle ambiguous questions?Asked almost every time

Detect ambiguity (which revenue, which date, which region) and ask a clarifying question or state assumptions explicitly, using business definitions from the semantic layer to pick standard interpretations.

5How do you help the model with business definitions?Very often asked

Provide a semantic layer or glossary: what 'revenue', 'active user' or 'region' mean, with example queries for common questions. Retrieve the relevant definitions with the schema. Curated views that already encode the definitions work even better.

6What is a semantic layer and why does it help?Very often asked

A curated layer (dbt metrics, Cube, LookML) defining business metrics, dimensions and joins once. Generating queries against it reduces errors because 'active customer' or 'net revenue' have one agreed definition.

7How do you validate generated SQL before running it?Very often asked

Parse it with a SQL parser, reject anything other than SELECT, check referenced tables and columns exist and are allowed, enforce row limits and timeouts, and optionally run EXPLAIN to catch very expensive plans.

8How do you handle errors from the database?Very often asked

Return the error message to the model to fix the query, limit retries, and if it still fails, ask the user to rephrase or show the closest working query with explanation.

9How do you enforce row-level and column-level security?Very often asked

Run queries as a role that only sees permitted data (row-level security policies, secure views), never rely on the prompt to hide columns, and mask sensitive columns in the warehouse.

10How do you present results so users can trust them?Very often asked

Show the SQL, the definitions used, the time range and filters in plain language, the result table and a suitable chart, and let users open the query in their BI tool.

11How do you keep costs under control on a cloud warehouse?Very often asked

Use LIMIT and partition filters, prefer aggregated tables, set query cost or byte limits (BigQuery maximum bytes billed), cache results for repeated questions and monitor per-user usage.

12How do you build an evaluation set for text-to-SQL?Very often asked

Collect real business questions with gold SQL written by analysts, include ambiguous and tricky joins, measure execution accuracy (results match gold), and track performance per question category.

13How do you retrieve the right tables when the warehouse has thousands of them?Very often asked

Index table and column descriptions, sample values and common joins, retrieve the most relevant tables for each question with semantic search plus keyword matching, then give the model only those schemas. Learn from which tables successful past queries used.

14How do you handle metrics that have a precise business definition, such as active users?Very often asked

Define them once in the semantic layer or as approved SQL snippets, have the assistant use those definitions instead of inventing calculations, and show which definition was applied in the answer.

15How do you evaluate a text-to-SQL system?Often asked

Build a set of questions with correct SQL or expected results. Run the generated SQL and compare results (execution accuracy) rather than the SQL text, since many queries are equivalent. Track failures by type: wrong table, wrong join, wrong filter.

16Why compare results instead of SQL text?Often asked

Different SQL can be correct, so execution accuracy compares result sets from the generated and gold queries rather than exact string matches.

17How do you handle dates and time zones?Often asked

Define a standard business calendar and time zone in the semantic layer, resolve relative dates ('last quarter') in code to explicit ranges, and show them in the answer.

18How do you support follow-up questions?Often asked

Keep conversation state with the previous query and filters, so 'and by region?' modifies the last query instead of starting over.

19How do you choose the chart type?Often asked

Pick from the result's shape: time series as line charts, category comparisons as bar charts, parts of a whole only with few categories, and tables for detailed data.

20How do you prevent prompt injection through data values?Often asked

Treat query results as data, never execute instructions found in them, keep SQL execution read-only, and restrict which tables can be queried.

21How do you improve accuracy over time?Often asked

Log questions, generated SQL, results and user feedback, have analysts correct failures, add corrected pairs to examples and the evaluation set, and update descriptions of confusing columns.

22When should the assistant refuse to answer?Often asked

When data needed is not available, the user lacks permission, or the question needs judgement beyond data; it should say so and suggest who to ask.

23How do you document tables for the model?Often asked

Write clear descriptions of each table and column (meaning, units, allowed values, gotchas like soft-deleted rows), and keep them in the catalogue alongside lineage.

24How do you explain a generated query to a non-technical user?Often asked

Translate the SQL into a short plain-language description of what was counted, filtered and grouped, list the tables and date range used, and let the user expand to see the full SQL.

25How do you handle questions that need data from two systems?Often asked

Answer only if both are joined in the warehouse with known keys, otherwise say the data lives in separate systems. Never join on fuzzy matches like names without telling the user about the risk.

26How do you keep the assistant fast for repeated questions?Often asked

Cache generated SQL by normalised question and user permissions, cache query results with short TTLs for dashboards, and suggest saved queries for common questions instead of regenerating SQL each time.

27How do you let users correct a wrong answer?Often asked

Let them flag the answer and edit the filters or the SQL, run the corrected query, store the pair as a new evaluation example after review, and use it as a few-shot example for similar questions.

28Which models work well for text-to-SQL?Sometimes asked

Strong reasoning and code models generally do best; test candidates on your own evaluation set because schema complexity varies widely.

29How do you handle very large result sets?Sometimes asked

Aggregate in SQL, return only the top rows with a count, and offer a download or BI link for full results.

30What should be logged?Sometimes asked

Question, user, retrieved schema, SQL, validation result, execution time, rows returned, cost and feedback.

31How do you roll out the assistant?Sometimes asked

Start with one well-modelled domain (sales or support), a group of analysts as early users, and expand domains as accuracy is proven.

32How do you handle questions about the future, like next quarter's sales?Sometimes asked

Explain that the assistant reports historical data, offer the trend or a simple forecast only if an approved forecasting model or table exists, and label any projection clearly as an estimate.

Objective questions 32

1What is the strongest protection against destructive SQL?Asked almost every time
  1. ALower temperature
  2. BA longer schema description
  3. CA polite system prompt
  4. DA read-only database roleCorrect answer

Why: The database refuses writes, whatever the model generates.

2What schema context should be sent to the model?Asked almost every time
  1. AThe entire warehouse
  2. BNo schema
  3. CRandom tables
  4. DOnly relevant tables retrieved by descriptionCorrect answer

Why: Smaller context, fewer mistakes.

3What should the assistant do with an ambiguous question?Asked almost every time
  1. AAsk for clarification or state assumptionsCorrect answer
  2. BGuess silently
  3. CRefuse always
  4. DRun every interpretation

Why: Avoid confident wrong answers.

4Which statements should validated SQL allow?Asked almost every time
  1. AAny statement
  2. BDELETE with a WHERE
  3. CDROP in staging
  4. DSELECT onlyCorrect answer

Why: Analytics must stay read-only.

5Why run analytics queries on a read replica?Very often asked
  1. AThey need no indexes
  2. BReplicas are free
  3. CSo heavy queries do not slow the production primaryCorrect answer
  4. DReplicas allow writes

Why: It isolates analytical load from the transactional database.

6What is a semantic layer?Very often asked
  1. AAgreed definitions of metrics, dimensions and joinsCorrect answer
  2. BA database backup
  3. CA UI theme
  4. DA cache

Why: One definition of revenue.

7How is row-level security enforced?Very often asked
  1. AAsking the model to filter
  2. BHiding columns in the prompt
  3. CTrusting users
  4. DA database role with RLS or secure viewsCorrect answer

Why: Prompts are not security.

8What should be shown with every answer?Very often asked
  1. AModel settings
  2. BNothing
  3. CThe SQL and the definitions usedCorrect answer
  4. DOnly a number

Why: Users can verify the logic themselves.

9How should a database error be handled?Very often asked
  1. ARetry forever
  2. BDrop the table
  3. CReturn it to the model to fix, with limited retriesCorrect answer
  4. DShow a blank page

Why: Then ask the user to rephrase.

10What limits warehouse cost?Very often asked
  1. ALIMITs, partition filters and byte capsCorrect answer
  2. BLarger queries
  3. CNo caching
  4. DSELECT * everywhere

Why: Monitor usage per user.

11Relative dates like 'last quarter' should be…Very often asked
  1. ALeft as text
  2. BResolved in code to explicit rangesCorrect answer
  3. CGuessed by the model
  4. DIgnored

Why: Show them in the answer.

12With thousands of tables, the model should receive…Very often asked
  1. ANo schema
  2. BRandom tables
  3. COnly the retrieved relevant schemasCorrect answer
  4. DEvery table's schema

Why: Focused context improves accuracy and cost.

13Metrics like 'active users' should use…Very often asked
  1. AThe model's own calculation
  2. BWhatever the user types
  3. CThe largest number
  4. DThe approved semantic-layer definitionCorrect answer

Why: One definition keeps answers consistent.

14Execution accuracy compares…Often asked
  1. ASQL text character by character
  2. BThe results of running the generated and reference queriesCorrect answer
  3. CQuery length
  4. DToken counts

Why: Different SQL can give the same correct result, so results are compared.

15Which chart suits a time series?Often asked
  1. AWord cloud
  2. BScatter of IDs
  3. CLine chartCorrect answer
  4. DPie chart

Why: Line charts show trends over time.

16How are follow-up questions handled?Often asked
  1. AIgnore context
  2. BAsk the user to repeat everything
  3. CModify the previous query from conversation stateCorrect answer
  4. DStart over each time

Why: Keeps conversations natural.

17What does EXPLAIN help catch?Often asked
  1. AUI bugs
  2. BNetwork issues
  3. CVery expensive query plansCorrect answer
  4. DSpelling errors

Why: Before running the query.

18How should huge result sets be returned?Often asked
  1. ANothing
  2. BAs screenshots
  3. CAggregated with top rows and a BI linkCorrect answer
  4. DAll rows in chat

Why: Keeps answers readable.

19Column descriptions should include…Often asked
  1. AThe author's name
  2. BRandom notes
  3. CNothing
  4. DMeaning, units and gotchasCorrect answer

Why: Prevents misread columns.

20When should the assistant refuse?Often asked
  1. AFor every question
  2. BWhen the query is short
  3. CWhen data or permission is missingCorrect answer
  4. DNever

Why: Say who to ask instead.

21How does accuracy improve over time?Often asked
  1. AIt cannot
  2. BBy raising temperature
  3. CBy deleting logs
  4. DAnalysts correct failures, added to examples and evalsCorrect answer

Why: This closes the feedback loop.

22Results containing instructions should be…Often asked
  1. AExecuted
  2. BSent to admins
  3. CTreated as data and ignored as commandsCorrect answer
  4. DFollowed

Why: This prevents prompt injection.

23A query explanation for business users should include…Often asked
  1. AOnly the raw SQL
  2. BThe database password
  3. CThe model's name
  4. DWhat was counted, filtered and the date rangeCorrect answer

Why: Plain language builds trust.

24Joining two systems on customer names is…Often asked
  1. ARequired
  2. BFaster and safer
  3. CRisky and must be disclosedCorrect answer
  4. DAlways exact

Why: Name matches create false joins.

25Repeated questions are sped up by caching…Often asked
  1. AOnly the chart colours
  2. BNothing
  3. CUser passwords
  4. DSQL and results scoped to permissionsCorrect answer

Why: Caches must respect who may see the data.

26User corrections should become…Often asked
  1. ADeleted logs
  2. BReviewed evaluation and few-shot examplesCorrect answer
  3. CIgnored notes
  4. DProduction SQL without review

Why: Corrections improve future answers.

27Which BigQuery setting caps query cost?Sometimes asked
  1. ASlots per user
  2. BMaximum bytes billedCorrect answer
  3. CMax rows
  4. DTimeout only

Why: Rejects expensive scans.

28Where should a rollout begin?Sometimes asked
  1. AAll domains at once
  2. BThe messiest data
  3. CExecutives only
  4. DOne well-modelled domainCorrect answer

Why: Expand as accuracy is proven.

29Which tool can define a semantic layer?Sometimes asked
  1. Adbt metrics or CubeCorrect answer
  2. BPhotoshop
  3. CSlack
  4. DExcel macros only

Why: Shared metric definitions.

30What should be logged per question?Sometimes asked
  1. AOnly the question
  2. BNothing
  3. COnly errors
  4. DSQL, validation, rows, cost and feedbackCorrect answer

Why: These logs are needed to improve.

31How are model candidates chosen?Sometimes asked
  1. ABy name
  2. BTested on your own evaluation setCorrect answer
  3. CBy popularity
  4. DBy release date

Why: Warehouse schemas vary widely.

32A question about next quarter's sales should…Sometimes asked
  1. AReturn last year's total as fact
  2. BBe answered only with a labelled, approved forecastCorrect answer
  3. CGet an invented number
  4. DRun a random query

Why: Projections must be clearly marked.

Track your progress through every blueprint in your dashboard.

Start learning