Simplifying data queries with AI-Driven SQL

Simplifying data queries with AI-Driven SQL

[???? Para vers?o em Portugês, role pra baixo ]



[ENG version]

Have you ever found yourself lost in a forest of data, desperately trying to find the right path to a well-founded decision?

We know that a good strategy must be built based on data and evidence. Qualitatively, we manage to learn to do this with relative ease: we construct questionnaires, conduct interviews, hold focus groups, and utilize various other approaches where we have considerable autonomy. However, qualitative data collection sometimes takes time, as it is a kind of artisanal work that is personalized and brings unique insights. Another thing we also know: it is dangerous to make decisions based solely on qualitative data, and often, because it requires more effort, we run the risk of conducting research that may not be quantitatively relevant to the key result targeted by the strategy.

In theory, quantitative analyses would require less effort because it is enough to have good questions, instrumented data collection, and data available for consultation. In this way, we could answer questions and hypotheses with data and, from the identified opportunities, complement them with qualitative research insights.

The described scenario seems perfect, doesn't it? Yes. However, we encounter structural problems that often hinder this perfect execution:

  1. Good Questions: Everything starts here. Without a good question, we cannot define success metrics and restrictive metrics for risk mitigation. For PMs, PDs, and Engineers, asking good questions is essential in the product process. According to Amplitude , starting with clear questions and objectives is fundamental for effective data instrumentation because, without it, it is difficult to know which events and metrics should be tracked and analyzed.
  2. Data Instrumentation: Without good questions, we will not know what to collect and how to collect it. What are the data? When should they be sent? Correct data instrumentation is essential to ensure we are collecting relevant and accurate information for analysis. Amplitude highlights that a well-defined tracking plan helps maintain the consistency and accuracy of collected data, enabling more effective analysis and actionable insights.
  3. Data Querying: Assuming the previous steps are being met, we already consider an analytical maturity of more than 60%. So, to close the cycle, we need proficiency in querying and transforming data, whether through SQL, analytics tools (Power BI, Looker Studio, etc.), or even in a spreadsheet (Sheets or Excel). Everything is valid. Just don't fail at the last moment. And it is exactly here that, often, the effort fails.

To query and transform data, it is necessary to have, in addition to good analytical thinking, technical knowledge of formulas to execute with assertiveness and autonomy. In my journey as a PD and PM, I have always noticed product managers reluctant and unmotivated to dedicate themselves to this. But in recent years, I have noticed that market demand and new technological trends with AI have changed this perspective.


My journey with SQL and data

When I started my career in design, I was immersed in the world of creativity, human behavior, and visual solutions focused on efficiency, good usability, and user satisfaction. Over time, my trajectory led me to product management, a field where data plays a crucial role. It was a reality shock: from a predominantly artistic environment to the need to understand and handle large volumes of data.

I remember the first time I had to deal with SQL. The syntax seemed like a secret code, and each execution error was a frustrating puzzle. Like many Product Managers without technical training, I had to learn the hard way, endlessly researching on the internet, watching tutorials, and taking data analytics courses (including the Data Analytics course from Tera , which I highly recommend). This learning made me realize the importance of being self-taught and proactive in the pursuit of knowledge.

Working at Hotmart , a company that values the democratization of data, I found a platform that allowed anyone to build their queries and conduct analyses. However, this came with the challenge of mastering SQL. From then on, I began to stand out for my ability to extract valuable insights from data, helping my colleagues to do the same.

AI entered the scene as a game-changer. With ChatGPT, I could transform simple questions into complex SQL queries without worrying so much about technical details. This not only accelerated my work process but also increased my confidence and autonomy in data analysis. AI taught me to look at data in a new way, where efficiency and accuracy are achieved with less effort and more intelligence.

But doesn't Hotmart have a Data Team? Yes, and without them, we wouldn't have evolved this far. They are responsible for structure, scalability, and democratization. Moreover, there are Data Analysts allocated to various teams. However, there is a productive capacity of these professionals who, being specialists, dedicate themselves to more complex studies that generate greater impact. And there arises the opportunity for Product Managers to become allies, working collaboratively with Analysts in building analyses and, most importantly, learning a little more from these incredible professionals.

