#TSQL2sday #149: T-SQL Advice you’d give to your younger self

Hello! As I mentioned on my invitation post, this month I’m hosting the T-SQLTuesday and my theme was “T-SQL Advice you’d give to your younger self”. Here’s my contribution.

If I could go back in time, and maybe send myself an anonymous email (which would probably go to my spam box? hmmm), this is what I’d like to find:

  • It’s ok to use Google, like every day multiple times a day. Sometimes we face issues and we may tend to get super deep into it, but forget that we do not need to re-invent stuff. Others have likely been through what you are living and if they were great human beings they even talked about it on the internet. Isn’t that wild? We must learn to be humble. It’s OK to have your colleagues and managers see an open Google tab, as long as you are delivering the job you’ve been given, you’ll be just fine.
  • Comment your code! I’ll give you a week and you’ll forget what you were doing anyways so leave some useful comments. That will help you and others who will pick up on your work after you. I like to add the following to all my scripts: author, date, project name and a little description. Sometimes I even add the name of the person who requested the work, makes it easier to talk directly whit whom I need to.
  • Do you know those times when you find yourself repeating the same piece of code over and over? There are better ways to version your code, but as a starting point, you can create a folder on your documents and start adding sql files there that you can refer to later. Here’s what I have on my folder:
    • how to search for a column or table with a specific name;
    • how to use date functions with examples such as DATEADD, DATEDIFF;
    • how to check for temp tables column names;
    • how to format phones when they’re all messed up;
    • how to find databases, filenames and paths;
    • getting a path for sql server log error message;
    • check you database size;
    • how to check for used and used space on the database
    • and whatever else your heart desires! This is the type of work that I do and that later will save my time. I’ll probably make more posts to show my solutions to this handy scripts 🙂
  • Always ident your code and use Uppercase for all commands. You’ll notice that one day you won’t even trust people who don’t do that (oh, the drama).
  • If you have someone senior than you at work, ask them questions when you’re stuck, they probably will solve the problem faster, more elegantly and you’ll learn how to do it by watching them!
  • Make it a habit of NOT using “*” when you are doing a SELECT query. It’s ok to do it once so you can see the table, but then your real query should list the fields you want to see, by name. ✨ Marie Kondo your query and let go of what does not serve you anymore ✨
  • Don’t wait until you are an accidental DBA to learn the fundamentals. Even if you just want to be able to discuss problems with them.
  • Learn how to read the query execution plan. It will help with understanding bottlenecks and how to optimize your queries.
    • …also, when optimizing, don’t struggle about the milliseconds you might save. Nobody will notice. You want to focus on the changes that will give you the biggest differences on execution time. Think about how big the impact will be by projecting “if I don’t fix this will someone come to my table with a very angry face?”
  • Whenever you start writing an UPDATE or DELETE statement, immediately write FROM… WHERE… This will save you the headaches of forgetting to finish your command and updating or deleting everything at once.

That’s it for me. Hope this was helpful for some beginners out there. Now tell me…

What do you wish you knew earlier? 🙂

Do you need SQL for a data related job?

Illustrations by Camila Henrique

I wanted to talk about this because I see a lot of doubts and lack of direction from people who are either beginning now in IT land or thinking about switching careers. The short answer to “do I need to know SQL for a data job?” , is yes. In the next few paragraphs I explain why I think so.

It’s easy to get caught up in all the fancy programming languages and methodologies for projects that sometimes the basics… are just not there. I believe having a good foundation opens paths to other doors that you could not see before. And I’m certain that SQL is one hell of a foundation to have in the data land.

Data jobs have been on a hype for the past few years. There’s a lot of speculating about what a data person job is (and actually it can vary a lot). However, there is one skill that seems to endlessly haunt job descriptions. Can you spot it below?

Taken from Linkedin, July 2021

Taken from Linkedin, July 2021

Taken from Linkedin, July 2021

