Chapter 1. Databases and Tables: Organizing Your Information
It’s time to bring order to your data. These days, just about every aspect of life involves data: the applications on your phone, the appearance of your social media feed, and even those detailed notes you take about your flossing habits. But all that information can only be useful if it’s arranged in a meaningful way so you can find what you want, when you want it.
You need a system to help you store and organize your data, and you need it now. Tables allow you to establish law and order and to craft your bits of info into rich assets, ready to be mined for insights. So turn the page, come on in, and get ready to enjoy the orderly world of relational databases.
Defining your data
Abby’s created quite a large assortment of notebooks, scraps of paper, and other records. Her collection is starting to get overwhelming. It’s so large that she can’t find all the details for her travels anymore, which is a bummer since she wants to take a big trip this year. Let’s give her a hand so she can get back to her adventures!
Exactly. A database is just what we need.
A database brings order to chaotic data. It’s a digital representation of all your notes and records. When you create a database, you can structure your information in a neat and logical format. And once your data is organized, you can easily access the contents of your database any time you need!
But before you create a database for Abby’s travel information, you’re going to need to have a better idea of what kinds of data you want to store and some ways of categorizing it.
Think about your data in categories
Let’s look at Abby’s travel data in a new way. Imagine cutting up one of her notebook pages, and then spreading the pieces out horizontally like this:
Now take the labels that you just made for each category, and place those above the corresponding bits information like this:
Build a table of information
You can follow this same process for each of Abby’s travel notes, and eventually, you’ll end up with a table of information with columns and rows. Here’s a few of those records in a nice table:
What is SQL?
You’re learning great things about how you can organize the information from multiple documents into categories of data and arrange them in a grid-like table. You may have worked with data like this in software for spreadsheets such as Excel or Google Sheets. In this book, we’ll use SQL to create tables as well as find the information we put in them. So what is SQL?
SQL is a programming languages for storing and retrieving tabular data, and by “tabular,” we just mean information that you can write down in a table with rows and columns. Even though it was introduced in the 1970s, SQL still remains very popular in today’s workplace.
You can pronounce “SQL” by spelling it out as “S.Q.L.” or by making it sound like the word “sequel.” It’s often described as standing for Structured Query Language, though its origin story differs from that slightly.
The anatomy of a table
In SQL, data is organized into tables. Each table contains catorgies of information called columns and rows of individual records.
Each column represents one category of information.
Remember the categories you came up with for Abby’s travel notes? Each category becomes a column in your table. For example, in a column for the mode of transportation, you might see these values: plane, train, car. You’ll sometimes see the word field instead of column. They mean the same thing.
Each row represents one individual record.
A table row contains all the information about one individual object. In Abby’s table, each row would be all the data about one city she would like to visit. Here’s an example of some of the data that might be in one row: Sydney, Australia, $4,000, warm, plane. And a row is often called a record.
A table of travel data
As you might have guessed, we’ll be organizing Abby’s travel notes into a table.
Each column of that table will contain details about one specific aspect of her plans, such as her proposed budget for each location or the attractions she plans to see at each stop.
Each row will provide all the information associated with a single city Abby wants to visit. For example, all the travel details about Boston span across the top row of this table snippet:
Not quite yet. We need to talk about databases first.
You now know all about tables, columns, and rows, but each table must belong to a database. After a quick exercise, let’s talk about those before going any further.
BE the table
Below, you’ll find some notes about coffee purchases and a table. Your job is to be the partially formed table and fill in all the missing bits. After you’ve completed the exercise, turn the page over to see if you’ve become one with the table.
BE the table Solution
Below, you’ll find some notes about coffee purchases and a table. Your job was to fill in the remainder of the table with the coffee purchase information and to give the table and columns descriptive names.
What’s a database?
So far, you’ve learned about tables of data. Each table column contains one category of information, and each table row houses the information of one individual record. But you also need a container for the table itself, and that’s where the database comes in.
While we’ve only talked about single tables of information—like Abby’s travel table—so far, most times you’ll have several tables of related information. A database can hold all those tables in one place so that you can keep track of them and easily associate them with each other.
Note
There’s a LOT of power in doing so, but more about this later.
Take command!
It’s time to get coding. As you’ve probably picked up on by now, this book is about SQL, a programming language for controlling and querying tabular data. But you’ll need a relational database management system (RDBMS) tool in order to use SQL. We’re using MySQL as our RDBMS in this book, but you are welcome to use another system if you prefer.
Start up your RDBMS and open a command line window or a graphical environment where you can use SQL to communicate with your RDBMS. Here’s our terminal window after we start MySQL:
Your first SQL commands
Let’s put Abby’s travel information into SQL. First you’ll need to get started with a database that will hold all your tables.
-
Type the following line of code to create a database called
travel_db
and then press enter to execute the command.Note
Spaces aren’t allowed in SQL database or table names, so you can use an underscore instead.
-
11Now tell the RDMBS to actually use the database.
Creating a SQL table
Now that you have a database for Abby’s travel information, it’s time to create a table of values. Let’s warm up by building a miniature version of the full dataset.
Say you’d like to create a table for some of the cities Abby would like to visit along with their countries. Below is a single command to type into your console window. When you’ve typed it, you can press enter to tell your RDBMS to go ahead and execute the command.
Steps for creating a general SQL table
You now know the overall steps to set up a table in SQL:
-
If it doesn’t already exist, create a database to contain your table.
-
Instruct your RDMBS to use that database.
-
Create your table by giving it a name and specifying the columns and data types it will store.
Your table is ready
Now that you know what each line of the CREATE
TABLE
code does, you’re ready to make Abby’s travel table within her database. You can enter the CREATE
TABLE
command one line at a time or as one really long single line.
Whichever way you choose, just before you hit enter after the semicolon, make sure you haven’t missed any characters or made any typos.
Note
VARCHAR(3) is very different than VARCHAR(30)!
When you’re ready, run this into your SQL console:
Actually, you’ll need a few more data types for other kinds of information.
Suppose Abby wants to add a column for the proposed date of her travels to each city. We wouldn’t want to store that as a VARCHAR
or an INTEGER
because another data type (called DATE
) has been specifically created for information like that. And that’s just one example. There are several other useful data types you haven’t met yet...
A selection of common data types
Data types help your RDBMS know what kinds of actions are (and are not) allowed on your data. They tell SQL how to process your information and how much storage to allocate for each entry.
These are a few of the most useful data types. You’ve already met VARCHAR
and INTEGER
, but have a look at some new types and examples to expand your collection.
Data types for text
These data types store text-based information like names and categories. If you know exactly how many characters your column entries will contain, use CHAR
for specific amount of storage; if not, stick with VARCHAR
to adjust the storage amount as you go.
Data types for numbers
Numeric data types in SQL break down into two categories: those with and without decimals. Either way, you can do math calculations like a sum or average on columns with numeric types.
Data types for dates and times
Some RDBMSs like MySQL have dedicated data types to store dates and times. You can do special computations with these such as extracting the year or month from a column of dates.
A data type for other things
What about data that doesn’t fall into one of these categories?
Can SQL store large documents, images, or even music? Yes, it can. You can use a data type called BLOB
to hold large data files like these.
Who am I?
A bunch of SQL data types, dressed in full costume, are playing the party game, “Who am I?” They’ll give you a clue, and you try to guess who they are based on what they say. If they happen to say something that could be true for more than one party guest, write down all who qualify. Fill in the blanks next to the sentences with the name of one (or more!) attendees.
Tonight’s guests are:
CHAR, VARCHAR, INT, DEC, DATE, DATETIME, and BLOB.
Answers in “Who am I? Solution”
Good call. Checking your work is important.
To see a summary of the locations
table you just made for Abby, use the DESC
command.
DESC
is short for DESCRIBE
, and you can run it for any of your SQL tables to list out the table columns and their associated data types.
Your table, DESCribed
You can use the DESC
command by typing it along with the name of your table:
Try it out on the locations
table you built. Once you enter it into your RDBMS, you should see something similar to this:
Changing table properties
Once you’ve reviewed the description of your table, you may find accidental errors or things you would like to change. For example, maybe there’s a column you wish you would have included—or one you wish you could get rid of.
Code Magnets
Oh no! We had carefully laid out the SQL code to create the travel database and the locations
table with the new state
column on the next page, but all the magnets fell on the floor. It’s your job to put them back together again to recreate the command. Some of the parentheses and semicolons fell on the floor and they were too small to pick up. Add as many of those as you need!
Magnets on the next page
Code Magnets Solution
Oh no! We had carefully laid out the SQL code to create the travel database and the locations
table with the new state
column on the next page, but all the magnets fell on the floor. It’s your job to put them back together again to recreate the command. Some of the parentheses and semicolons fell on the floor and they were too small to pick up. Add as many of those as you need!
Dropping and recreating tables
You’re going to need to get rid of your old locations
table and recreate it if you want to add in a column for US states.
Lucky for you, dumping an old table is much simpler than creating new one. All you need is the DROP TABLE
command:
Let’s try it on Abby’s travel table,which is called locations
:
Now that travel_db
no longer has a locations
table, you can enter a CREATE TABLE
statement to recreate it and add the state
column.
Adding a new column
We just added the state
column to our locations
table. We stayed within the travel_db
database and followed these steps to add a new column to our existing table:
-
We created the original table with
CREATE TABLE
. We gave it a name and supplied the column names and data types. We decided the table needed an additional column. -
We used
DROP TABLE
with the table name to completely get rid of our table. -
We recreated the table using
CREATE TABLE
once again. We used the same table name but added the new column to our column list along with its data type.
That’s an excellent idea, and you’ll want to use a text editor throughout this book.
Once you type and save your commands in a text editor like Notepad or TextEdit, you can copy and paste them into your SQL console. If you ever need the same or a similar command, you’ll have something to begin from. Or if you ever make a typo, you won’t need to start from scratch. You can just edit your saved code.
Hitting your cruising altitude
Nice work getting Abby’s data off to a great start! You built her a database to store her travel tables and created the structure for her locations
table. The information in her stacks of sticky notes and crumpled notebook pages is about to find a new digital home in SQL.
Pat yourself on the back for completing Chapter 1 and pull up your landing gear up because you’ve officially reached your cruising altitude and the fun is just beginning.
SQLcross
Take some time to sit back and give your left brain something to do. It’s your standard crossword; all of the solutions are words from this chapter.
Across
2. Each category of data forms a ______ in your table.
4. This holds a flexible amount of text data.
5. This structure organizes data into rows and columns.
6. Use this command to inspect table details.
7. End every SQL statement with one of these.
9. This numeric data type works for prices such as 19.99.
10. Also called a record, this holds information for a single item.
Down
1. A ______ holds tables and other SQL structures.
2. This keyword can help you make a DATABASE or a TABLE and goes in front of either.
3. This command lets you switch into a database.
6. To get rid of your table, use ______ TABLE.
8. This data type likes whole numbers (even negatives!) but not fractions.
Answers in “Who am I? Solution”
Your SQL toolbox
You’ve got Chapter 1 under your belt, congratulations! You already know how to create databases and tables. You can make columns with some of the most common data types, and you know what to do if you forget a column. Take a moment to review this chapter’s content and watch your SQL Toolbox fill up!
Who am I? Solution
From “Who am I?”
A bunch of SQL data types, dressed in full costume, are playing the party game, “Who am I?” They’ll give you a clue, and you try to guess who they are based on what they say. If they happen to say something that could be true for more than one party guest, write down all who qualify. Fill in the blanks next to the sentences with the name of one (or more!) attendees.
Tonight’s guests are:
CHAR, VARCHAR, INT, DEC, DATE, DATETIME, and BLOB.
SQLcross Solution
Take some time to sit back and give your left brain something to do. It’s your standard crossword; all of the solutions are words from this chapter.
From “SQLcross”
Across
2. Each category of data forms a ______ in your table.
4. This holds a flexible amount of text data.
5. This structure organizes data into rows and columns.
6. Use this command to inspect table details.
7. End every SQL statement with one of these.
9. This numeric data type works for prices such as 19.99.
10. Also called a record, this holds information for a single item.
Down
1. A ______ holds tables and other SQL structures.
2. This keyword can help you make a DATABASE or a TABLE and goes in front of either.
3. This command lets you switch into a database.
6. To get rid of your table, use ______ TABLE.
8. This data type likes whole numbers (even negatives!) but not fractions.
Get Head First SQL, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.