So now you know how to SELECT data but not yet how to choose where to get that data FROM. Let’s get into the real stuff and SELECT data FROM a specific table.
In our example database we have a table called albums, which holds info on some music albums. It has three columns, id, title, artist_id. Here’s what it looks like in Excel:
To get data that’s in this table we need to specify what columns we want to SELECT and FROM where we want to select it. So let’s try to get a list of all the album titles we’ve got stored. We can use the following template to do so:
SELECT [stuff you want to select] FROM [the table that it is in];
Let’s start with a simple one and query for everything (all of it!) from the albums table.
Look at all that data! Notice at the bottom of the table we’ve paginated it for you so it doesn’t take up the whole page. All of the columns and rows in the table albums have been fetched. You can see the table above looks similar to what the data would look like in Excel.
You’ll notice above that we used the star
* in SQL to specify what we wanted to SELECT. The
* is called a “splat” and is a handy shortcut for selecting all of the columns available, instead of having to write each one out.
As an alternative to the splat we can list out each of the columns we want to select. So the following query will return the same data as above.
But of course we don’t have to query for all of the columns if we don’t want. If we wanted to just get all the album titles and ids we can query for just those columns.
And notice that the columns will come back in the order that you list them in. Try reversing the column order in the above query by selecting id first and then title.
There are a lot of other Tables in our example database like artists and tracks. Try fetching some data from one of those:
Now it’s getting interesting right? Right now though we’re getting a list of all the results in the table back. We need to learn how to filter, group, manipulate and limit these results.