BENCHMARK OF OPEN-SOURCE LANGUAGE MODELS FOR TEXT-TO-SQL ON BRAZILIAN ONCOLOGY DATA
DOI:
https://doi.org/10.66104/zvzdrv85Keywords:
Text-to-SQL, Language models, Database, Oncology data, Execution-based evaluationAbstract
This work presents an experimental benchmark to evaluate open-source language models in the Text-to-SQL task, using questions in Brazilian Portuguese and public data on oncology care in Brazil. The study compared Qwen2.5-Coder 7B, DeepSeek-Coder 6.7B, and Llama 3, executed locally through Ollama, across four experimental scenarios defined by the presence or absence of the database schema in the prompt and by the presence or absence of linguistic variations in the questions. The evaluation was based on the Execution Accuracy (EX) metric, complemented by an analysis of error categories and generation and execution latencies. The results showed that Qwen2.5-Coder 7B achieved the best overall performance, with an EX of 80.0%, as well as the lowest average generation latency. Providing the database schema was the most influential factor, increasing the average model accuracy from 53.9% to 93.3%. The linguistic variations used did not degrade the average model performance, suggesting robustness only to the controlled superficial noise adopted in the experiment. The findings indicate that open-source language models can be applied to SQL query generation in controlled scenarios, although their performance strongly depends on the structural context provided and on the quality of the question formulation.Downloads
References
DOU, L. et al. Multispider: towards benchmarking multilingual text-to-SQL semantic parsing. In: AAAI CONFERENCE ON ARTIFICIAL INTELLIGENCE, 37., 2023, Washington, DC. Proceedings [...]. Washington, DC: AAAI Press, 2023. v. 37, n. 10, p. 12745–12753. Disponível em: https://doi.org/10.1609/aaai.v37i10.26367. Acesso em: 26 jan. 2026. DOI: https://doi.org/10.1609/aaai.v37i11.26499
GUO, D. et al. DeepSeek-Coder: when the large language model meets programming – the rise of code intelligence. arXiv preprint arXiv:2401.14196, 2024. Disponível em: https://arxiv.org/abs/2401.14196. Acesso em: 26 jan. 2026.
JOSÉ, M. A.; COZMAN, F. G. mRAT-SQL+GAP: a Portuguese text-to-SQL transformer. In: BRITTO, A.; VALDIVIA DELGADO, K. (ed.). Intelligent systems. Cham: Springer International Publishing, 2021. p. 511–525. DOI: https://doi.org/10.1007/978-3-030-91699-2_35
KIM, H. et al. FLEX: expert-level false-less execution metric for reliable text-to-SQL benchmark. In: CONFERENCE OF THE NATIONS OF THE AMERICAS CHAPTER OF THE ASSOCIATION FOR COMPUTATIONAL LINGUISTICS: HUMAN LANGUAGE TECHNOLOGIES, 2025, Albuquerque. Proceedings [...]. Albuquerque: Association for Computational Linguistics, 2025. p. 4448–4475. Disponível em: https://aclanthology.org/2025.naacl-long.228. Acesso em: 26 jan. 2026. DOI: https://doi.org/10.18653/v1/2025.naacl-long.228
LI, J. et al. Can LLM already serve as a database interface? A BIg bench for large-scale database grounded text-to-SQLs. In: CONFERENCE ON NEURAL INFORMATION PROCESSING SYSTEMS, 37., 2023, New Orleans. Proceedings[...]. New Orleans: Curran Associates, 2023. Disponível em: https://openreview.net/forum?id=dI4wzAE6uV. Acesso em: 26 jan. 2026.
MARCONI, M. A.; LAKATOS, E. M. Fundamentos de metodologia científica. 5. ed. São Paulo: Atlas, 2003. ISBN 85-224-3397-6.
OLLAMA. Ollama documentation. 2025. Disponível em: https://github.com/ollama/ollama. Acesso em: 15 jan. 2026.
PHAM, K. T. et al. Multilingual text-to-SQL: benchmarking the limits of language models with collaborative language agents. In: BOROVICA-GAJIC, R. et al. (ed.). Databases theory and applications. Singapore: Springer Nature Singapore, 2026. p. 108–123. ISBN 978-981-95-6196-4. Disponível em: https://doi.org/10.1007/978-981-95-6196-4_8. Acesso em: 26 jan. 2026. DOI: https://doi.org/10.1007/978-981-95-6196-4_8
PI, X. et al. Towards robustness of text-to-SQL models against natural and realistic adversarial table perturbation. In: ANNUAL MEETING OF THE ASSOCIATION FOR COMPUTATIONAL LINGUISTICS, 60., 2022, Dublin. Proceedings [...]. Dublin: Association for Computational Linguistics, 2022. p. 2007–2022. Disponível em: https://aclanthology.org/2022.acl-long.142/. Acesso em: 26 jan. 2026. DOI: https://doi.org/10.18653/v1/2022.acl-long.142
SHI, L. et al. A survey on employing large language models for text-to-SQL tasks. ACM Computing Surveys, New York, v. 58, n. 2, p. 1–37, set. 2025. ISSN 0360-0300. Disponível em: https://doi.org/10.1145/3737873. Acesso em: 26 jan. 2026. DOI: https://doi.org/10.1145/3737873
TENORIO, L. Oncology treatment DataSUS – Brazil (2013–2023). Kaggle, 2025. Disponível em: https://www.kaggle.com/datasets/lhucastenorio/oncology-treatment-datasus-brazil-20132023. Acesso em: 26 jan. 2026.
WOHLIN, C. et al. Experimentation in software engineering. Berlin; Heidelberg: Springer, 2012. ISBN 978-3-642-29044-2. Disponível em: https://doi.org/10.1007/978-3-642-29044-2. Acesso em: 26 jan. 2026. DOI: https://doi.org/10.1007/978-3-642-29044-2
WRETBLAD, N. et al. Understanding the effects of noise in text-to-SQL: an examination of the BIRD-bench benchmark. In: ANNUAL MEETING OF THE ASSOCIATION FOR COMPUTATIONAL LINGUISTICS, 62., 2024, Bangkok. Proceedings [...]. Bangkok: Association for Computational Linguistics, 2024. p. 356–369. Disponível em: https://aclanthology.org/2024.acl-short.34. Acesso em: 26 jan. 2026. DOI: https://doi.org/10.18653/v1/2024.acl-short.34
YU, T. et al. Spider: a large-scale human-labeled dataset for complex and cross-domain semantic parsing and text-to-SQL task. In: CONFERENCE ON EMPIRICAL METHODS IN NATURAL LANGUAGE PROCESSING, 2018, Brussels. Proceedings [...]. Brussels: Association for Computational Linguistics, 2018. p. 3911–3921. Disponível em: https://aclanthology.org/D18-1425/. Acesso em: 26 jan. 2026. DOI: https://doi.org/10.18653/v1/D18-1425
Apêndice A – Perguntas canônicas do benchmark
Este apêndice apresenta as 30 perguntas canônicas utilizadas no benchmark. Cada pergunta corresponde à formulação-base em português brasileiro, sem ruído linguístico, e está associada a uma consulta SQL de referência apresentada no Apêndice B.
ID
Pergunta canônica
Tipo de consulta
Dificuldade
br_0001
Quantos registros existem no conjunto de dados?
Agregação
Simples
br_0002
Quantos registros há por sexo?
Agregação
Intermediária
br_0003
Qual é a idade média dos pacientes por sexo?
Agregação
Intermediária
br_0004
Quais são os 10 CIDs (cid10) mais frequentes no conjunto de dados?
Agregação
Intermediária
br_0005
Quantos registros existem por ano de diagnóstico (dim_tempo.ano)?
Agregação com junção
Intermediária
br_0006
Quantos registros existem por mês de diagnóstico (dim_tempo.ano e dim_tempo.mes)?
Agregação com junção
Intermediária
br_0007
Qual é o tempo médio até tratamento (tempo_trat) por ano de diagnóstico?
Agregação com junção
Complexa
br_0008
Qual é o tempo mediano até tratamento (tempo_trat) no conjunto de dados?
Subconsulta
Complexa
br_0009
Quantos registros possuem tempo_trat preenchido (não nulo)?
Agregação
Intermediária
br_0010
Quais são as 10 UFs de residência (uf_resid) com mais registros?
Agregação
Complexa
br_0011
Quais são os 10 municípios de residência (mun_resid) com mais registros?
Agregação
Complexa
br_0012
Quais são as 10 UFs de tratamento (uf_trat) com mais registros?
Agregação
Complexa
br_0013
Qual é o total de registros em que a UF de residência é diferente da UF de tratamento?
Agregação
Intermediária
br_0014
Para cada UF de residência, qual é a proporção de casos cujo tratamento ocorreu na mesma UF?
Agregação
Complexa
br_0015
Quantos registros existem por tipo de tratamento (tratamento_id)?
Agregação
Intermediária
br_0016
Qual é a idade média por tipo de tratamento (tratamento_id)?
Agregação
Intermediária
br_0017
Quantos registros existem por estadiamento (estadiam_id)?
Agregação
Intermediária
br_0018
Qual é o tempo médio até tratamento por estadiamento (estadiam_id) considerando apenas tempo_trat não nulo?
Agregação
Intermediária
br_0019
Quantos registros existem por diagnostic_id (tipo de diagnóstico)?
Agregação
Intermediária
br_0020
Quais são os 10 CNES de diagnóstico (cnes_diagn) com mais registros?
Agregação
Complexa
br_0021
Quais são os 10 CNES de tratamento (cnes_trat) com mais registros?
Agregação
Complexa
br_0022
Qual é a quantidade de registros por sexo e ano de diagnóstico?
Agregação com junção
Complexa
br_0023
Entre 2018 e 2023, qual foi o total de registros por ano de diagnóstico?
Agregação com junção
Complexa
br_0024
No ano de 2020, quais são os 10 CIDs (cid10) mais frequentes?
Agregação com junção
Complexa
br_0025
No ano de 2020, qual é o total de registros por sexo?
Agregação com junção
Intermediária
br_0026
Qual é o tempo médio até tratamento por sexo no ano de 2020 (somente tempo_trat não nulo)?
Agregação com junção
Complexa
br_0027
Quantos registros possuem município de residência preenchido (mun_resid não nulo)?
Agregação
Intermediária
br_0028
Qual é a quantidade de registros cuja UF de diagnóstico é diferente da UF de residência?
Agregação
Intermediária
br_0029
Qual é a quantidade de registros cujo município de tratamento é diferente do município de residência (ambos não nulos)?
Agregação
Intermediária
br_0030
Qual é a idade mínima, máxima e média no conjunto de dados?
Agregação
Intermediária
Apêndice B – Consultas SQL de referência
Este apêndice apresenta as consultas SQL de referência, também denominadas gold SQL, utilizadas para avaliar as respostas geradas pelos modelos. Cada consulta está associada ao mesmo identificador da pergunta canônica apresentada no Apêndice A.
br_0001
SELECT COUNT(*) FROM fact_onco
br_0002
SELECT sexo, COUNT(*) AS n FROM fact_onco GROUP BY sexo ORDER BY n DESC
br_0003
SELECT sexo, AVG(idade) AS idade_media FROM fact_onco WHERE idade IS NOT NULL GROUP BY sexo ORDER BY idade_media DESC
br_0004
SELECT cid10, COUNT(*) AS n FROM fact_onco GROUP BY cid10 ORDER BY n DESC LIMIT 10
br_0005
SELECT t.ano, COUNT(*) AS n FROM fact_onco f JOIN dim_tempo t ON f.anomes_dia = t.anomes GROUP BY t.ano ORDER BY t.ano
br_0006
SELECT t.ano, t.mes, COUNT(*) AS n FROM fact_onco f JOIN dim_tempo t ON f.anomes_dia = t.anomes GROUP BY t.ano, t.mes ORDER BY t.ano, t.mes
br_0007
SELECT t.ano, AVG(f.tempo_trat) AS tempo_medio FROM fact_onco f JOIN dim_tempo t ON f.anomes_dia = t.anomes WHERE f.tempo_trat IS NOT NULL GROUP BY t.ano ORDER BY t.ano
br_0008
SELECT AVG(tempo_trat) FROM (SELECT tempo_trat FROM fact_onco WHERE tempo_trat IS NOT NULL ORDER BY tempo_trat LIMIT 2 - (SELECT COUNT(*) FROM fact_onco WHERE tempo_trat IS NOT NULL) % 2 OFFSET (SELECT (COUNT(*) - 1) / 2 FROM fact_onco WHERE tempo_trat IS NOT NULL))
br_0009
SELECT COUNT(*) FROM fact_onco WHERE tempo_trat IS NOT NULL
br_0010
SELECT uf_resid, COUNT(*) AS n FROM fact_onco WHERE uf_resid IS NOT NULL GROUP BY uf_resid ORDER BY n DESC LIMIT 10
br_0011
SELECT mun_resid, COUNT(*) AS n FROM fact_onco WHERE mun_resid IS NOT NULL GROUP BY mun_resid ORDER BY n DESC LIMIT 10
br_0012
SELECT uf_trat, COUNT(*) AS n FROM fact_onco WHERE uf_trat IS NOT NULL GROUP BY uf_trat ORDER BY n DESC LIMIT 10
br_0013
SELECT COUNT(*) FROM fact_onco WHERE uf_resid IS NOT NULL AND uf_trat IS NOT NULL AND uf_resid <> uf_trat
br_0014
SELECT uf_resid, CAST(SUM(CASE WHEN uf_trat = uf_resid THEN 1 ELSE 0 END) AS REAL) / COUNT(*) AS proporcao_mesma_uf FROM fact_onco WHERE uf_resid IS NOT NULL AND uf_trat IS NOT NULL GROUP BY uf_resid ORDER BY uf_resid
br_0015
SELECT tratamento_id, COUNT(*) AS n FROM fact_onco WHERE tratamento_id IS NOT NULL GROUP BY tratamento_id ORDER BY n DESC
br_0016
SELECT tratamento_id, AVG(idade) AS idade_media FROM fact_onco WHERE tratamento_id IS NOT NULL AND idade IS NOT NULL GROUP BY tratamento_id ORDER BY idade_media DESC
br_0017
SELECT estadiam_id, COUNT(*) AS n FROM fact_onco WHERE estadiam_id IS NOT NULL GROUP BY estadiam_id ORDER BY n DESC
br_0018
SELECT estadiam_id, AVG(tempo_trat) AS tempo_medio FROM fact_onco WHERE estadiam_id IS NOT NULL AND tempo_trat IS NOT NULL GROUP BY estadiam_id ORDER BY estadiam_id
br_0019
SELECT diagnostic_id, COUNT(*) AS n FROM fact_onco WHERE diagnostic_id IS NOT NULL GROUP BY diagnostic_id ORDER BY n DESC
br_0020
SELECT cnes_diagn, COUNT(*) AS n FROM fact_onco WHERE cnes_diagn IS NOT NULL GROUP BY cnes_diagn ORDER BY n DESC LIMIT 10
br_0021
SELECT cnes_trat, COUNT(*) AS n FROM fact_onco WHERE cnes_trat IS NOT NULL GROUP BY cnes_trat ORDER BY n DESC LIMIT 10
br_0022
SELECT f.sexo, t.ano, COUNT(*) AS n FROM fact_onco f JOIN dim_tempo t ON f.anomes_dia = t.anomes WHERE f.sexo IS NOT NULL GROUP BY f.sexo, t.ano ORDER BY t.ano, f.sexo
br_0023
SELECT t.ano, COUNT(*) AS n FROM fact_onco f JOIN dim_tempo t ON f.anomes_dia = t.anomes WHERE t.ano BETWEEN 2018 AND 2023 GROUP BY t.ano ORDER BY t.ano
br_0024
SELECT f.cid10, COUNT(*) AS n FROM fact_onco f JOIN dim_tempo t ON f.anomes_dia = t.anomes WHERE t.ano = 2020 GROUP BY f.cid10 ORDER BY n DESC LIMIT 10
br_0025
SELECT f.sexo, COUNT(*) AS n FROM fact_onco f JOIN dim_tempo t ON f.anomes_dia = t.anomes WHERE t.ano = 2020 GROUP BY f.sexo ORDER BY n DESC
br_0026
SELECT f.sexo, AVG(f.tempo_trat) AS tempo_medio FROM fact_onco f JOIN dim_tempo t ON f.anomes_dia = t.anomes WHERE t.ano = 2020 AND f.tempo_trat IS NOT NULL GROUP BY f.sexo ORDER BY tempo_medio DESC
br_0027
SELECT COUNT(*) FROM fact_onco WHERE mun_resid IS NOT NULL
br_0028
SELECT COUNT(*) FROM fact_onco WHERE uf_diagn IS NOT NULL AND uf_resid IS NOT NULL AND uf_diagn <> uf_resid
br_0029
SELECT COUNT(*) FROM fact_onco WHERE mun_trat IS NOT NULL AND mun_resid IS NOT NULL AND mun_trat <> mun_resid
br_0030
SELECT MIN(idade) AS idade_min, MAX(idade) AS idade_max, AVG(idade) AS idade_media FROM fact_onco WHERE idade IS NOT NULL
Apêndice C – Variações linguísticas controladas
Este apêndice apresenta as versões com ruído das perguntas canônicas. As variações foram construídas de forma controlada, preservando a intenção semântica original e mantendo a mesma consulta SQL de referência associada à pergunta canônica correspondente.
ID
Pergunta canônica
Pergunta com ruído
Tipo de variação
br_0001
Quantos registros existem no conjunto de dados?
Qtos registros existem no conjunto de dados?
Abreviação lexical
br_0002
Quantos registros há por sexo?
Qtd de registros por sexo?
Abreviação lexical; simplificação sintática
br_0003
Qual é a idade média dos pacientes por sexo?
Qual a idade média dos pacintes por sexo?
Erro ortográfico controlado; simplificação sintática
br_0004
Quais são os 10 CIDs (cid10) mais frequentes no conjunto de dados?
Quais são os 10 CIDs (cid10) mais frequentes nos dados?
Simplificação sintática
br_0005
Quantos registros existem por ano de diagnóstico (dim_tempo.ano)?
Quantos registros existem por ano de diag (dim_tempo.ano)?
Abreviação lexical
br_0006
Quantos registros existem por mês de diagnóstico (dim_tempo.ano e dim_tempo.mes)?
Qtd de registros por mês de diagnóstico (dim_tempo.ano e dim_tempo.mes)?
Abreviação lexical; simplificação sintática
br_0007
Qual é o tempo médio até tratamento (tempo_trat) por ano de diagnóstico?
Qual o tempo médio até tratamnto (tempo_trat) por ano de diagnóstico?
Erro ortográfico controlado; simplificação sintática
br_0008
Qual é o tempo mediano até tratamento (tempo_trat) no conjunto de dados?
Qual o tempo mediano até tratamnto (tempo_trat) no conjunto de dados?
Erro ortográfico controlado; simplificação sintática
br_0009
Quantos registros possuem tempo_trat preenchido (não nulo)?
Quantos registros têm tempo_trat preenchido (não nulo)?
Substituição lexical superficial
br_0010
Quais são as 10 UFs de residência (uf_resid) com mais registros?
Top 10 UFs de residência (uf_resid) com mais registros?
Reformulação coloquial; simplificação sintática
br_0011
Quais são os 10 municípios de residência (mun_resid) com mais registros?
Quais os 10 munic de residência (mun_resid) com mais registros?
Abreviação lexical; simplificação sintática
br_0012
Quais são as 10 UFs de tratamento (uf_trat) com mais registros?
Top 10 UFs de tratamento (uf_trat) com mais registros?
Reformulação coloquial; simplificação sintática
br_0013
Qual é o total de registros em que a UF de residência é diferente da UF de tratamento?
Qual o total de registros em que a UF de residência é dif da UF de tratamento?
Abreviação lexical; simplificação sintática
br_0014
Para cada UF de residência, qual é a proporção de casos cujo tratamento ocorreu na mesma UF?
Pra cada UF de residência, qual a proporção de casos cujo trat ocorreu na mesma UF?
Abreviação lexical; reformulação coloquial
br_0015
Quantos registros existem por tipo de tratamento (tratamento_id)?
Qtd de registros por tipo de tratamento (tratamento_id)?
Abreviação lexical; simplificação sintática
br_0016
Qual é a idade média por tipo de tratamento (tratamento_id)?
Qual a idade média por tipo de trat (tratamento_id)?
Abreviação lexical; simplificação sintática
br_0017
Quantos registros existem por estadiamento (estadiam_id)?
Qtd de registros por estadiam (estadiam_id)?
Abreviação lexical; simplificação sintática
br_0018
Qual é o tempo médio até tratamento por estadiamento (estadiam_id) considerando apenas tempo_trat não nulo?
Qual o tempo médio até tratamnto por estadiam (estadiam_id) considerando apenas tempo_trat não nulo?
Abreviação lexical; erro ortográfico controlado; simplificação sintática
br_0019
Quantos registros existem por diagnostic_id (tipo de diagnóstico)?
Qtd de registros por diagnostic_id (tipo de diagnóstico)?
Abreviação lexical; simplificação sintática
br_0020
Quais são os 10 CNES de diagnóstico (cnes_diagn) com mais registros?
Top 10 CNES de diagnóstico (cnes_diagn) com mais registros?
Reformulação coloquial; simplificação sintática
br_0021
Quais são os 10 CNES de tratamento (cnes_trat) com mais registros?
Top 10 CNES de tratamento (cnes_trat) com mais registros?
Reformulação coloquial; simplificação sintática
br_0022
Qual é a quantidade de registros por sexo e ano de diagnóstico?
Qtd de registros por sexo e ano de diagnóstico?
Abreviação lexical; simplificação sintática
br_0023
Entre 2018 e 2023, qual foi o total de registros por ano de diagnóstico?
Entre 2018 e 2023, qual o total de registros por ano de diagnóstico?
Simplificação sintática
br_0024
No ano de 2020, quais são os 10 CIDs (cid10) mais frequentes?
Em 2020, quais os 10 CIDs (cid10) mais frequentes?
Reformulação coloquial; simplificação sintática
br_0025
No ano de 2020, qual é o total de registros por sexo?
Em 2020, qual o total de registros por sexo?
Reformulação coloquial; simplificação sintática
br_0026
Qual é o tempo médio até tratamento por sexo no ano de 2020 (somente tempo_trat não nulo)?
Qual o tempo médio até tratamnto por sexo em 2020 (só tempo_trat não nulo)?
Erro ortográfico controlado; reformulação coloquial; simplificação sintática
br_0027
Quantos registros possuem município de residência preenchido (mun_resid não nulo)?
Qtd de registros com município de residência preenchido (mun_resid não nulo)?
Abreviação lexical; simplificação sintática
br_0028
Qual é a quantidade de registros cuja UF de diagnóstico é diferente da UF de residência?
Qtd de registros em que UF de diagnóstico é diferente da UF de residência?
Abreviação lexical; simplificação sintática
br_0029
Qual é a quantidade de registros cujo município de tratamento é diferente do município de residência (ambos não nulos)?
Qtd de registros em que município de trat é diferente do município de residência?
Abreviação lexical; simplificação sintática
br_0030
Qual é a idade mínima, máxima e média no conjunto de dados?
Qual a idade mínima, máxima e média no conjunto de dados?
Simplificação sintática
Apêndice D – Prompts utilizados nos experimentos
Todo o conteúdo instrucional foi enviado diretamente no campo prompt da requisição ao Ollama. Não foi utilizado system prompt separado.
D.1 Prompt dos cenários sem esquema
You are an expert data analyst. Generate ONE SQLite query.STRICT RULES:- Output ONLY the SQL query. No markdown, no explanation, no backticks.- SQLite ONLY. Do NOT use unsupported functions such as MEDIAN(), PERCENTILE(), DATE_TRUNC(), ILIKE.- Return a single executable SQL query.- Use only valid SQLite syntax.- Do not invent explanations or comments.- If top-k is requested, use ORDER BY ... DESC LIMIT k.- Always return deterministic output: include ORDER BY when LIMIT is used.- IMPORTANT: The SELECT column order MUST match the question requirement.EXAMPLES (follow style exactly):Q: Quantos registros existem no conjunto de dados?SQL: SELECT COUNT(*) FROM fact_oncoQ: Quais são os 10 CIDs mais frequentes?SQL: SELECT cid10, COUNT(*) AS n FROM fact_onco GROUP BY cid10 ORDER BY n DESC LIMIT 10Q: Qual o tempo médio até tratamento por ano?SQL: SELECT t.ano, AVG(f.tempo_trat) AS tempo_medio FROM fact_onco f JOIN dim_tempo t ON f.anomes_dia = t.anomes WHERE f.tempo_trat IS NOT NULL GROUP BY t.ano ORDER BY t.anoNow answer:Q (pt-BR): {PERGUNTA_EM_PORTUGUES}SQL:
D.2 Prompt dos cenários com esquema
You are an expert data analyst. Generate ONE SQLite query.STRICT RULES:- Output ONLY the SQL query. No markdown, no explanation, no backticks.- SQLite ONLY. Do NOT use unsupported functions such as MEDIAN(), PERCENTILE(), DATE_TRUNC(), ILIKE. - If the question asks for median, implement median using ORDER BY/LIMIT/OFFSET (no custom functions).- Use ONLY tables/columns that exist in the provided schema.- NEVER reference a table/alias that is not present in FROM/JOIN. - If you select dim_sexo.sexo, you MUST JOIN dim_sexo on fact_onco.sexo = dim_sexo.sexo.- Follow foreign keys: joins must match the schema (fact_onco FK -> dim_* PK).- Prefer using dim_tempo (ano, mes) by joining fact_onco.anomes_dia = dim_tempo.anomes when filtering/grouping by year/month.- If comparing UFs/municípios, use the correct columns: uf_resid/uf_trat/uf_diagn and mun_resid/mun_trat/mun_diagn.- When the question asks about "tempo até tratamento", use fact_onco.tempo_trat and ignore NULL values (WHERE tempo_trat IS NOT NULL).- For TOP-K by frequency or by any metric, EXCLUDE NULL values unless explicitly requested: - e.g., WHERE IS NOT NULL- If top-k is requested, use ORDER BY ... DESC LIMIT k.- Always return deterministic output: include ORDER BY when LIMIT is used.- If you use an alias (e.g., f, t, d), you MUST define it in FROM/JOIN (e.g., FROM fact_onco f). Never use undefined aliases.- Do not add unnecessary dimension joins. If a column exists in fact_onco (e.g., sexo, uf_resid, cid10), use it directly (no dim_* join).- For ratios/proportions, exclude NULLs for every column involved (e.g., uf_resid IS NOT NULL AND uf_trat IS NOT NULL).- When computing a ratio "by X", GROUP BY X and ORDER BY X unless the question asks for ordering by the metric.- For ANY aggregation/grouping by a categorical column X (COUNT/AVG by X, frequency tables, distributions): ALWAYS exclude missing values unless explicitly requested: add `WHERE X IS NOT NULL` before `GROUP BY X`.- IMPORTANT: The SELECT column order MUST match the question requirement and the examples' style (e.g., for "por ano, tempo médio", output: ano first, metric second).Schema:{ESQUEMA_COMPACTO_DO_BANCO}EXAMPLES (follow style exactly):Q: Quantos registros existem no conjunto de dados?SQL: SELECT COUNT(*) FROM fact_oncoQ: Quais são os 10 CIDs (cid10) mais frequentes?SQL: SELECT cid10, COUNT(*) AS n FROM fact_onco GROUP BY cid10 ORDER BY n DESC LIMIT 10Q: Qual o tempo médio até tratamento por ano?SQL: SELECT t.ano, AVG(f.tempo_trat) AS tempo_medio FROM fact_onco f JOIN dim_tempo t ON f.anomes_dia = t.anomes WHERE f.tempo_trat IS NOT NULL GROUP BY t.ano ORDER BY t.anoQ: Qual a mediana do tempo até tratamento?SQL: SELECT AVG(tempo_trat) AS mediana FROM ( SELECT tempo_trat FROM fact_onco WHERE tempo_trat IS NOT NULL ORDER BY tempo_trat LIMIT 2 - (SELECT COUNT(*) FROM fact_onco WHERE tempo_trat IS NOT NULL) % 2 OFFSET (SELECT (COUNT(*) - 1) / 2 FROM fact_onco WHERE tempo_trat IS NOT NULL) )Q: Em 2020, quantos registros por sexo?SQL: SELECT f.sexo, COUNT(*) AS n FROM fact_onco f JOIN dim_tempo t ON f.anomes_dia = t.anomes WHERE t.ano = 2020 GROUP BY f.sexo ORDER BY n DESCQ: Qual a proporção de casos em que a UF de tratamento é a mesma UF de residência, por UF de residência?SQL: SELECT uf_resid, CAST(SUM(CASE WHEN uf_trat = uf_resid THEN 1 ELSE 0 END) AS REAL) / COUNT(*) AS proporcao_mesma_uf FROM fact_onco WHERE uf_resid IS NOT NULL AND uf_trat IS NOT NULL GROUP BY uf_resid ORDER BY uf_residQ: Distribuição por estadiamento (estadiam_id), do mais frequente ao menos frequente.SQL: SELECT estadiam_id, COUNT(*) AS n FROM fact_onco WHERE estadiam_id IS NOT NULL GROUP BY estadiam_id ORDER BY n DESCNow answer:Q (pt-BR): {PERGUNTA_EM_PORTUGUES}SQL:
D.3 Esquema compacto utilizado nos prompts com esquema
# Schema dump: br_onco_v1TABLE dim_cid10(cid10:TEXT)TABLE dim_cnes(cnes_id:INTEGER)TABLE dim_diagnostic(diagnostic_id:INTEGER)TABLE dim_estadiam(estadiam_id:INTEGER)TABLE dim_municipio(mun_id:INTEGER, uf_id:INTEGER)TABLE dim_sexo(sexo:TEXT)TABLE dim_tempo(anomes:INTEGER, ano:INTEGER, mes:INTEGER)TABLE dim_tratamento(tratamento_id:INTEGER)TABLE dim_uf(uf_id:INTEGER)TABLE fact_onco(id:INTEGER, anomes_dia:INTEGER, anomes_trat:INTEGER, uf_resid:INTEGER, mun_resid:INTEGER, uf_diagn:INTEGER, mun_diagn:INTEGER, uf_trat:INTEGER, mun_trat:INTEGER, cnes_diagn:INTEGER, cnes_trat:INTEGER, cid10:TEXT, sexo:TEXT, idade:INTEGER, tratamento_id:INTEGER, diagnostic_id:INTEGER, estadiam_id:INTEGER, tempo_trat:INTEGER, dt_diag:TEXT, dt_trat:TEXT)FKs: fact_onco.anomes_trat -> dim_tempo.anomes; fact_onco.anomes_dia -> dim_tempo.anomes; fact_onco.cnes_trat -> dim_cnes.cnes_id; fact_onco.cnes_diagn -> dim_cnes.cnes_id; fact_onco.mun_trat -> dim_municipio.mun_id; fact_onco.mun_diagn -> dim_municipio.mun_id; fact_onco.mun_resid -> dim_municipio.mun_id; fact_onco.uf_trat -> dim_uf.uf_id; fact_onco.uf_diagn -> dim_uf.uf_id; fact_onco.uf_resid -> dim_uf.uf_id; fact_onco.estadiam_id -> dim_estadiam.estadiam_id; fact_onco.diagnostic_id -> dim_diagnostic.diagnostic_id; fact_onco.tratamento_id -> dim_tratamento.tratamento_id; fact_onco.cid10 -> dim_cid10.cid10; fact_onco.sexo -> dim_sexo.sexo
Downloads
Published
Issue
Section
License
Copyright (c) 2026 Fabrício de Carvalho Mota, Wanderson de Vasconcelos Rodrigues da Silva, Jeferson do Nascimento Soares

This work is licensed under a Creative Commons Attribution 4.0 International License.
Authors who publish in this journal agree to the following terms:
Authors retain copyright and grant the journal the right of first publication, with the work simultaneously licensed under the Creative Commons Attribution License, which permits the sharing of the work with proper acknowledgment of authorship and initial publication in this journal;
Authors are authorized to enter into separate, additional agreements for the non-exclusive distribution of the version of the work published in this journal (e.g., posting in an institutional repository or publishing it as a book chapter), provided that authorship and initial publication in this journal are properly acknowledged, and that the work is adapted to the template of the respective repository;
Authors are permitted and encouraged to post and distribute their work online (e.g., in institutional repositories or on their personal websites) at any point before or during the editorial process, as this may lead to productive exchanges and increase the impact and citation of the published work (see The Effect of Open Access);
Authors are responsible for correctly providing their personal information, including name, keywords, abstracts, and other relevant data, thereby defining how they wish to be cited. The journal’s editorial board is not responsible for any errors or inconsistencies in these records.
PRIVACY POLICY
The names and email addresses provided to this journal will be used exclusively for the purposes of this publication and will not be made available for any other purpose or to third parties.
Note: All content of the work is the sole responsibility of the author and the advisor.