See? With the right organization, there's plenty of work for everyone: PM, DA, and AI – a winning combination.


The role of AI in simplifying SQL queries

Sometimes we find ourselves stuck in front of a screen, trying to decipher the logic of a complex SQL query, wishing there was an easier way to get the insights we need. The truth is, many PMs share this frustration. SQL, although powerful, can be intimidating for those without solid technical training. But what if there was a way to simplify this process?

Artificial Intelligence, especially through tools like ChatGPT, is changing the game. With AI, the complexity of SQL syntax dissolves, allowing you to focus on what really matters: making strategic data-driven decisions. Instead of getting lost in the minutiae of coding, you can simply describe what you need in natural language, and AI does the rest. According to Product School , AI can transform complex SQL queries into simple natural language requests, saving time and allowing product managers to focus on strategy.


??Hands-On!

Let's imagine you launched a new feature in your product and need to monitor user adoption and retention of this feature. Using ChatGPT, you can simplify the entire process of creating the necessary queries for this analysis.

Prompt for ChatGPT:

"I am launching a new feature on our online education platform. I need to track the daily adoption rate and weekly retention rate of users who use this feature. I have two tables: 'usuarios' (columns: 'id_usuario', 'data_registro') and 'atividades_funcionalidade' (columns: 'id_usuario', 'id_funcionalidade', 'tipo_atividade', 'data_atividade'). Create an SQL query to monitor the daily adoption rate and a query for the weekly retention rate."


?? Copy this prompt


Generated query for daily Adoption Rate:

SELECT 
    DATE(af.data_atividade) AS data,
    COUNT(DISTINCT af.id_usuario) AS numero_usuarios
FROM 
    atividades_funcionalidade af
WHERE 
    af.id_funcionalidade = 'nova_funcionalidade'
GROUP BY 
    DATE(af.data_atividade)
ORDER BY 
    data;        


Generated query for weekly Retention Rate:

WITH semana_inicial AS (
    SELECT 
        id_usuario,
        MIN(DATE(data_atividade)) AS primeira_semana
    FROM 
        atividades_funcionalidade
    WHERE 
        id_funcionalidade = 'nova_funcionalidade'
    GROUP BY 
        id_usuario
),
uso_semanal AS (
    SELECT 
        id_usuario,
        DATE(data_atividade) AS semana,
        COUNT(*) AS uso_na_semana
    FROM 
        atividades_funcionalidade
    WHERE 
        id_funcionalidade = 'nova_funcionalidade'
    GROUP BY 
        id_usuario, DATE(data_atividade)
)
SELECT 
    si.primeira_semana,
    COUNT(CASE WHEN DATE_PART('week', us.semana) = DATE_PART('week', si.primeira_semana) + 1 THEN 1 END) AS retencao_na_semana_1,
    COUNT(CASE WHEN DATE_PART('week', us.semana) = DATE_PART('week', si.primeira_semana) + 2 THEN 1 END) AS retencao_na_semana_2
FROM 
    semana_inicial si
JOIN 
    uso_semanal us ON si.id_usuario = us.id_usuario
GROUP BY 
    si.primeira_semana
ORDER BY 
    si.primeira_semana;        


Continuous adjustments and learning

A happy ending? Of course not!

Artificial Intelligence will make mistakes, a lot of them, before getting it right. The difference is that it makes mistakes much faster until it gets it right than a human, and that we cannot deny. Therefore, when a generated query presents an error or does not produce the expected results, you should inform the error to ChatGPT, and it will adjust the query to correct the problem. Distrusting data is always important, whether it is a query generated by AI or by a human.

And the best part of this whole process is that AI explains the entire construction and adjustment process in natural language, allowing humans to also learn the meaning of formulas, calculations, etc. This iterative process allows continuous learning and constant improvement in creating and adjusting SQL queries. It's fascinating!


Artificial intelligence is transforming the way we interact with data, simplifying complex processes and empowering product professionals to make faster and more informed decisions. Adopting tools like ChatGPT not only facilitates the creation of SQL queries but also promotes continuous learning, making us more autonomous and efficient.

The paradigm shift brought by AI is evident: technical complexity dissipates, giving way to a more intuitive and accessible interaction with data. The result? More precise and data-driven strategic decisions, increased team confidence, and more efficient collaboration between PMs, data analysts, and AI tools.

