SQL as the advantage of being easily understandable. You could show a SQL query to a grandma and she may be able to figure out what’s happening.
In this article I will show you the basics of a SQL query, and you will see that it’s probably easier than you thought.
What is a SQL Query
The goal of a SQL Query is to extract data from a database in a desired format.
Imagine a table that has a few rows and a few columns. You want the data in that table plus or minus some information.
For example, you might want to filter out some information, or join your table to another one to get more information.
A SQL query has basically 2 main functions:
- Extract Data
- Add or Remove Data
SQL Query Structure
Let’s focus on how to extract data first. To do so, I think you would agree that we first need to select some data from a table. Well, let’s do just that:
SELECT * FROM myTable
The SELECT keyword let’s you choose the columns that you want SQL to return.
The FROM keyword let’s you choose the table you want to query.
Instead of specifying all columns to return, the * symbol let’s you choose them all.
Add or Remove Data
There are many different ways to merge data together and to filter data out in SQL and we won’t go through all of them here.
To filter data out you can use the WHERE clause like below.
WHERE coneSize = 'Small'
In that case you’re not pulling data from the whole table, but only from a subset of that table that is small cones.
To add data you can use the JOIN clause. Using or example above, you might want to know who’s the supplier for each flavor:
FROM iceCreamFlavors a
JOIN flavorsSuppliers b
ON a.supplierID = b.supplierID
The “a” and “b” after the table names are called aliases. They allow you to rename a table so that you can reference it faster later on.
The ON keyword let you specify on which column(s) you want to join your 2 tables.
To join 2 tables with multiple columns you can just chain them with the keyword AND.
That’s everything you need to know to start doing some simple SQL queries 🙂