0% found this document useful (0 votes)
146 views212 pages

Head First SQL A Learners Guide To Querying and Managing Data - Kimberley Fessel - 2nd Edition (2024)

Head First SQL is a learner's guide focused on querying and managing data using SQL, with the second edition published in August 2026. The book provides early release content, allowing readers to engage with the material before the final version is available. It covers essential topics such as data organization, SQL commands, and the creation of databases and tables, using practical examples to illustrate concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
146 views212 pages

Head First SQL A Learners Guide To Querying and Managing Data - Kimberley Fessel - 2nd Edition (2024)

Head First SQL is a learner's guide focused on querying and managing data using SQL, with the second edition published in August 2026. The book provides early release content, allowing readers to engage with the material before the final version is available. It covers essential topics such as data organization, SQL commands, and the creation of databases and tables, using practical examples to illustrate concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 212

Head First SQL

SECOND EDITION

A Learner’s Guide to Querying and Managing Data

With Early Release ebooks, you get books in their earliest form—the
author’s raw and unedited content as they write—so you can take
advantage of these technologies long before the official release of
these titles.

Kimberly Fessel
Head First SQL
by Kimberly Fessel

Copyright © 2026 Dr Kim Data LLC. All rights reserved.

Printed in the United States of America.

Published by O’Reilly Media, Inc. , 1005 Gravenstein Highway


North, Sebastopol, CA 95472.

O’Reilly books may be purchased for educational, business, or