If you have already experienced the transformative power of AI in your data analysis or are curious to learn more, share your experiences or questions in the comments. Let's explore together how technology can continue to revolutionize the field of product management.

And remember: with PMs, DAs, and AI working together, the future is promising and full of opportunities.


References:

  1. Amplitude Blog: "Analytics Instrumentation"
  2. Product School: "The Ultimate Guide to AI Resources for Product Managers"






[PT-BR version]

Simplificando consultas de dados com SQL gerado por IA

Você já se perdeu em uma floresta de dados, tentando desesperadamente encontrar o caminho certo para uma decis?o bem embasada?

Sabemos que uma boa estratégia deve ser construída baseada em dados e evidências. Qualitativamente, conseguimos aprender a fazer isso com certa facilidade: construímos questionários, realizamos entrevistas, conduzimos focus groups e utilizamos diversas outras abordagens nas quais temos bastante autonomia. No entanto, as coletas qualitativas por vezes demandam certo tempo, pois s?o uma espécie de trabalho artesanal, personalizado e que traz insights únicos. Outra coisa que também já sabemos: é perigoso tomar decis?es baseando-se apenas em dados qualitativos e, por muitas vezes, demandar um esfor?o maior, corremos o risco de fazer pesquisas que talvez n?o sejam quantitativamente relevantes em rela??o ao resultado-chave direcionado pela estratégia.

Em teoria, análises quantitativas demandariam um esfor?o menor, pois basta ter boas perguntas, coletas de dados instrumentalizadas e dados disponíveis para consulta. Dessa forma, poderíamos responder perguntas e hipóteses com dados e, a partir das oportunidades identificadas, complementar com insights qualitativos de pesquisas.

O cenário descrito parece perfeito, n?o é? Sim. Porém, encontramos problemas estruturais que muitas vezes dificultam essa execu??o perfeita:

  1. Boas perguntas: Tudo come?a por aí. Sem uma boa pergunta, n?o conseguimos definir boas métricas de sucesso e métricas restritivas para mitiga??o de riscos. Para PMs, PDs e Engenheiros, fazer boas perguntas é algo essencial no processo de produto. Segundo a Amplitude , come?ar com perguntas e objetivos claros é fundamental para uma instrumenta??o eficaz de dados, pois sem isso, é difícil saber quais eventos e métricas devem ser rastreados e analisados.
  2. Instrumenta??o de dados: Sem boas perguntas, n?o saberemos o que coletar e como coletar. Quais s?o os dados? Quando eles devem ser enviados? A instrumenta??o correta de dados é fundamental para garantir que estamos coletando informa??es relevantes e precisas para análise. A Amplitude destaca que um plano de rastreamento bem definido ajuda a manter a consistência e a precis?o dos dados coletados, permitindo uma análise mais eficaz e insights mais acionáveis.
  3. Consulta de dados: Considerando que os passos anteriores estejam sendo atendidos, já consideramos uma maturidade analítica de mais de 60%. Ent?o, para fechar o ciclo, precisamos de proficiência em consultar e transformar dados, seja através de SQL, ferramentas de analytics (Power BI, Looker Studio, etc) ou até mesmo em uma planilha (Sheets ou Excel). Tudo vale. Só n?o vale morrer na praia. E é exatamente aqui que, muitas vezes, a bola bate na trave.

Para consultar e transformar dados, é necessário ter, além de um bom pensamento analítico, conhecimento técnico em fórmulas para executar com assertividade e autonomia. Em minha jornada como PD e PM, sempre percebi product managers pouco dispostos e motivados a se dedicar a isso. Mas, nos últimos anos, tenho percebido que a demanda do mercado e as novas tendências tecnológicas com IA têm mudado essa perspectiva.


Minha jornada com SQL e Dados

Quando comecei minha carreira em design, eu estava imerso no mundo da criatividade, comportamento humano e solu??es visuais focadas em eficiência, boa usabilidade e satisfa??o do usuário. Com o tempo, minha trajetória me levou à gest?o de produtos, um campo onde os dados desempenham um papel crucial. Foi um choque de realidade: de um ambiente predominantemente artístico para a necessidade de entender e manipular grandes volumes de dados.

