What to do When Working on SQL Project (That Someone Else Started) For The First Time

I was recently tasked with my first SQL project at work, and “feeling overwhelmed” was an understatement.

The original author had written the code years ago, had already left the company, and passed along minimal knowledge to the team.

The query was over 600 lines long, and CTEs (common table expression, aka temporary results that can be referenced later on in the query) were labeled with names like “screen” and “base”…what!?

Let’s to through what I’d do together:

  1. Acknowledge the fear, possible knowledge gaps, and all the negative feelings. They’re normal, but let them be fleeing.

  2. Take a deep breath, then open the code

  3. Do an initial walkthrough. This is not to understand the code, just to get an idea of what you’re working with.

    Things to note during the walkthrough:

    1. What’s the end goal of the query?
    2. Which tables are being used?
    3. Are any filters involved? (dates, countries, etc.)
    4. Are there CTEs, and what results do they output?
  4. Once I’ve gotten an overall understanding of what the query’s about, I then go in and rewrite at least a portion of the code to really understand what the query is about and how the tables relate to each other. It can also clear up any confusing aliases.

    I also find some unnecessary lines in queries this way, so this is a good way to clean up old code as well.

  5. This could be optional if there aren’t a lot of tables involved, but I personally think making an entity relationship diagram (ERD) is very helpful. Sounds complicated, but it’s basically a map showing how the tables involved are related. This is a great thing to refer to especially if there are multiple joins involved in the query. This can be done in parallel with the previous step.

  6. Cross-check your new code with the old code to make sure that you’re getting the same data!

And that’s it! It’s easy to overthink or shut down when overwhelmed, but all large tasks can be broken down to manageable pieces. You got this!