sales promotional use. Online editions are also available for
most titles ( http://oreilly.com ). For more information, contact
our corporate/institutional sales department: 800-998-9938 or
[email protected] .

Editors: Melissa Potter and David Michelson

Production Editor: Katherine Tozer

Interior Designer: David Futato

Cover Designer: Karen Montgomery

Illustrator: Kate Dullea

August 2026: Second Edition


Revision History for the Early
Release
2024-02-13: First Release

See http://oreilly.com/catalog/errata.csp?isbn=9781098163655
for release details.

The O’Reilly logo is a registered trademark of O’Reilly Media,


Inc. Head First SQL , the cover image, and related trade dress
are trademarks of O’Reilly Media, Inc.

The views expressed in this work are those of the author and do
not represent the publisher’s views. While the publisher and
the author have used good faith efforts to ensure that the
information and instructions contained in this work are
accurate, the publisher and the author disclaim all
responsibility for errors or omissions, including without
limitation responsibility for damages resulting from the use of
or reliance on this work. Use of the information and
instructions contained in this work is at your own risk. If any
code samples or other technology this work contains or
describes is subject to open source licenses or the intellectual
property rights of others, it is your responsibility to ensure that
your use thereof complies with such licenses and/or rights.
978-1-098-16359-4

[]
Brief Table of Contents (Not Yet
Final )
Chapter 1: Data and Tables (available)

Chapter 2: Inserting Data (available)

Chapter 3: The SELECT Statement (unavailable)

Chapter 4: CRUD Operations (unavailable)

Chapter 5: Advanced SELECT (unavailable)

Chapter 6: Smart Table Design: Normalization and Multiple


Tables (unavailable)

Chapter 7: Efficiency Considerations: Data Types and Indexes


(unavailable)

Chapter 8: Join Types (unavailable)

Chapter 9: Subqueries (unavailable)

Chapter 10: Temporary Tables and Table Variables (unavailable)

Chapter 11: Stored Procedures and Functions (unavailable)


Chapter 12: Constraints and Views (unavailable)

Chapter 13: Locking, Blocking, and Isolation (unavailable)

Chapter 14: Security (unavailable)

Chapter 15: Databases and the Cloud (unavailable)

Chapter 16: SQL Across Other Databases (unavailable)

Appendix: Installing MySQL on Mac or Windows (unavailable)


Chapter 1. Databases and Tables:
Organizing Your Information
A NOTE FOR EARLY RELEASE READERS

With Early Release ebooks, you get books in their earliest form
—the author’s raw and unedited content as they write—so you
can take advantage of these technologies long before the official
release of these titles.

This will be the 1st chapter of the final book. Please note that
the GitHub repo will be made active later on.

If you have comments about how we might improve the content


and/or examples in this book, or if you notice missing material
within this chapter, please reach out to the editor at
[email protected] .
Figure 1-1.

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

Figure 1-2.
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!
Figure 1-3.
BRAIN POWER

Figure 1-4.

Is there a better way to organize this information?

Do you have any notes like these that could use a better
organization system?
Figure 1-5.

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.
SHARPEN YOUR PENCIL

Figure 1-6.

Here are a few of Abby’s notes. What types of information do


these entries have in common? Give each category of
information a descriptive label and write those labels in the
space provided below.

We’ve added a few to get you started.


Figure 1-7.
SHARPEN YOUR PENCIL SOLUTION

Figure 1-8.

Here are a few of Abby’s notes. What types of information do


these entries have in common? Give each category of
information a descriptive label and write those labels in the
space provided below.

We’ve added a few to get you started.


Figure 1-9.
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:

Figure 1-10.

Now take the labels that you just made for each category, and
place those above the corresponding bits information like this:

Figure 1-11.
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:

Figure 1-12.
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?

Figure 1-13.

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 S tructured Q uery L anguage, though its origin
story differs from that slightly.

Figure 1-14.
WATCH IT!

Figure 1-15.

You’re going to need SQL.

You can code in SQL through a variety of platforms and tools. Be


sure to read the introduction of this book and check out Appendix
II to get an application to work with SQL on your computer.
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.

Figure 1-16.

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.
Figure 1-17.

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 .
Figure 1-18.
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:

Figure 1-19.
Figure 1-20.

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.

Figure 1-21.
Figure 1-22.
Figure 1-23.
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.

Figure 1-24.
Figure 1-25.
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.

Figure 1-26.
Figure 1-27.
Figure 1-28.

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.
Databases contain related
information
All of the tables in a database should be related and connected
to each other in some way. For example, the coffee purchases
you worked previously with could belong to a database that
contains information about place you like to shop:

Figure 1-29.
BRAIN POWER

Figure 1-30.

Can you think of any databases you interact with in your daily
life?

What tables do you think they contain? And what columns do


those tables have?
SHARPEN YOUR PENCIL

Figure 1-31.

Consider the databases and tables below. Think about the


categories of information you might find in each. Come up with
likely columns for each table. For the final database, suggest
two possible tables as well.

We did the first table to start you off.


Figure 1-32.
SHARPEN YOUR PENCIL SOLUTION

Figure 1-33.

Consider the databases and tables below. Think about the


categories of information you might find in each. Come up with
likely columns for each table. For the final database, suggest
two possible tables as well.

We did the first table to start you off.


Figure 1-34.
Figure 1-35.

Yes, we are!

Abby has been patient long enough, and it’s finally time to turn
her travel notes into a relational database .

A relational database consists of information in a tabular


format. That just means the data will be stored in tables with
rows and columns, just like the ones we’ve been talking about.
You’re about to create a database and then a table to store
Abby’s travel entries. But first, make sure you have the
necessary software installed.
WATCH IT!

Figure 1-36.

If you’re not using MySQL, your mileage may vary.

We’re using MySQL to work with our databases. If you’re using


an alternate database management system (DBMS), the
commands in this book might look a little different on your
machine.

See Appendix II for instructions on installing MySQL on your


server.
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.

Figure 1-37.

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:
Figure 1-38.
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.

Figure 1-39.

11Now tell the RDMBS to actually use the database.


Figure 1-40.
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.

Figure 1-41.
Figure 1-42.
SHARPEN YOUR PENCIL

Figure 1-43.

Example 1-1. Look how easy it is to write SQL

The code to the left is our CREATE TABLE statement for Abby’s
full travel table. Try to guess what each line of the CREATE
TABLE command does.

Also give an example of the data that will go in each column


(besides the example provided).

We’ve done a few to get you started.


Figure 1-44.
Figure 1-45.
SHARPEN YOUR PENCIL SOLUTION

Figure 1-46.

Example 1-2. Look how easy it is to write SQL

The code to the left is our CREATE TABLE statement for Abby’s
full travel table. Try to guess what each line of the CREATE
TABLE command does.

Also give an example of the data that will go in each column


(besides the example provided).

We’ve done a few to get you started.


Figure 1-47.
Figure 1-48.
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.

Figure 1-49.

Instruct your RDMBS to use that database.

Figure 1-50.

Create your table by giving it a name and specifying the


columns and data types it will store.
Figure 1-51.
BRAIN POWER

Figure 1-52.

This process allows you to create a SQL table, but what other
steps will Abby need before she can plan a trip with her travel
notes?
THERE ARE NO DUMB QUESTIONS

Q: Why did we need two commands for the travel_db


database?

A: The first command created travel_db and the second


command asked the RDBMS to actually work with it. You can
create as many databases as you’d like, but you can only use
one database at a time. Once you’re using a database, all the
tables you create will be contained within that database.

Q: I noticed that we used capital letters for the SQL


commands and lowercase letters for the database name. Is
that necessary?

A: Some systems do require certain keywords to be capitalized,


but SQL itself is case insensitive. That said, it’s best practice to
capitalize SQL commands to help out with readability. Just look
at the command we executed:

CREATE DATABASE travel_db;

The capitalization makes it easy to quickly see that CREATE


DATABASE is the command while travel_db is the database
name.

Q: What if I only need to create one table; do I still need a


database for it?

A: Yes, you do. SQL requires all tables to belong to a database,


and there are good reasons for this. For example, SQL allows
multiple users to access table data. Being able to grant (or
deny!) access to an entire database is sometimes simpler than
needing to control the permissions on each and every table.

Q: Is there anything I should know about naming my


databases, tables, and columns?

A: You’ll generally want to give descriptive names to all your


SQL items. For example, “ travel_hours ” is a much better
name than “ column6 ”.

Sometimes you’ll want to use more than one word in your


names, but you can’t use spaces. The underscore let’s you
combine words for more descriptive names. Some options
include:

travel_db
travel_database
traveldb
travelDB
travelDatabase

All of these are valid SQL names, but it’s generally best practice
not to capitalize the first letter of your names to avoid
confusion.

You should also avoid most special characters like apostrophes.


There are ways you can include these, but it’s far simpler to
skip them altogether.

Q: What if I prefer to use “travelDatabase” with no


underscore?

A: Go right ahead. The important thing is to be consistent. If you


use travelDatabase , with no underscore and the second word
capitalized, then you should stick to that naming convention
throughout all your tables in the database. For instance, you
should name a table with contact information myContacts to
continue the trend.

Q: I also noticed that we included a semicolon at the end of


each SQL command. Is that necessary and why is it there?
A: The semicolon at the end of your SQL statements signals that
your command is over. Some database management systems
don’t require a semicolon as a statement terminator, but MySQL
does. So we will use them in this book.

Q: What happens if I leave the semicolon off when I press


enter?

A: MySQL will “hang” and wait for more input commands until
you do. If you press enter before including a semicolon, MySQL
will go on to the next line like this:

mysql> USE travel_db


->

This is helpful because sometimes it’s useful to break up


commands onto multiple lines for readability. If you ever
accidentally forget semicolon, just type one on the next line and
press enter once more.

Q: Is there a way to see all the databases I have access to?

A: Yes, you can. The command to do this strongly depends on


which RDBMS you are using, but in MySQL you can run the
command:
SHOW databases;

You’ll see a list of all your databases, including those you


created and others that come with MySQL like sys and
information_schema .
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:


Figure 1-53.

Figure 1-54.
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.

Figure 1-55.

Figure 1-56.
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.

Figure 1-57.

Figure 1-58.
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.

Figure 1-59.

Figure 1-60.
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.

Figure 1-61.
WATCH IT!

Figure 1-62.

These data type names may be different in your SQL


RDBMS.

Unfortunately, there are no universally accepted names for


various data types. Your SQL RDBMS might use different names
for one or more of these types. Check your documentation to
learn the correct names for your RDBMS.
Who am I?

Figure 1-63.

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.


Figure 1-64.

Answers in “Who am I? Solution”


THERE ARE NO DUMB QUESTIONS

Q: Why should I care about data types at all?

A: There are two main reasons. First, the data type lets your
RDBMS know what types of actions can be performed on the
data in that column. For example, you can do mathematical
operations on numerical columns but not on ones with text.
Second, the data type dictates how much storage should be
allocated. Items entered in a BLOB column can be much, much
bigger than a CHAR(1) column.

Q: Since it can hold anything, why not just use BLOB for all
my values?

A: As tempting as that is, it’s a waste of space. BLOB takes up


much more storage than the other data types. As your database
grows, you risk running out of space on your computer. You
also can’t do important calculations on BLOB that you can do on
text ( VARCHAR , CHAR ) or numerical ( INT , DEC ) data types.

Q: Why do I need two data types for numerical values?

A: It all comes down to database storage and efficiency.


Choosing the best matching data type for each column in your
table will reduce its size and operations on your data faster.
Q: How do I choose the number of characters I’ll need for
VARCHAR ?

A: You’ll do your best to estimate the maximum number of


characters any entry one entry in that column will contain. Try
not to underestimate the number of characters because you’ll
get an error if you exceed the limit. Also try not to overestimate
to avoid wasting space. It’s better to estimate a little over rather
than a little under, though.

Q: Why do some data types have two names like CHARACTER


and CHAR ? Is there any difference between these?

A: Nope! You can use CHARACTER and CHAR interchangeably.


You can just think of CHAR as a nickname. It’s shorter to type
out, so you’ll likely see it used more often than CHARACTER . The
same goes for INTEGER and INT as well as DECIMAL and DEC .

Q: Do I have to decide the data type for each column up


front?

A: Yes, you do. You’ll need to specify what data type each
column has before adding any information to your table. There
are ways to update your column’s data type later, but it’s easiest
if you don’t need to.
Q: What happens if I type in the data type incorrectly or
select the wrong number of characters for CHAR or VARCHAR
?

A: You need to type everything in correctly. Making a typo in


the data type will likely cause an error, and the wrong number
of text characters will either waste space or yield errors. Create
each table with care.

Q: But what if I make a mistake in CREATE TABLE?

A: You’ll see one way to recreate a table shortly, but we’ll talk
about ways to fix SQL tables in Chapter 6.

Q: Is this it? Are these all the types?

A: No, but these are the most important ones. Data types also
differ slightly by RDBMS, so consult your system’s
documentation for more information.
Figure 1-65.

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:

Figure 1-66.

Try it out on the locations table you built. Once you enter it
into your RDBMS, you should see something similar to this:
Figure 1-67.
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.

Figure 1-68.
BRAIN POWER

Figure 1-69.

What sorts of problems do you think adding a new column


could create?
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!

Figure 1-70.

Magnets on the next page


Figure 1-71.
EXERCISE

Figure 1-72.

An exercise within an exercise? Yep, we’re crafty like that.


When you finish rearranging the magnets, try typing the code
you just constructed into your SQL RDBMS. Write your RDBMS’s
response here:

..........................................................................................................................
...

If that doesn’t work, try adding the new state column by


executing only the CREATE TABLE part of the code from within
the travel_db database. Again, write your RDBMS’s response
here:

..........................................................................................................................
...
Figure 1-73.
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!
Figure 1-74.
EXERCISE SOLUTION

Figure 1-75.

Did you try entering the reconstructed command into your


console? If you did, you already know that the Code Magnets
solution didn’t help you create a new state column.

You probably saw something like this when creating the


travel_db database:

Figure 1-76.

Or if you only entered the code to create the locations table


within travel_db , you got this:
Figure 1-77.

SQL databases must be given unique names , and the tables


within a database must all have unique names. That means
you’ll get an error if you try to create one that already exists.

You can’t recreate an existing database or table!


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:

Figure 1-78.

Let’s try it on Abby’s travel table,which is called locations :

Figure 1-79.
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.

Figure 1-80.
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:
MAKE IT STICK

Figure 1-81.

Roses are red,

Violets are blue.

Within one database,

Table names must be new.

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.
WATCH IT!

Figure 1-82.

Don’t DROP without double checking.

The DROP TABLE command deletes your table... and any data in
it! Be very sure you want to get rid of everything before
executing it.
THERE ARE NO DUMB QUESTIONS

Q: So if I need to add a column, I have to drop my table and


recreate it. What if I already have data in my table? Do I
really have to delete all my information?

A: In this case, it was best just to drop the table and start over
since we hadn’t added any of Abby’s travel data yet. But in cases
where you already have a full table of info, there is a way to
change your table without deleting everything. We’ll get into
that much more later on.

Q: What if I try to drop a table that doesn’t exist?

A: You’ll get an error. This definitely can happen by accident, so


you can add the optional SQL keywords IF EXISTS to your
drop command like this:

DROP TABLE IF EXISTS


my_table;

This command drops the table called my_table if it exists;


otherwise,it does nothing.
Q: You said two tables within the same database can’t have
matching names. What about tables in different databases?

A: Good catch. Tables in different databases can have the same


name. For example, you could create a locations table in
travel_db and a locations table in a separate database
called real_estate_db . These locations tables could have
the same or different columns.

Figure 1-83.
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.

Figure 1-84.
SHARPEN YOUR PENCIL

Figure 1-85.

Below you’ll find a sequence of SQL commands, meant to be


entered in the console in order from top to bottom. Classify
each command as “OK” or “Error”. For each statement that is
OK to run, describe what will happen when you execute the
command; for those that produce an error, explain why the
statement won’t work.

We did a few to kick things off.


Figure 1-86.
SHARPEN YOUR PENCIL SOLUTION

Figure 1-87.

Below you’ll find a sequence of SQL commands, meant to be


entered in the console in order from top to bottom. Classify
each command as “OK” or “Error”. For each statement that is
OK to run, describe what will happen when you execute the
command; for those that produce an error, explain why the
statement won’t work.

We did a few to kick things off.


Figure 1-88.
SQLcross

Figure 1-89.

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.
Figure 1-90.

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

Figure 1-91.

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!
Figure 1-92.
BULLET POINTS

When getting started organizing new information into tabular


format with SQL:

Break up your data into logical categories. These will


become the columns of your tables.
Use CREATE DATABASE to create the database that will hold
all of your tables.
Enter the command USE with your database’s name to tell
your SQL RDBMS to switch into your database.
All tables are created with a CREATE TABLE statement. Add
column names and their data types here.
Some of the most common data types include VARCHAR ,
CHAR , INT , DEC , DATE , DATETIME , and BLOB . Each has
different rules for what goes inside and how much storage
to allocate.
You can check the properties of your columns with the
command DESC .
Run the DROP TABLE statement to throw away your table.
Use it with care!
Who am I? Solution

Figure 1-93.

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.


Figure 1-94.
SQLcross Solution

Figure 1-95.

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”
Figure 1-96.

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.
Chapter 2. Inserting Data: Adding
Table Rows
A NOTE FOR EARLY RELEASE READERS

With Early Release ebooks, you get books in their earliest form
—the author’s raw and unedited content as they write—so you
can take advantage of these technologies long before the official
release of these titles.

This will be the 2nd chapter of the final book. Please note that
the GitHub repo will be made active later on.

If you have comments about how we might improve the content


and/or examples in this book, or if you notice missing material
within this chapter, please reach out to the editor at
[email protected] .
Figure 2-1.

Ready to fill ‘er up? Creating databases and tables is great fun,
but what’s the point of all that precious SQL structure without
actual data to occupy it?

That’s where this chapter comes in: here, you’ll learn how to
add values to your tables with the INSERT command. You’ll
see plenty of INSERT variations and meet that infamous NULL
character you’ve heard spooky stories about. But not to worry,
you’re also going to be able to tame those missing values with
some minor adjustments to your CREATE TABLE statement.

There’s a lot to be done, so come on in. And remember, in SQL, a


full table is a happy table.
Setting up a database with tables
In Chapter 1 , you learned that you can store data in a
relational database that contains tables . You can think about
your information as categories, which become the columns of
your table. The rows of your table, on the other hand, hold
information for a single item.

Figure 2-2.
Plan and set up your structure in SQL before adding any
data.
BRAIN POWER

Figure 2-3.

What are the benefits of deciding the structure of your


database, tables, and columns ahead of time? Are there any
drawbacks?
Checking back in with Abby
Abby needs a way to organize her travel notes, and you helped
her set up a SQL database called travel_db along with a table
called locations in the previous chapter. But now she’s ready
to add her information.
Figure 2-4.
Inserting data into tables
Now that you’ve set everything up, it’s time to actually put a
row of data into your table. For that, you’ll use a new SQL
command called INSERT . Here’s the goal:

Figure 2-5.

Take a look at the template statement below to see how each


part of INSERT works. Keep in mind that the values in the
second set of parentheses need to be in the exact same order
as the column names in the proceeding parentheses.
Figure 2-6.
WHO DOES WHAT?

Before you write an INSERT statement for Abby, match up your


column names and values. These must be matched correctly
before including them in INSERT .
Figure 2-7.
WHO DOES WHAT? SOLUTION

Before you write an INSERT statement for Abby, match up your


column names and values. These must be matched correctly
before including them in INSERT .
Figure 2-8.
Creating your INSERT statement
Now let’s insert the data for Boston into Abby’s table. Review
the code below and then try it out for yourself in the exercise.

Figure 2-9.
WATCH IT!

Figure 2-10.

Order matters!

The values should be listed in the exact same order as the


column names.
EXERCISE

Figure 2-11.

This is one way to add a row of data to your table. Try it


yourself. Type the command into a text editor first. That way, if
you make a mistake, you won’t have to retype the entire thing.
Pay attention to the single quotes and commas. Then make sure
you’re in the travel_db database, and enter it into your SQL
console. Write the response you get here:

...................................................................................................................
Figure 2-12.

Not always and yes usually.

It may feel like a lot of typing, but it’s important to practice


writing out the full INSERT statement so you can understand
the connection between all of its parts. We’ll see ways to reduce
the amount of typing shortly.

Whether or not it’s worth putting your data into SQL comes
down to how often you’ll need to access it and perform
calculations on it. As you’ll learn in this book, SQL is a powerful
language for creating, querying, and transforming your data.
There are many different actions you can perform with SQL, so
for large databases of information, its benefits strongly
outweigh the initial chore of setting everything up.
SHARPEN YOUR PENCIL

Figure 2-13.

Your SQL RDBMS will tell you when something is wrong with
your statement, but it will sometimes be a bit vague. Try to
figure out what’s wrong with each of the following INSERT
statements. Then type it in to see what your RDBMS reports.
Figure 2-14.
SHARPEN YOUR PENCIL SOLUTION

Figure 2-15.

Your SQL RDBMS will tell you when something is wrong with
your statement, but it will sometimes be a bit vague. Try to
figure out what’s wrong with each of the following INSERT
statements. Then type it in to see what your RDBMS reports.
Figure 2-16.
See your table with SELECT
Once you’ve added the Boston information to the locations
table, how can you see what you’ve entered? (Be sure to do the
Exercise in “Exercise” before proceeding.)

The DESC command only shows us the structure of the table,


not the information inside it. Instead, you should use a SELECT
statement to see the data in your table. Here’s how it works:

Figure 2-17.
RELAX

Figure 2-18.

Don’t worry much about SELECT for now.

We’ll look at SELECT a lot more in Chapter 3. For now, just sit
back and marvel at the beauty of your table when you use this
command.

NOTE

Now try it yourself to view Abby’s Boston data. You’ll have to stretch out
your console window to see all the results laid out nicely.
Figure 2-19.
A new recommendation
Abby’s coworker, Milo, recently returned from New Delhi and
could not stop raving about his trip.

Figure 2-20.

Abby jotted down Milo’s recommendations but hasn’t done any


further research. Here’s what she has so far about New Delhi
and how that compares to the locations table you already
started:
Figure 2-21.
Records with missing values
Even though her note is missing some information, we can
input the data she does have with an INSERT statement. Abby
can add the missing items to the record later.

You can insert a few columns while leaving others out:

Figure 2-22.

And here’s what happens when you enter the INSERT


statement into your SQL console:
Figure 2-23.
Revisiting your table
So far, you’ve added travel information for Boston and New
Delhi into the locations table. You had complete data for
Boston but incomplete information about New Delhi. Thinking
in terms of rows and columns, your table might look like this:

Figure 2-24.

Only a few of the New Delhi columns have values, so what


shows up in SQL in the places where information is missing?
Use SELECT to take a look at the locations table after adding
the New Delhi row:
Figure 2-25.
TODAY’S INTERVIEW: CONFESSIONS OF A NULL

Figure 2-26.

Head First: Welcome, NULL. I have to admit, I didn’t expect to


see you, but thanks for joining us. We’ve heard you can be hard
to pin down. In fact, there’s a rumor going around that you’re
nothing more than a zero, or nothing at all.

NULL : That’s absurd! Yes, I’m here, and I’m very real. You think
I’m a figment of your imagination?

Head First : Well, not exactly. But it’s just that you show up
whenever something has no value...

NULL : Sure, better me than, say, a zero, or an empty string.

Head First: What’s an empty string?

NULL : You know... a blank bit of text. You could make one with
two single quotes with nothing inside them. It’s still considered
text, but has length zero. Like setting the value of state in the
locations table to”.

Head First: Oh, thanks for that. So you aren’t just a fancy way
of saying nothing?

NULL : I thought I already told you, I’m not nothing! I represent


something... just something a bit undefined.

Head First : So if we compare you to zero or an empty string,


you’re saying you wouldn’t equal either of those?

NULL : Absolutely not! I’d never be equal to zero or an empty


string or even another NULL. You can’t compare one NULL to
another. A value can be NULL, but it never equals NULL
because NULL is an undefined value. Alright?

Head First : Whoa, slow down, NULL. Let’s get this straight. You
aren’t equal to zero. You aren’t equal to an empty string. And
you aren’t even equal to yourself? That makes no sense!

NULL : Yeah, I’ll admit it’s confusing. Just think of me this way:
I’m undefined. I represent missing data. You don’t know what
value should go in my place, so I could be filling in for
anything. I might even be empty. You just don’t know.
Head First : Okay. I guess that tracks. Well, we also want to
address another potentially sensitive subject. We’ve heard that
sometimes you aren’t wanted. That maybe there are times
when you NULLs cause problems.

NULL : Since this interview feels like a safe space, I’ll give you
the scoop. I confess it. I have been known to show up in
surprising places before. What, you’ve never crashed a party or
two? But in all seriousness, some columns should always have
values. Like city in the locations table. No point recording
the other details for a NULL city.

Head First : So you wouldn’t go where you weren’t wanted?

NULL : Hey, just tell me where I don’t belong. When you’re


creating your table and setting up your columns, just let me
know.

Head First : We can do that? Cool. Thank you for yet another
pearl of wisdom, NULL.

NULL : Not a problem. See? I’m not a nuisance after all. Now
let’s wrap this up. I’ve got places to go and values to stand in for.
THERE ARE NO DUMB QUESTIONS

Q: So a NULL shows up in my table for every missing value?

A: Yes, it does. Any time you execute an INSERT statement,


columns that you leave off will get a NULL for that row. The
only exception is for tables that are set up differently in their
CREATE TABLE commands. We’ll see more about that soon.

Q: You mentioned I can fill in information for the NULLs


later. How does that work?

A: If you want to fill in missing information, you can use a


command called UPDATE , which you’ll learn about in Chapter
5.

Q: In INSERT , why do I need to provide the column names


along with the values in the exact same order?

A: This is so SQL knows where to place each value. In the New


Delhi example, we didn’t have values for every column, so we
needed to let SQL know where each value should go. We
ensured that SQL placed the values in the correct column by
specifying the column names in the exact same order as their
matching values.
Q: What if I make a mistake when using INSERT ?

A: The UPDATE and DELETE commands you’ll see in Chapter 5


allow you to correct typos and other mistakes.

Q: About the SELECT statement, does SELECT always return


your full table? What about really large tables?

A: We’ll spend a lot more time covering the SELECT statement


in Chapters 3, 4, and 6, but to briefly answer your questions, no,
it does not always return your full table. Many times you’ll
want to narrow down to specific rows or columns, especially in
cases of very large tables.

Q: How is SELECT different from the DESC command?

A: DESC shows you a description of your table structure,


including its columns and their data types. SELECT shows you
the actual data your table contains.
Figure 2-27.

Yes, there is.

There’s some information that just should not be NULL . Can


you imagine Abby entering a row of travel information but
skipping the city name? That doesn’t sound useful. You can
make sure NULL s never show up in a particular column by
saying they aren’t allowed when you set up your table. More on
how to do that after an exercise...
GUIDED: EXERCISE

Figure 2-28.

It’s time to build a new table of data in SQL, but don’t worry,
we’ll help you along the way. Your eventual goal is to organize
your grocery purchases and recreate the table of information
found at the bottom of this page. Follow the outlined steps by
writing your own SQL code and typing it into your console.
Once you think you know how to solve a step or two, check our
solution to make sure it matches your answer before
proceeding.

Create a new database called expenses .


Switch into the expenses database.
Think you’ve got the right code for steps 1 and 2? Here’s our
solution :
Figure 2-29.

Now create a new table called grocery_bills . Include


the column names from the table below and pick an
appropriate data type for each column.

Figure 2-30.

Turn the page to continue


GUIDED: EXERCISE

Figure 2-31.

You are in the process of recreating a table with grocery bill


information.

This is how you can solve Step 3 and create the table structure
in SQL:

Figure 2-32.

Before adding any data, check your table by viewing its


description.
Figure 2-33.

Now that your table is set up, insert the four rows of
table data. Pay special attention to the missing values.

Figure 2-34.
Figure 2-35.

Lastly, take a look at your table data with SELECT . Do


you see any NULLs ?

Figure 2-36.
Controlling NULLs...
There are likely going to be columns in your table that should
always have values. You will depend on certain information to
sort, filter, or otherwise identify the records in your database,
and NULL s can really put a damper on those types of
operations. Fortunately, you can easily set up your table to not
accept NULL values for columns of your choosing.

For example, Abby’s travel information isn’t going to be very


useful if she doesn’t have a city name for each row of her table.
Likewise, she needs to know each country so she can
distinguish Paris, France , and Paris, Texas, USA .

This is how she can set up her CREATE TABLE statement to not
allow NULL s in those columns:
Figure 2-37.
BRAIN POWER

Figure 2-38.

What would happen if you ran this code within travel_db ?


... and Setting DEFAULTs
And if we have a column that we know is usually a specific
value, we can assign it a DEFAULT value. The value that follows
the DEFAULT keyword is automatically inserted into the table
each time a row is added if no other value is specified . The
default value should match the column’s data type.

Since Abby lives in the United States, many of her travel entries
feature destinations in the USA. Instead of forcing herself to
enter a country for each row, she would like a default value of
“USA” to show up if she leaves the country out of her INSERT
statement.

Here’s her CREATE TABLE command now:


Figure 2-39.

Figure 2-40.
SHARPEN YOUR PENCIL

Figure 2-41.

You’ve decided to expand your expenses database by tracking


your coffee purchases in addition to your grocery bills. Below
you’ll find SQL code to create a new table called
coffee_purchases . Notice which columns allow or do not
allow NULL s as well as those that provide a DEFAULT value:

Figure 2-42.

Here’s what happens when we use DESC on the


coffee_purchases table:
Figure 2-43.

For each of the sticky notes below, write an INSERT statement


to add the data to the coffee_purchases table we just created.
Then fill in the table with how the data will look in SQL.
Figure 2-44.
SHARPEN YOUR PENCIL SOLUTION

Figure 2-45.

For each of the sticky notes below, write an INSERT statement


to add the data to the coffee_purchases table we just created.
Then fill in the table with how the data will look in SQL.
Figure 2-46.
Variations on INSERT #1
In addition to leaving out some of the columns (which creates
NULL s or DEFAULT s), there are three other INSERT variations
you should know about.

Omitting the column names

Figure 2-47.

You can leave out the column names to reduce the amount
of typing. However, you can only do this if you provide
values for all columns, in the same order you originally
added the columns when creating your table. (Double check
the column order of Abby’s table in “Controlling NULLs...” if
you are unsure.)
Here’s what that looks like for the locations table:

Figure 2-48.
Variations on INSERT #2

Figure 2-49.

Changing the order of the columns


You can change the order of your column names, as long as
you also change the order of your values to match. For this
variation, you must provide the column names .
Otherwise, SQL won’t know where to place each of your
values in the table.
Let’s add a row to the locations table using this variation:

Figure 2-50.
Variations on INSERT #3

Figure 2-51.

Adding multiple rows at once


Finally, you can add multiple rows with just one INSERT
statement. After the VALUES keyword, provide values for
each row you want to add in a set of parentheses, separated
by commas.
This command adds three rows to locations :
Figure 2-52.
SHARPEN YOUR PENCIL

Figure 2-53.

You bought a few more drinks and want to put additional data
into the coffee_purchases table from “Sharpen your pencil” .

NOTE

Make sure to double check which columns of the


coffee_purchases table are NOT NULL or have DEFAULTs.

For each of the following INSERT statements, indicate if the


command is OK or if it will produce an error. Add the rows from
valid statements to the table like they would appear in SQL.
Figure 2-54.

Answers in “Sharpen your pencil Solution”


A punctuation problem

Figure 2-55.

But Abby’s program doesn’t seem to be responding. She types a


few semicolons, trying to get the query to end. No luck.
Figure 2-56.
BRAIN POWER

Figure 2-57.

What do you think is going on here?

Figure 2-58.
Unmatched single quotes
Exactly! When Abby tried to add a record, SQL was expecting
an even number of single quotes: one before and after each
text, date, or time value. Martha’s Vineyard , confused matters
because it had an apostrophe. The SQL RDBMS is still waiting
for one more single quote.
RELAX

Figure 2-59.

You can get back control of your console.

End the statement by typing a single quote and a semicolon. This


gives the RDBMS the extra single quote that it’s expecting.

You’ll get an error when you type a quote and semicolon, and
you’ll have to enter your INSERT command again.

NOTE

You’ll get an error, but at least you’ll be able to try again.


Figure 2-60.
INSERT data with single quotes in
it
When you’re trying to insert a VARCHAR , CHAR , or BLOB that
contains an apostrophe, you must tell your RDBMS that the
single quote isn’t meant to end the text but is part of the text
and needs to be included in the value. Here’s two ways you can
do that:

NOTE

The single quote is a “special” or “reserved” SQL character.

Add a backslash
You can put a backslash in front of your apostrophe to
indicate that it’s part of the text. Doing so is called “
escaping ” the single quote.
Add another apostrophe
Instead of just one apostrophe, use two. Including an extra
single quote also “escapes” it and lets SQL know it should be
in the value.
Figure 2-61.
THERE ARE NO DUMB QUESTIONS

Q: Did you say the single quote is a “special” character?

A: Yes, that means that the single quote has a specific function
in the SQL language. It’s used to tell your SQL software where a
text string begins and ends.

Q: Are there other special characters in SQL?

A: Yes, there are, and you’ve already seen one other: the
asterisk. You’ll learn about more special characters and their
functionality in upcoming chapters.

Q: Isn’t this single quote the same thing as an apostrophe?

A: That’s right. SQL assigns it a very specific meaning, however.


Use a single quote to tell the SQL software that the data in
between two of them is text data.

Q: Couldn’t we make it easy to identify an apostrophe by


using double quotes around text values instead?

A: No. Don’t use double quotes around text. Some RDBMSs may
allow double quotes, but stick with single quotes in case.
Q: Why did I get an error copying and pasting single quotes
from a text editor into my SQL console?

A: In SQL, the single quote on your keyboard produces a single


straight quote, but in text editors, you may get a single
quotation mark, which is slightly different. You might need to
retype the single quotes in your SQL code before entering your
INSERT commands.
It’s only up from here!
We’ve officially solved Abby’s punctuation problem and given
her multiple ways to INSERT data into her tables. You know
how to set up databases and tables and how to disallow NULL s
or provide DEFAULT s if you need to.

Great job developing your relational database skills so far, and


there’s a whole lot more you can do with SQL. After reviewing
this chapter, keep reading to learn about actually finding your
data after you’ve gone to the trouble of storing it.
Figure 2-62.
SHARPEN YOUR PENCIL

Figure 2-63.

The following SQL statement is supposed to add budget


information to the locations table for St. John’s, Canada, but it
produces an error. Rewrite the code below using the different
methods of escaping the single quote.
Figure 2-64.
SHARPEN YOUR PENCIL SOLUTION

Figure 2-65.

The following SQL statement is supposed to add budget


information to the locations table for St. John’s, Canada, but it
produces an error. Rewrite the code below using the different
methods of escaping the single quote.
Figure 2-66.
SQLcross

Figure 2-67.

How does a crossword puzzle help you learn SQL? Well, it


makes you think about words and concepts from this chapter in
a different way.
Figure 2-68.

Across

1. Use this to specify a value for a column if no other value is


assigned in an INSERT.

5. One way to escape out apostrophes (see 10 across)

8. The column names and values must be in the same _______ in


your INSERT statement.
9. Use these around text and date values in INSERT.

10. One way to escape out apostrophes (see 5 across)

11. You can’t compare one ______ to another.

Down

1. The DEFAULT value provided must match the column’s ______.


(2 words)

2. Add data to your table with this statement.

3. These keywords disallow missing column values.

4. Set up any column DEFAULT values within this command. (2


words)

6. You’ll get an ______ if you skip a NOT NULL column that has
no DEFAULT.

7. You can add multiple table ______ with one INSERT.

Answers in “SQLcross Solution”


Your SQL toolbox

Figure 2-69.

Great job completing Chapter 2 . You’ve added commands to


INSERT data and control NULL s to your toolbox. For a full list
of tooltips from this book, check out Appendix III.
Figure 2-70.
BULLET POINTS

To get data into your table, use one of the several variations
of the INSERT statement.
A NULL value is an undefined value. It does not equal zero
or an empty string.
Any columns that are not assigned values in your INSERT
statement are automatically set to NULL (unless they have a
DEFAULT ).
You can force a column to not allow missings by using the
keywords NOT NULL when you create your table.
Using a DEFAULT value when you CREATE a table fills the
column with that value if one isn’t given in INSERT .
Insert data that have apostrophes by adding an escape
character (either ' or \ ).
SHARPEN YOUR PENCIL SOLUTION

Figure 2-71.

From “Sharpen your pencil”

You bought a few more drinks and want to put additional data
into the coffee_purchases table from “Sharpen your pencil” .

For each of the following INSERT statements, indicate if the


command is OK or if it will produce an error. Add the rows from
valid statements to the table like they would appear in SQL.
Figure 2-72.
SQLcross Solution

Figure 2-73.

From “SQLcross”

How does a crossword puzzle help you learn SQL? Well, it


makes you think about words and concepts from this chapter in
a different way.
Figure 2-74.

Across

1. Use this to specify a value for a column if no other value is


assigned in an INSERT.

5. One way to escape out apostrophes (see 10 across)

8. The column names and values must be in the same _______ in


your INSERT statement.
9. Use these around text and date values in INSERT.

10. One way to escape out apostrophes (see 5 across)

11. You can’t compare one ______ to another.

Down

1. The DEFAULT value provided must match the column’s ______.


(2 words)

2. Add data to your table with this statement.

3. These keywords disallow missing column values.

4. Set up any column DEFAULT values within this command. (2


words)

6. You’ll get an ______ if you skip a NOT NULL column that has
no DEFAULT.

7. You can add multiple table ______ with one INSERT.


About the Author
Kimberly Fessel is a data science educator with over a decade
of instructional experience. She has supported students in
corporate settings, at academic universities, and most recently
as director at a data science bootcamp. Kimberly has taught
SQL to students for years, both in person and online, along with
other data management technologies like MongoDB. She’s
conducted scores of mock SQL interviews and accordingly
knows the most common stumbling blocks for beginners and
intermediates.

Kimberly is currently a data science consultant with her own


instructional brand, Dr Kim Data. Her educational YouTube
channel currently has over 16,000 subscribers, and she plans to
launch her first paid online course about data science metrics
later this Fall. Kimberly loves to teach in a highly visual,
creative manner, and the Head First book series emphatically
matches her preferred teaching philosophy.

You might also like