SQL is always on high demand for any data job. Because it’s part of our basics. And knowing your basics can help you thrive. You can learn a lot of interesting stuff about data, but in the end, you’ll most likely need to get your hands on a database at some point, and SQL is how you talk to a database (and I think that’s beautiful. Stop judging me!).

I’m working on a series of posts dedicated to people who would like to learn SQL from zero. I’ll focus on the Microsoft product, MS SQL Server. They have a version of SQL just for it, it’s called T-SQL. I hope to share my knowledge with you and perhaps help someone along the way. This is my way of giving back to the community 🙂

Any questions or suggestions, my comments are always there for you.

If you want to check out this same post in Portuguese, click here.

Você precisa de SQL para trabalhar na área de dados?

Ilustrações por Camila Henrique

Eu quis falar sobre isso pois eu vejo muitas dúvidas e uma falta de direção de pessoas que estão começando em TI ou pensando em trocar de carreira. A resposta rápida para a pergunta “eu preciso saber SQL para conseguir um trabalho na área de dados?”, é sim, precisa. Nos próximos parágrafos eu te explico por que eu penso isso.

É fácil se perder no meio de tantas linguagens de programação e metodologias de projeto que às vezes o básico fica pra trás. Eu acredito que ter uma boa fundação pode te abrir portas que antes você não veria. Eu tenho certeza que SQL é uma grande skill pra se ter na área de dados.

Os data jobs estão em alta há alguns anos. Existe muita especulação sobre o que uma pessoa da área faz (e realmente, isso pode variar muito). Porém, existe uma habilidade que sempre aparece nas descrições de vagas de trabalho. Você consegue encontrá-la abaixo nos exemplos?

This image has an empty alt attribute; its file name is image.png
Linkedin, Julho 2021

Linkedin, Julho 2021

Linkedin, Julho 2021

O SQL sempre está em demanda para muitas vagas. Porque faz parte dos básicos da área. Quando você domina os básicos, você tem grandes chances de prosperar. Você pode aprender coisas ótimas sobre a área de dados, mas no fim, em algum momento você vai precisar lidar com ele: um banco de dados. E adivinha: SQL é justamente como nos comunicamos com os bancos de dados, sua própria língua (eu acho isso lindo, pare de me julgar!).

Eu estou trabalhando em uma série de posts dedicados à pessoas que gostariam de aprender SQL do zero. Meu foco será o produto da Microsoft, o MS SQL Server. Eles tem uma “versão” de SQL só para esse banco de dados, é o T-SQL. Eu espero compartilhar meu conhecimento com você e quem sabe eu não ajude alguém no meio do caminho. Esse é meu jeito de retribuir para a comunidade 🙂

Perguntas ou sugestões, meus comentários estão sempre abertos!

Se você quiser ler este mesmo post em inglês, leia aqui.

T-SQL Tuesday – Meu tipo de dado (menos) favorito em SQL: DATE

Olá! Este post é uma contribuição ao T-SQL Tuesday. T-SQL Tuesday é um blogothon mensal, onde a comunidade se reúne para escrever sobre um tópico diferente. O tópico de março  é sobre seu tipo de dados favorito. Brent Ozar é o host do mês.

Eu escrevi esse post em duas versões. Esta que você está lendo em português, e uma em inglês.

Se você trabalha com dados, você provavelmente não tem controle sobre todas suas fontes. Por exemplo, você pode coletar dados de lugares diferentes. Talvez seja o seu trabalho centralizar os dados, e criar padrões para que os dados façam sentido para o seu time. Uma vez que você entendeu seus dados, você pode extrair o real valor deles.

Quando seus dados existem em diferentes sistemas, talvez você não tenha controle sobre a validação que acontece por trás. 

Por exemplo, um dos seus fornecedores podem ser muito específicos sobre os tipos de dados que eles permitem no sistema. Isso significa que quando os dados chegarem até você, você verá algo (idealmente) mais estruturado. Contudo, seus dados podem também prover de um sistema liderado por desenvolvedores que decidiram deixar o usuário “livre” para fazer o que quiser (atenção ao verbo “querer” e não “precisar”, existe uma grande diferença aí).

