If you’re not a data scientist but you have questions, you need to know SQL. This guide will run through everything you need to get started: from technical topics to how to be a useful, smart teammate.
- What is SQL, exactly?
- Database schemas
- Basics of a SQL query
- Where and how to write SQL
- Query performance
- The advanced stuff: window functions, nesting, and such
- Practical tips for getting better and being a good teammate
- Where to learn more
One very, very important caveat: SQL queries can write data to a database, not just read it. But that’s mostly for engineers and database admins, so this post will focus on reading data – probably 99% of what you want to do.
What is SQL, exactly?#
Data in a database is almost never in the format you need it to be in. SQL is a programming language that lets you pull that data and rearrange it: add things together, group over time, replace dollar signs, you name it.
When you write SQL, you’re building what’s called a query: every “piece” of SQL you write will return one set of data. A SQL query can be as short as a few words, or as long as hundreds of lines. It’s sort of like making an order at a restaurant: you need to tell the database exactly what you want, and it will serve up the data you asked for. You’ll usually mess up the first few times before you get it right.
Database schemas#
Before you understand how SQL works, you need to understand how data is stored. If you’re querying a database with SQL, chances are that database is organized as a series of tables, each with columns - think of a spreadsheet in Excel. A row is a single “data point” and a column is a type of data. So if we have a database full of orders that our customers made, one row would represent one order, while a column might be “order type” or “order date.”
You’ll often hear people (yes, people) refer to a weird word called “schemas” – but don’t fret! A schema is just a description of the structure of a database. A schema usually says something like “this database has these tables in it, each table has these columns, and these tables are related to each other in these ways.”
🚨 Confusion Alert
For reasons beyond me, PostgreSQL - one of the most popular relational databases – uses the word “schema” to refer to something else: a collection of tables. Most of the time you hear the word though, it will be in reference to database structure.
Poking through schemas are a useful way to better understand the data you’re working with and avoiding confusion down the road. Here’s what a schema might look like; you’ll notice there’s an entry for each column in the table and information about data types.
Basics of a SQL query#
Let’s start by running through the basics of a SQL query, and then dive into more details around how to do a good job at writing one.
- The basics
Let’s start with a query and work backwards. We work at a DTC floss company named Flossier, and we want to analyze our order volume. This SQL query gets us the order ID, order date, and user ID for all orders that were made today.
SELECT
order_id AS id,
order_date ,
user_id
FROM orders
WHERE order_date = CURRENT_DATE()
ORDER BY order_dateYou can probably get the gist of what this is doing: SELECTing the columns that we want FROM the table we want (it’s called “orders”) and filtering for WHERE the order_date is today (CURRENT_DATE()). Every SQL query will start with a SELECT and a FROM, and most of them will use a WHERE. Let’s run through these keywords in a bit more depth:
→ SELECT
The SELECT keyword designates which columns of data you want in your results. Tables will usually have more columns than you need for your analysis, so you’ll pick a subset of them in your query. If you want to return all columns in a table, you can write SELECT * instead of spelling out all of the individual column names.
🖇 Workplace Example
The phrase “select star” is pretty common in conversation among data and engineering teams. You might hear something like “select star isn’t working” which means that a table is down and not queryable because you can’t select anything from it (i.e. SELECT * doesn’t work).
The SELECT part of your query isn’t just where you pick columns, though; part of what makes SQL powerful is what you can do with the columns you’re selecting, like adding them together or transforming them. We’ll cover that in the “everything else” section.
→ FROM
A database usually has a bunch of tables, so you need to specify which table you want to pull your data from. Each query can only have one source table, but you can join other tables onto it: more on that later.
→ WHERE
The WHERE clause lets you filter the rows that you want; without it, your query will return every single row in the table. The general format works like this:
- The column you want to filter on (e.g. order_date)
- An operator (e.g.
>,<,=) - A filter value (
2020-01-01)
In our query above, we only want to look at orders that happened today: so we use WHERE order_date = CURRENT_DATE(). CURRENT_DATE() is a built in function that gets whatever today’s date is.
→ ORDER BY
This (surprise!) lets you order your results by a column or by multiple columns. In our example query, we ordered the results by the order_date column. By default, ordering is ascending, but we can adjust this to ORDER BY order_date DESC to order descending.
→ AS
You can rename anything you’re working with in SQL - columns or tables - with the AS keyword. This is called aliasing, and it’s useful if you’ve got tables with long complex names that you want to skip typing out, a lot of similar sounding columns, or aggregations.
Grouping and aggregating#
Where SQL gets really powerful is the ability to aggregate. Aggregation lets you answer questions like:
- How many orders have we gotten over the past few months?
- What’s the biggest order a customer has made in the past week?
- What’s our monthly revenue over the past year?
The answers to these questions require summing up or taking the max/min of things, and that’s pretty much what aggregation in SQL is. To aggregate, you’ll need to do two things: add an aggregation keyword into your SELECT statement, and add a GROUP BY clause at the end of your query. This here query gets us the number of daily orders since the beginning of the month:
SELECT
order_date,
COUNT(*)
FROM orders
WHERE order_date >= ‘2020-05-01’
GROUP BY order_dateThe COUNT() keyword counts up the number of rows per order_date - we’re using the * inside because that’s the way that people typically do it (we could also have written COUNT(order_id) or any other column, and it wouldn’t make a difference). We also added a GROUP BY statement at the bottom to tell our database to aggregate that COUNT() per order_date and not per any other column.
Aggregation takes a little time to get comfortable with, so don’t sweat it.
Joining#
Sometimes, all of the data you need will be in one table. Lucky you! Other times though, you’ll need to marry the data from two (or fifteen) different tables to get the answer to your question. SQL lets you JOIN tables together ON a shared column – also called a key – so you can make use of both data sets.
Example time! We’ve been pulling orders data - but what if we also want to know the name of the user who made the order? The problem is that the user’s name is in the users table, not the orders table. Thankfully, the user_id column exists in both tables and can use it to join them together:
SELECT
orders.order_id,
orders.order_date,
orders.user_id,
users.user_name
FROM orders
JOIN users
ON orders.user_id = users.user_idLearning about JOINs is a whole trip, because there are different kinds: INNER JOINs, OUTER JOINs, LEFT JOINs, CROSS JOINs, and others too. There’s literally an entire website on the topic. Don’t sweat the details though; the more SQL you write, the more you’ll learn. For now, just make sure you understand the concept.
Everything else#
There are thousands of other things you can do with SQL, like:
- Concatenate words together
- Round numbers
- Add and subtract date intervals
- Use conditional logic (if this then that)
It’s not quite a programming language, but it’s pretty powerful. We’ll cover a few more things in the advanced section below, but just keep in mind that if you can think of it, you can probably do it in SQL.