Lembro-me das primeiras vezes que precisei lidar com SQL. A sintaxe parecia um código secreto, e cada erro de execu??o era um enigma frustrante. Como muitos Product Managers sem forma??o técnica, tive que aprender na marra, pesquisando incansavelmente na internet, assistindo tutoriais e fazendo cursos de data analytics (inclusive, o curso de Data Analytics da Tera é sensacional, recomendo). Esse aprendizado me fez perceber a importancia de ser autodidata e proativo na busca por conhecimento.

Trabalhando na Hotmart , uma empresa que valoriza a democratiza??o dos dados, encontrei uma plataforma que permitia a qualquer pessoa construir suas queries e realizar análises. Contudo, isso veio com o desafio de dominar SQL. A partir daí, comecei a me destacar por minha capacidade de extrair insights valiosos dos dados, ajudando meus colegas a fazerem o mesmo.

A IA entrou em cena como um divisor de águas. Com o ChatGPT, pude transformar perguntas simples em consultas SQL complexas, sem precisar me preocupar tanto com os detalhes técnicos. Isso n?o apenas acelerou meu processo de trabalho, mas também aumentou minha confian?a e autonomia na análise de dados. A IA me ensinou a olhar para os dados de uma maneira nova, onde a eficiência e a precis?o s?o alcan?adas com menos esfor?o e mais inteligência.

Mas na Hotmart n?o tem um time de Dados? Sim, e sem eles n?o teríamos evoluído tanto até aqui. Eles s?o responsáveis pela estrutura, escalabilidade e democratiza??o. Além disso, existem Data Analysts alocados em diversos times. Porém, existe uma capacidade produtiva desses profissionais que, por serem especialistas, se dedicam a estudos mais complexos e que geram maior impacto. E aí surge a oportunidade de Product Managers se tornarem aliados, trabalhando de forma colaborativa com os Analistas na constru??o das análises e, o mais precioso, aprendendo um pouco mais com esses profissionais incríveis.

Tá vendo? Se organizar direitinho, tem trabalho pra todes: PM + DA + IA, um trio de milh?es.


O papel da IA na simplifica??o de consultas SQL

às vezes nos pegamos parados diante de uma tela, tentando decifrar a lógica de uma consulta SQL complexa, desejando que houvesse uma maneira mais fácil de obter os insights de que precisamos. A verdade é que muitos PMs compartilham dessa frustra??o. SQL, embora poderoso, pode ser intimidante para aqueles que n?o têm uma forma??o técnica sólida. Mas, e se houvesse uma maneira de simplificar esse processo?

A Inteligência Artificial, especialmente através de ferramentas como o ChatGPT, está mudando esse jogo. Com a IA, a complexidade da sintaxe SQL se dissolve, permitindo que você se concentre no que realmente importa: tomar decis?es estratégicas baseadas em dados. Em vez de se perder nas minúcias da codifica??o, você pode simplesmente descrever o que precisa em linguagem natural, e a IA faz o resto. Segundo a Product School , a IA pode transformar consultas SQL complexas em simples solicita??es de linguagem natural, economizando tempo e permitindo que os gerentes de produto se concentrem na estratégia.


M?o na Massa!

Vamos imaginar que você lan?ou uma nova funcionalidade em seu produto e precisa acompanhar a ado??o e a reten??o dos usuários dessa funcionalidade. Utilizando o ChatGPT, você pode simplificar todo o processo de cria??o das queries necessárias para essa análise.


Prompt para ChatGPT:

"Estou lan?ando uma nova funcionalidade em nossa plataforma de educa??o online. Preciso acompanhar a taxa de ado??o diária e a taxa de reten??o semanal dos usuários que utilizam essa funcionalidade. Tenho duas tabelas: 'usuarios' (colunas: 'id_usuario', 'data_registro') e 'atividades_funcionalidade' (colunas: 'id_usuario', 'id_funcionalidade', 'tipo_atividade', 'data_atividade'). Crie uma query SQL para acompanhar a taxa de ado??o diária e uma query para a taxa de reten??o semanal."


?? Copie esse prompt


Query gerada para Taxa de Ado??o diária:

