0% found this document useful (0 votes)
5 views

How To Code SQL Like A Boss

Uploaded by

destrada.cabita
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

How To Code SQL Like A Boss

Uploaded by

destrada.cabita
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

How to Code SQL Like a Boss!

So, you have been working with SQL for a bit, and are getting pretty good writing
queries, yet you get stuck on more the more complex ones.
What can you do to get over this hurdle?
How about I show you how to code SQL like a boss? Interested?
Keep reading if you are looking for a proven method to take that complicated
query you need to write and break it down into a simple and easily verifiable
steps.

Coding SQL Like a Boss


What's quite surprising is that I found out that I can code like a boss by taking
baby steps. Whenever I need to write a complex query that I cannot “see” in my
head these are the steps I follow:
▪ Understand what results your customer expects.
▪ Write out request
▪ Plan the steps
▪ Verify the steps as you go

The Scenario
Let’s set the stage. Suppose the Sales Manager is looking at past sales and she
wants to see a yearly summary of sales, which she gave you as a mock-up on that
Excel sheet that she did.

EssentialSQL.com
What is your next step?

Understand the Results


Before you can write any query, it’s a really good idea to know the goal. What is
your result? Obviously, all our good planning is going to go to waste if we do not
deliver what the customer expects.
Like planning a road-trip, knowing your destination is key.
When talking to your customer, clear up any ambiguities. Make sure you and your
customer is on the same page. For example, what does the Sales Manager
consider as sales? Are they just the products Adventure Works makes, or do they
include merchandise bought from suppliers and resold?
Here are the things I do to understand the request to ensure that the customer
and I are on the same page:
1. Agree on definitions to clear up ambiguities
2. Identify calculations.
3. Understand any criteria used to filter or limit the data.
In summary, avoid making assumptions about the request. When in doubt ask
questions.
It is far easier to get your query on track before you have written it, than three
quarters finished.

EssentialSQL.com
Write out the Request
The next step is to write out the request. This can only be done once you
understood the customer’s needs.
▪ Write out the request in your own words. Do not use jargon, but instead,
stick to an easy to understand language. If you cannot write a simple
description, then that is a warning.
▪ No query should be complicated that you cannot describe its meaning.
Here is what I wrote for the Sales Manager’s request:

For final verification, ask your customer to read the description. Does it make
sense to them? Do they agree?
If so, congratulate yourself!
Now, you have a good requirement that both you and your customer understand
and agree what should be done.

EssentialSQL.com
Plan the Steps
It is time to put on your SQL thinking hat. In this step we are going to put
together our game plan.
As you may know, writing SQL is different than writing a traditional computer
program. You “tell” a computer program what to do step-by-step, while in SQL
you describe the result.
Given this, most people dive right in and try to write the query. It can be fun,
but there are problems with this approach, such as the following:
▪ You can “see” the results, but not what the SQL is needed needs! Like that
road-trip, you know where you are, where you need to go, but without a
map, do not know which highways to take to get there.
▪ The result summarizes the data required to verify if the underlying query
works! Are you summarizing the right stuff? How would you know?
▪ You get lost or sidetracked. This is easy to do once you start your journey.
If you run into problems, not having a good direction may get you off the
path.
Chances are you’ll end up with a working query, which doesn’t meet the
customer’s requirements.
Here are steps I would take to construct the Sales Manager’s query:
Step 1: What core columns drive the query?
For our example, they are Product Model, Product Name, Finished Goods Flag,
Make Flag, Order Date, and Line Total.
Step 2: Which tables house those columns? What table joins and stitch the
results together?
The tables required are SalesOrderHeader, SalesOrderDetail, Product, and
ProductModel. The tables are joined using SalesOrderHeaderID, ProductID, and
ProductModelID.
Step 3: What intermediate steps are needed to complete the query? Are
subqueries or other calculation required?

EssentialSQL.com
We will need to group our data by the Sales Year, so we’ll need to calculate the
year based on the Sales Order Date.
Step 4: Does the result require summarization or finishing work?
Yes! We will summarize the LineTotal by Sales Year.
Step 5: Do I need to limit the summarization or results to specific summary values
or ranges?
Yes, we need to limit the report to product models with greater than $500,000 in
yearly sales. Do to this we can use the HAVING clause.
Step 6: Are the results sorted?
Finally, we will sort the results by the Sales Year total.

Hopefully, you are seeing a pattern here. I write my query from the bottom up.
Each query is different. So, the step I take are necessarily the same, but the
strategy is not.
I start with the core data, the details, and then from there, in a step wise fashion
incrementally add more features, verifying along the way, to ensure the query is
right on track.