Dados dos tipos de datas são muito importantes em SQL. Mas para nós humanos, datas podem ser formatadas de diferentes maneiras… Por exemplo, no Brasil, escrevemos datas de um jeito diferente dos Estados Unidos.

  • Brasil: DD/MM/AAAA
  • EUA: MM/DD/AAAA

Em SQL, seu tipo de data é guardado no banco assim: AAAA-MM-DD. Não tem como errar, certo? Errado.

Lembra quando eu disse que você pode ter origens diferentes dos dados e que por isso não tem controle sobre as validações? Vamos pensar no seguinte exemplo:

  • Seus clientes usam um sistema de outro fornecedor, passando os dados para eles
  • O fornecedor usa os dados para fazer o que quer que seja que o sistema faça
  • Eles te enviam os dados com o resultado do projeto
  • Você, um profissional inteligente, tenta carregar os dados no seu sistema. E mais importante, seu sistema é formatado com os tipos de dados que você espera receber. Então, digamos que você queira receber um campo com valores do tipo data, você vai formatar sua tabela para ter um tipo de data.
  • Vamos usar a tabela “ThirdPartyInfo” abaixo como exemplo.

Agora, como você já deve ter imaginado, seu fornecedor não aplicou nenhum tipo de validação para esses tipos de dados. Logo, você pode se deparar com alguns tipos de datas estranhos, como esses:

  • Jan/2021
  • 03-20-18
  • 01-02-03 (onde começar com esse?!)
  • 2022/2
  • Entre outros…

Isso é o que acontece quando tentamos inserir algo que não é uma data, em qualquer uma das colunas do tipo data.

Não importa o método que você use para popularizar essa tabela, você vai receber um erro se você não está passando valores do tipo data para suas colunas do tipo data.

Como evitar problemas como esse

  • Seja honesto com o seu fornecedor sobre a razão de ter os tipos de dados que você precisa, e explique quais são eles. Como explicar? Fazendo aquilo que os profissionais de TI mais odeiam: documentando.
  • Se o fornecedor está relutante com a mudança, fale com seus superiores, mostre para eles cenários onde você tem que gastar seu tempo precioso (e caro) só para arrumar esse erro. Reinforce que isso pode ser evitado se todo mundo estivesse na mesma página sobre os tipos dos dados que vocês compartilham.
  • Se nada acima funcionar, ou você precisar de uma solução temporária enquanto a situação se resolve, você poderia validar os dados do seu lado. Se você fizer um esforço agora, antes do problema, pode parecer mais trabalho, massss o você do futuro vai te agradecer por ter se esforçado antes do problema chegar.

Aprendendo do pior jeito

  • Exemplo da vida real: eu recentemente tive um problema que me custou um certo tempo. Eu recebi um arquivo csv necessário para um relatório, e o arquivo tinha alguns campos de datas. Minha tabela estava esperando receber os campos de datas com valores…de datas. Porém, meu job do carregamento dos dados estava com problemas.
    • Eu tive que dar um passo para trás e tentar encontrar a raiz do problema. Eu pensei que fosse ser algo fácil de conseguir se eu olhasse as entradas mais recentes do arquivo (esse tipo de arquivo era mandado pra nós todos os dias, com as coisas mais recentes atualizadas). Meu problema principal, foi que eu não isolei a coluna de data que estava dando erro. Na verdade, no SQL Server, a mensagem de erro quase sempre é muito genérica, e não me falava qual a coluna. Tudo que eu sabia era que uma string estava tentando ser convertida em data, mas sem sucesso.
    • Meu segundo maior problema foi arrumar tudo que eu encontrei no arquivo, que pudesse de alguma forma estar causando o problema. Alerta spoiler: isso não resolveu meu problema.
    • Eu demorei um tempo para entender que usar a função “ISDATE”, seria uma maneira fácil de procurar por uma coluna que esperava receber um tipo de data, mas que recebia outra coisa.