SELECT 
    DATE(af.data_atividade) AS data,
    COUNT(DISTINCT af.id_usuario) AS numero_usuarios
FROM 
    atividades_funcionalidade af
WHERE 
    af.id_funcionalidade = 'nova_funcionalidade'
GROUP BY 
    DATE(af.data_atividade)
ORDER BY 
    data;        


Query gerada para Taxa de Reten??o semanal:

WITH semana_inicial AS (
    SELECT 
        id_usuario,
        MIN(DATE(data_atividade)) AS primeira_semana
    FROM 
        atividades_funcionalidade
    WHERE 
        id_funcionalidade = 'nova_funcionalidade'
    GROUP BY 
        id_usuario
),
uso_semanal AS (
    SELECT 
        id_usuario,
        DATE(data_atividade) AS semana,
        COUNT(*) AS uso_na_semana
    FROM 
        atividades_funcionalidade
    WHERE 
        id_funcionalidade = 'nova_funcionalidade'
    GROUP BY 
        id_usuario, DATE(data_atividade)
)
SELECT 
    si.primeira_semana,
    COUNT(CASE WHEN DATE_PART('week', us.semana) = DATE_PART('week', si.primeira_semana) + 1 THEN 1 END) AS retencao_na_semana_1,
    COUNT(CASE WHEN DATE_PART('week', us.semana) = DATE_PART('week', si.primeira_semana) + 2 THEN 1 END) AS retencao_na_semana_2
FROM 
    semana_inicial si
JOIN 
    uso_semanal us ON si.id_usuario = us.id_usuario
GROUP BY 
    si.primeira_semana
ORDER BY 
    si.primeira_semana;        



Ajustes e aprendizado contínuo

Final feliz? Claro que n?o!

A Inteligência Artificial vai errar e muito antes de acertar. A diferen?a é que ela erra muito mais rápido até chegar ao acerto do que um humano, e isso n?o podemos negar. Por isso, quando uma query gerada apresentar algum erro ou n?o produzir os resultados esperados, você deve informar o erro ao ChatGPT e ele ajustará a query para corrigir o problema. Desconfiar dos dados é sempre importante, seja uma consulta gerada por IA ou por humano.

E o melhor de todo esse processo é que a IA explica todo o processo de constru??o e ajustes com uma linguagem natural, permitindo ao humano também aprender o significado das fórmulas, dos cálculos, etc. Esse processo iterativo permite um aprendizado contínuo e uma melhoria constante na cria??o e ajuste de queries SQL. é fascinante!

A inteligência artificial está transformando a maneira como interagimos com dados, simplificando processos complexos e empoderando profissionais de produto a tomarem decis?es mais rápidas e informadas. A ado??o de ferramentas como o ChatGPT n?o apenas facilita a cria??o de queries SQL, mas também promove um aprendizado contínuo, nos tornando mais aut?nomos e eficientes.


A mudan?a de paradigma trazida pela IA é evidente: a complexidade técnica se dissipa, dando lugar a uma intera??o mais intuitiva e acessível com os dados. O resultado? Decis?es estratégicas mais precisas e baseadas em dados, um aumento na confian?a do time e uma colabora??o mais eficiente entre PMs, analistas de dados e ferramentas de IA.

Se você já experimentou o poder transformador da IA em suas análises de dados ou está curioso para saber mais, compartilhe sua experiência ou dúvidas nos comentários. Vamos juntos explorar como a tecnologia pode continuar a revolucionar o campo do gerenciamento de produtos.

E lembre-se: com PMs, DAs e IA trabalhando em conjunto, o futuro é promissor e repleto de oportunidades.


Referências:

  1. Amplitude Blog: "Analytics Instrumentation"
  2. Product School: "The Ultimate Guide to AI Resources for Product Managers"


Luiz Souza

Human Resources? |? Business Partnering? |? People Development? |? Training and Mentorship

7 个月

Absolutely agree! AI’s ability to simplify complex tasks like writing SQL queries is a game-changer. Tools like ChatGPT not only save time but also boost confidence in decision-making. The synergy between product managers, data analysts, and AI will definitely shape the future of innovation. Exciting times ahead!

要查看或添加评论,请登录

Douglas Sá的更多文章

社区洞察

其他会员也浏览了