EssentialSQL.com
Verify as you Go
Using my game plan as a guide I start to lay down the query. The idea is to slowly
build up the query, per the game plan, verifying results along the way.
SQL seems so monolithic or its all-or-nothing. What we are going to do, is build
up our query step-by-step. Achieving small wins along the way.

This is the core query I wrote for the Sales Manager example:
SELECT TOP 100
PM.Name ProductModel,
P.Name Product,
P.FinishedGoodsFlag,
P.MakeFlag,
SOH.OrderDate,
SOD.LineTotal
FROM Sales.SalesOrderHeader AS SOH
INNER JOIN Sales.SalesOrderDetail AS SOD ON SOH.SalesOrderID = SOD.SalesOrderID
INNER JOIN Production.Product AS P ON SOD.ProductID = P.ProductID
INNER JOIN Production.ProductModel PM on P.ProductModelID = PM.ProductModelID

Tip! To make sure I don’t get too many rows back I’ll use Top 100 to limit my query to
100 results.

This is a great place to double-check the results just to make sure your JOINS are
working as expected and you are returning “good” data.
Once you are comfortable with the core data, start adding the WHERE clause.
For the next several steps, slowly add in elements needed in the final query such
as calculated fields.

EssentialSQL.com
By now, you query may look like this:
SELECT TOP 100
PM.Name ProductModel,
P.Name Product,
P.FinishedGoodsFlag,
P.MakeFlag,
Year(SOH.OrderDate) SalesYear,
SOH.OrderDate,
SOD.LineTotal
FROM Sales.SalesOrderHeader AS SOH
INNER JOIN Sales.SalesOrderDetail AS SOD ON SOH.SalesOrderID = SOD.SalesOrderID
INNER JOIN Production.Product AS P ON SOD.ProductID = P.ProductID
INNER JOIN Production.ProductModel PM on P.ProductModelID = PM.ProductModelID
WHERE P.FinishedGoodsFlag = 1 and MakeFlag = 1

If the filtering is complex, it is OK to go slow by adding causing one at a time, pausing to


verify result in-between.

Now, add in the GROUP BY to summarize the sales by year. In doing so, it is used
to support by doublechecking the data, such as the FinishedGoodsFlag.
SELECT Year(SOH.OrderDate) SalesYear,
PM.Name ProductModel,
Sum(SOD.LineTotal) YearlySales
FROM Sales.SalesOrderHeader AS SOH
INNER JOIN Sales.SalesOrderDetail AS SOD ON SOH.SalesOrderID = SOD.SalesOrderID
INNER JOIN Production.Product AS P ON SOD.ProductID = P.ProductID
INNER JOIN Production.ProductModel PM on P.ProductModelID = PM.ProductModelID
WHERE P.FinishedGoodsFlag = 1 and MakeFlag = 1
GROUP BY Year(SOH.OrderDate), PM.Name

Finally finish up the query by adding formatting and sorting.


SELECT Year(SOH.OrderDate) SalesYear,
PM.Name ProductModel,
FORMAT(Sum(SOD.LineTotal),'N0') YearlySales
FROM Sales.SalesOrderHeader AS SOH
INNER JOIN Sales.SalesOrderDetail AS SOD ON SOH.SalesOrderID = SOD.SalesOrderID
INNER JOIN Production.Product AS P ON SOD.ProductID = P.ProductID
INNER JOIN Production.ProductModel PM on P.ProductModelID = PM.ProductModelID
WHERE P.FinishedGoodsFlag = 1 and MakeFlag = 1
GROUP BY Year(SOH.OrderDate), PM.Name
HAVING Sum(SOD.LineTotal) > 5000000
ORDER BY SalesYear

EssentialSQL.com
Conclusion
Keep in mind that every query is different, So the steps taken, are not always the same- but the
approach is!

When facing difficult or complex SQL queries, do not try to write everything all at once. Instead, try to
get a foundation in place and then build and verify small changes as you go.

Getting these small wins give you confidence, and help you know you are on the right track.

So, in summary here is my approach:

▪ Make sure you understand the query. Write it out in simple language to make sure you
understand.
▪ Confirm the request with the customer.
▪ Once you are good to go, get a core query in place and verify you are pulling in the correct data.
▪ From there, add to your query slowly by verifying results along the way.

I think you may find this approach better and takes away some stress and make it more enjoyable to
write queries.

Looking to learn more SQL? If so, check out my free online tutorial. It is a great way to learn SQL.

Kris.

EssentialSQL.com

You might also like