Em momentos de desespero, esquecemos soluções simples, como esta. 

Observe que o resultado dessa consulta tem um valor do tipo texto. Agora, você pode aplicar essa validação ANTES de carregar os dados na sua tabela de produção, além de usar o mesmo comando para investigar problemas como esse.

Resumindo: eu na verdade gosto do tipo DATE no SQL. Funciona bem, mas o problema real foi que falhamos como humanidade pois nunca concordamos em um único formato para datas. Espero te ajudar de alguma forma!

Se quiser ler mais sobre tipos de dados de datas em SQL, leia aqui (em inglês). 

Você resolveria meu problema de uma maneira diferente? Me conte abaixo nos comentários (:

T-SQL Tuesday – My (least) favorite SQL data type: DATE

Hello! This post is a contribution to T-SQL Tuesday. T-SQL Tuesday is a monthly blogothon where we get together and write about a different topic. March’s topic was to blog about you favorite data type, hosted by Brent Ozar.

I wrote two versions of this post. This one you’re reading in English, and this one in Portuguese.

If you work with data, you probably do not have control over all the data sources you need. What I mean, is that for example, you may receive data from different places. Perhaps it’s your job to centralize and standardize it the best you can, so that it makes sense to your team. Once you understand the data, value can be extracted from it.

When your data comes from different systems, it’s likely you will not have control over the data’s validation. For example, one of you vendors may be very specific about the data types allowed into their systems, which means when the data gets to you, you’ll see something (ideally) more structured. However, your data may also be handled by a group of fed up developers who decided they will allow everything the user wants (special attention to the the verb there being want instead of need, big difference).

Date data types are really important and used in SQL. But for humans, dates can be formatted in some ways… For example, I’m from Brazil, and the way we write our dates is different from the US.

  • Brazil: DD/MM/YYYY
  • US: MM/DD/YYYY

In SQL, your date type stores data like this: YYYY-MM-DD. No room for mistakes, right? Bam, Wrong.

Remember when I said you may have different data sources and you can’t control their data type validations? Let’s think of the following example:

  • Your clients use a 3rd part system
  • The 3rd party uses the data to do whatever it is their system does
  • They send you that data with the results of your project
  • You, a smart data person, tries to load the data into your system. Most importantly, your system is formatted with the data types you expect to receive. So, for example, if you expect a field with a date value, you’ll format your table to have a date type column.
  • Let’s use the table “ThirdPartyInfo” as an example.

Now, as should have assumed by now, your third party did not applied any data validation to the date types. Hence, you may get some crazy “dates”, like this:

  • Jan/2021
  • 03-20-18
  • 01-02-03 (where to even begin with this one?!)
  • 2022/2
  • and many others….

Here’s what happens when you try to insert something that’s not a date, into any of the date columns:

It does not matter the method you’ll use to input data to your table, you’ll get an error if you’re not passing date values to your date types columns.

How can you avoid issues like this

  • Be open to your vendor about why this is important to your data, and explain to them your tables data type. How? Documenting, the thing IT people hate most.
  • If the vendor is pushing back, talk to your superiors, and show them a scenario in which you need to spend your precious (expensive) time to fix this mishap. Enforce this could be avoided if everyone were on the page about the data types for the data you share.
  • If nothing above works, or you need a temporary solution, you could validate the data on your end too. More work upfront, but your future self will thank you for putting this effort now.

Learning it the hard way

  • Real life example: I recently had an issue that cost me a lot of time. I had received a csv I needed for reporting, and the file had a few date fields. My table, was expecting date types to come in all the fields, but I was getting errors on my data loading job.
    • I had to take a step back and find where the issue was. I thought it would be easy to find, by checking the most recent info that got into the system (this was a daily file we received), and so I started looking for the issue. My main mistake, was that I did not isolate the date column that was giving me an error. In the SQL Server, the error message was really vague, I could only tell there was a string trying to be converted to date and I had several different date fields in my table.
    • My second big mistake was fixing everything I found on the source file, and I thought was wrong and causing the issues. Spoiler alert: it wasn’t.
    • It took me some time to realize that “ISDATE” was an easy way to search for a column that is expecting a date type, but received something else instead:
In desperate times, we may be blind by stress and not think about simple things, like this.

You see that the return to that query has the string value. Now, you could apply this kind of check as a validation before you load data into your production table, and also use it to troubleshoot issues like mine.

With all that being said, I actually like the DATE data type in SQL. It works great, the real issue is that we as humanity never agreed on a single date format. Sigh. I hope this helps!

If you want you can read more about the Date types here: Date types in SQL

Would you solve my problem in a different way? Tell me how below in the comments (:

Commenting and Naming practices with T-SQL scripts

Image: https://tinyurl.com/pt8ly0ix

Do you know that feeling when you’re starting another query and this time you’re thinking “I won’t re-use this… this is a one-time thing…”. We both know you’re lying.

I said that because most of the time:

  • you’re code is reusable
  • you’re human and you forget stuff, so perhaps tomorrow you forgot something you realized how to do today
  • I’ve never seen where you keep your scripts but I bet that needs a clean up

When you’re working on something, try to picture your future self. Your older self has probably no clue about what this *really_important_2018_script* project was. Is your older/wiser version happy while reading that? I don’t think so.

If you make an effort now to be more “tidy” with your code, here’s who will be happy:

  • your future self
  • your colleagues who read your code
  • people who will take your job in the future and think “hey! this person don’t suck as much as I thought… just a little!”

How to add comments in SQL

Basically, there are two ways to add comments in SQL:

1- add “–” and start typing!

2- add “/**/” and write in between the stars.

No one is better than the other. The first option is usually for in-line smaller comment. The second it’s more for commenting out blocks of code or writing bigger comments in a way they will not be on one same line.

Initial comments

Personally, I believe comments are a good thing. It’s not something I do with every line, however, when I open a new query, I automatically add my comments.

Here’s how I like to start my scripts:

Important note: if you’re writing a stored procedure, remember to add this block of comments after your “CREATE PROCEDURE” statement. When you do so, the comment will show up when you right-click on the stored procedure and chose “Modify”. Otherwise it’s gone and saved only on your main script file.

Naming your file

Try to be descriptive when naming your file, and don’t abbreviate too much. The name you chose may seem relevant now, but again, ask yourself “is my future version hating me now?”. If the answer is yes, than chose something else.

If the script you are creating is part of a bigger project that involves other scripts, then try to start every file name with something that refers to the project itself.

For example: sp_AutomatedFinancialReports_CalculatingEmployeeSalary

Here’s what we know based on the file name:

  • sp: this is a stored procedure
  • AutomatedFinancialReports: project name that’s descriptive
  • CalculatingEmployeeSalary: this is what your specific script will do as part of the project

Avoid at all costs using “new”, “old”, “final” and relative names on your file. This is not useful long-term. If you’re creating many drafts, I’d go with versions like “v1”, “v2”, or just add the plain date to your file name. But remember this is a temporary name, and that once you figure your “v23_final_new” file, you’ll change the name accordingly. Another trick is to move your thousand drafts to a, guess what, drafts folder. The idea is that your main project folder keeps your already tested and ready to go script.

This is some basic stuff I do everyday and I hope you find it useful. Do you add something else that you’d like to share? Leave a comment (:

Want to read this post in Portuguese? Check out this link.

See you later!

Práticas para comentários e nomes de arquivos SQL

Image: https://tinyurl.com/pt8ly0ix

Conhece o sentimento de abrir um novo arquivo, e pensar “eu não vou reutilizar esse código… só vou fazer isso uma vez…”. Nós dois sabemos que você está mentindo.

Eu estou falando isso pois, na maior parte do tempo:

  • seu código é reutilizável
  • você é humano e esquece as coisas. Então, talvez amanhã você já tenha esquecido como resolver uma coisa que você fez hoje.
  • eu nunca vi onde você salva seus scripts mas eu aposto que você poderia fazer uma boa limpeza na sua pasta

Quando você está trabalhando em algo, tente se imaginar no futuro. O seu “eu” mais velho provavelmente não tem ideia do que seja o *projeto_importante_2018_script*. O seu eu mais experiente está feliz lendo este arquivo? Eu acho que não.

Se você fizer um esforço agora para ser mais “arrumadinho” com o seu código, essas pessoas vão ficar muito felizes:

  • o seu eu futuro
  • seus colegas de trabalho que leem seus códigos
  • pessoas que vão assumir seu lugar no futuro, e vão pensar “olha só! essa pessoa não era tão péssima, era apenas ruim mesmo!”

Como adicionar comentários em SQL

Basicamente, existem duas maneiras de adicionar comentários em SQL:

1- adicione “–” e comece a digitar!

2- adicione “/**/” e escreva entre os asteriscos.

Nenhum é melhor que o outro. A primeira opção é mais usada para comentários na mesma linha do código. A segunda, é mais comum para comentar blocos de código, ou escrever comentários maiores que não vão ficar em uma linha gigante.

Comentários iniciais

Pessoalmente, eu acredito que comentários são algo bom. não é algo que eu faça em cada linha do código, porem, quando eu abro uma nova query, automaticamente eu adiciono um cabeçalho de comentários.

Eu começo meus scripts da seguinte forma:

Autor: quem está escrevendo o script.

Data: quando o script foi criado, para edições eu geralmente adiciono um edit na mesma linha.

Projeto: qual projeto o script faz parte. É legal descrever um pouco o projeto.

Descrição: descrever a razão do seu script, aqui é onde você explica onde está parte se encaixa no todo.

Requisitado por: nome de quem pediu que isso fosse desenvolvido. Além dos nomes, talvez seja interessante adicionar também os emails para contato.

Importante: se você está escrevendo uma stored procedure, lembre-se de adicionar o seu bloco de comentários depois do comando “CREATE PROCEDURE”. Fazendo isso, o seu comentário vai estar integrado ao código da proc, e vai aparecer inclusive quando você escolher a opção de “modificar” o arquivo. Se você não fizer assim, o comentário vai ficar salvo apenas no próprio arquivo principal do script.

Dando um nome ao arquivo

Tente ser descritivo e intuitivo quando for nomear seu arquivo, e não abrevie muito. O nome que você escolheu pode parecer relevante na hora, mas de novo, pergunte-se se o seu eu do futuro está te odiando agora.

Se o seu script fizer parte de um projeto maior, então tente começar o nome do arquivo como algo que remeta ao projeto.

Por exemplo: sp_RelatorioFinancasAutomatico_CalculoSalarioFuncionario

Com esse nome, sabemos:

  • sp: isso é uma stored procedure
  • RelatorioFinancasAutomatico: nome descritivo do projeto
  • CalculoSalarioFuncionario: o que a sua parte especifica do script faz 

Evite usar termos como “novo”, “velho”, “final”, dentre outros. Isso não é útil em longo prazo. Se você está criando vários rascunhos, por exemplo, seria interessante versionar, usando “v1”, “v2”, ou até adicionar a data no nome do arquivo. Mas, lembre-se que esses nomes deveriam ser temporários, e assim que você descobrir qual finalmente é sua versão “v23_final_novo”, mude esse nome. Outra coisa que você pode fazer é mover seus rascunhos para uma sub-pasta dentro do projeto, assim fica mais fácil de organizar os scripts “finais” e importantes.

Essas são coisas básicas que eu faço todos os dias. Espero que você tenha achado útil. Existe outra coisa que você adiciona que gostaria de compartilhar? Deixe seu comentário (:

Quer ler este post em Inglês? Clique aqui.

Até mais!