Loading…

Azure SQL Copilot (#03) – Será que ele consegue analisar uma query e sugerir melhorias?

Fala Pessoal,

Seguimos aqui nos testes e feedbacks do SQL Copilot para o time de produto.

Dessa vez vou mostrar se ele consegue analisar uma query, que provavelmente será uma das coisas que os clientes mais devem usar nele, principalmente quem não tem um DBA interno.

Criei uma tabela de teste e inseri alguns registros:

Vamos trabalhar com uma query bem simples para facilitar o aprendizado:

Ao rodar essa query no SSMS o SQL Server identifica um missed index e já nos sugere criar um índice na coluna Name.

Vamos ver se o Copilot também nos sugere isso?

Ele demora uns 40 segundos para responder e mostra essas mensagens enquanto processa:

 

Mandei ele melhorar uma query que faltava um índice e ele realmente achou o missed index igual encontramos lá no SSMS:

 

Resposta completa do Copilot:

“Based on the analysis of your query, I found a missing index recommendation that could potentially improve the performance of your query. Here are the details:

  • The query with the hash 0xD770ACA80BEFB236 could benefit from an index on the Name column of the Client table. The suggested index creation statement is as follows:
This index could potentially improve the performance of your query by 9,924.00%. Please note that this is an estimation and the actual benefit may vary. You should test this index in a non-production environment before implementing it in production.

Regarding anti-pattern queries, I didn’t find any in your workload. Azure SQL’s internal telemetry did not flag any of your queries as containing an antipattern. However, there still may be other types of antipatterns in your queries not detected by the telemetry.

Please continue with the following troubleshooting steps:

  • Identify recent changes in database workload.

For more information on identifying and adding missing indexes, you can refer to this guide.

For more information on tuning nonclustered missing index suggestions, you can refer to this guide.

For more information on performance problems due to antipattern queries, you can refer to this blog post.

Click here to view the query or queries we used for your answer in Azure Portal’s SQL editor.”

 

Criei o índice que ele indicou e fiz a mesma pergunta para ver o que ele me responderia:

Resposta do Copilot:

Based on the analysis of your query, there are no missing index recommendations or anti-pattern queries detected in your workload. This means that there are no suggestions for creating new indexes to improve the performance of your query, and no anti-patterns were identified in your query that could be causing performance issues.

Anti-patterns are certain query patterns that can lead to suboptimal performance. The types of anti-patterns that Azure SQL’s internal telemetry checks for include type conversion preventing seek, large number of OR in predicate, large IN, and non-optimal OR logic. However, it’s important to note that there may be other types of anti-patterns not detected by the telemetry.

Since no missing index recommendations or anti-pattern queries were found, it suggests that your query is already optimized for the current database schema and workload. However, performance can also be affected by other factors such as recent changes in database workload, so it’s recommended to identify any such changes for further troubleshooting.

For more information on identifying and adding missing indexes, you can refer to this guide.

For more information on tuning nonclustered missing index suggestions, you can refer to this guide.

For more information on performance problems due to antipattern queries, you can refer to this blog post.

Click here to view the query or queries we used for your answer in Azure Portal’s SQL editor.

Realmente não tem muito o que fazer com essa query após a criação do índice né?

Agora vamos criar um novo problema para essa query para ver se ele consegue analisar.

O famoso e bem comum problema de conversão implicita do NVARCHAR x VARCHAR.

Problema: Cliente tem uma coluna varchar e faz uma busca passando um parametro nvarchar. O SQL não consegue utilizar o índice existente na coluna e faz um SCAN.

Simulei esse problema com essa consulta abaixo que por usar o caracter N já deixa de fazer um seek no índice e faz um Scan na tabela:

Fiz a mesma pergunta que antes, mas ele não conseguiu me falar que o me gera um problema de performance e faz minha query fazer um Scan ao invés de um seek.

Até tenta me orientar se estou fazendo correto a query, mas a questão da performance não me ajudou:

E reparem que ele identificou o N do nvarchar.

Falou que posso omitir mas não me indicou que isso pode matar a performance do meu ambiente.

Entrei em contato com o time do produto e me falaram para tentar fazer essa pergunta passando o hash da query, que eles ainda estão trabalhando nesse tipo de pergunta passando o código direto no Copilot.

Encontrei o hash da minha query assim:

 

Perguntei ao Copilot e não é que ele realmente encontrou que a query contém um anti-pattern:

Destaque para essa parte:

“The internal SQL telemetry returned a row for the query hash 0xD770ACA80BEFB236, indicating that the query contains an anti-pattern. The anti-pattern type is TypeConvertPreventingSeek, which means that the query is performing a type conversion that prevents the SQL Server from using an index seek operation, potentially leading to less efficient query execution. The last occurrence of this anti-pattern was on 2024-06-05 16:10:54 (UTC). You may want to review the query and consider modifying it to avoid this anti-pattern. For more information on anti-pattern queries and how to address them, you can refer to this resource:

Nesse link ele mostra os tipos de Anti-Pattern que o Copilot deve pegar (futuros testes que teria que fazer):

The following are the antipatterns that can be captured during query optimization:

  • Column data type conversion preventing an index seek (implicit type conversion)* **
  • Non-optimal/unfriendly OR**
  • Large IN clause**
  • Large number of OR predicates**

There are other antipattern query scenarios that you should be aware of as you design your application such as:

  • Non-parameterized/ad-hoc workloads
  • Improper transaction management
  • Non-SARGable predicates

Agora sim o Copilot deu a resposta que eu queria e mostrando de forma bem clara que a conversão piora a performance da query:

“The anti-pattern type is TypeConvertPreventingSeek, which means that the query is performing a type conversion that prevents the SQL Server from using an index seek operation, potentially leading to less efficient query execution.”

 

Já perdi as contas de quantas queries já melhoramos só de acertar essa conversão implicita do nvarchar para o varchar.

Ainda precisou de eu passar o hash da query, mas em breve não deve precisar e mesmo quem não é DBA, que consegue ver o problema só de olhar a query, vai ter essa indicação de problema pelo Copilot.

Sensacional né!?

E é só o começo. Isso ainda deve evoluir demais e ficar cada vez mais rápido as respostas.

 

Quer ficar por dentro das novidades do mundo da IA e aprender junto com nosso Head de IA Rodrigo Ribeiro?

O Rodrigo criou um instagram, blog e canal no youtube só para falar der IA, o IA Talking. Não deixem de acompanhar:

 

Posts Anteriores:

 

Até o próximo artigo.

 

Abraços,

Fabrício Lima

CEO na Fabrício Lima Soluções em BD

Microsoft Data Platform MVP

Instagram:@fabriciofrancalima

Linkedin: https://www.linkedin.com/in/fabriciofrancalima/

Consultoria: [email protected]

 

Deixe uma resposta