Page
1
A Brain-Friendly Guide SQL A Learner’s Guide to Querying and Managing Data Kimberly Fessel Second Edition
Page
2
ISBN: 978-1-098-16365-5 US $69.99 CAN $87.99 What will you learn from this book? Do you have an abundance of data but don’t know how to make sense of it? Do you want to gain useful insights from your data, but you’re not sure where to begin? Mining data is a vital, well-paying skill, and SQL provides the most fundamental way to query and manage data. But learning SQL can be intimidating. This thoroughly revised book teaches you SQL fundamentals in a painless and enjoyable manner. With the Head First series’ hands-on, conversational style, you’ll quickly grasp SQL concepts, then move to intermediate topics, including subqueries and joins. You’ll gain the knowledge, skills, and confidence necessary to get the most out of your data with SQL DATABASES / SQL Why does this book look so different? If you’ve read a Head First book, you know what to expect: a visually rich format designed for the way your brain works. If you haven’t, you’re in for a treat. With this book, you’ll learn about SQL through a multisensory experience that engages your mind—rather than a text-heavy approach that puts you to sleep. SQL “Not your standard SQL textbook. This engaging, beginner- friendly guide is packed with clear explanations, visuals, and hands-on exercises, making SQL fun and easy to learn!” —Alice Zhao author of SQL Pocket Guide “If you find SQL too technical and out of reach, give this book a try. It will break things down step-by-step using friendly examples, and even cover some bigger picture questions that other SQL books do not cover.” —Thomas Nield author of Getting Started with SQL and Essential Math for Data Science Fly through SQL fundamentals WHERE country = 'USA' WHERE travel_mode = 'plane' AND Discover the query within OUTER query INNER query
Page
3
Advance Praise for Head First SQL “Not your standard SQL textbook. This engaging, beginner-friendly guide is packed with clear explanations, visuals, and hands-on exercises, making SQL fun and easy to learn!” — Alice Zhao, author of SQL Pocket Guide “If you find SQL too technical and out of reach, give this book a try. It will break things down step-by- step using friendly examples, and even cover some bigger picture questions that other SQL books do not cover.” — Thomas Nield, author of Getting Started with SQL and Essential Math for Data Science “There are books you buy, books you keep, books you keep on your desk, and thanks to O’Reilly and the Head First crew, there is the ultimate category, Head First books. They’re the ones that are dog-eared, mangled, and carried everywhere. Head First SQL is at the top of my stack. Heck, even the PDF I have for review is tattered and torn.” — Bill Sawyer, director of database user assistance development, Oracle “This is not SQL made easy; this is SQL made challenging, SQL made interesting, SQL made fun. It even answers that age-old question ‘How to teach non-correlated subqueries without losing the will to live?’ This is the right way to learn—it’s fast, it’s flippant, and it looks fabulous.” — Andrew Cumming, author of SQL Hacks, zoo keeper at sqlzoo.net “Outrageous! I mean, SQL is a computer language, right? So books about SQL should be written for computers, shouldn’t they? Head First SQL is obviously written for human beings! What’s up with that?!” — Dan Tow, author of SQL Tuning
Page
4
Praise for the Head First Approach “It’s fast, irreverent, fun, and engaging. Be careful—you might actually learn something!” — Ken Arnold, former senior engineer at Sun Microsystems, coauthor (with James Gosling of Java), The Java Programming Language “I feel like a thousand pounds of books have just been lifted off my head.” — Ward Cunningham, inventor of the wiki and founder of the Hillside Group “Just the right tone for the geeked-out, casual-cool guru coder in all of us. The right reference for practical development strategies—gets my brain going without having to slog through a bunch of tired stale professor-speak.” — Travis Kalanick, cofounder of Uber and Scour, founder of Red Swoosh , and member of the MIT TR100 “The combination of humour, pictures, asides, sidebars, and redundancy with a logical approach to introducing the basic tags and substantial examples of how to use them will hopefully have the readers hooked in such a way that they don’t even realize they are learning because they are having so much fun.” — Stephen Chapman, Ask Felgall
Page
5
Other books in O’Reilly’s Head First series Head First Software Architecture Head First Git Head First Python Head First C# Head First Go Head First Agile Head First Swift Head First JavaTM Head First Object-Oriented Analysis and Design (OOA&D) Head First HTML with CSS and XHTML Head First Design Patterns Head First Servlets and JSP Head First EJB Head First PMP Head First Software Development Head First JavaScript Head First Ajax Head First Physics Head First Statistics Head First Rails Head First PHP & MySQL Head First Algebra Head First Web Design
Page
6
(This page has no text content)
Page
7
Head First SQL Second Edition Wouldn’t it be dreamy if there was a book that could teach me SQL without making me drift off to sleep or repeatedly whisper, “What does that even mean?” It’s probably just a fantasy... Kimberly Fessel
Page
8
Head First SQL by Kimberly Fessel Copyright © 2026 Dr Kim Data LLC All rights reserved. Published by O’Reilly Media, Inc., 141 Stony Circle, Suite 195, Santa Rosa, CA 95401. O’Reilly Media books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (oreilly.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com. Series Creators: Kathy Sierra and Bert Bates Series Advisors: Eric Freeman and Elisabeth Robson Acquisitions Editor: David Michelson Development Editor: Melissa Potter Production Editor: Katherine Tozer Proofreader: Charles Roumeliotis Indexer: Potomac Indexing, LLC Cover Design: Susan Thompson, based on a series design by Ellie Volckhausen Cover and Interior Illustrations: José Marzan Jr. Page Viewers: Abby, Kimberly’s dog—a German Shepherd-Chihuahua mix Printing History: August 2007: First Edition June 2026: Second Edition The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. The Head First series designations, Head First SQL, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and the authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. No start-up travel companies, hungry college students, or summer camps were harmed in the making of this book. ISBN: 978-1-098-16365-5 [LSI]
Page
9
To some of the great things that came out of the 1970s: relational databases, the original SEQUEL, and “Boogie Shoes,” my daughter’s favorite song. Decades later, we’re still enjoying them.
Page
10
viii The author Author of Head First SQL Kimberly Fessel is the founder of Dr Kim Data LLC. She lives in Western Connecticut with her husband, Kai; their daughter, Kodi; and the real Abby, who is actually a lovable German Shepherd-Chihuahua mix. Kimberly is a data consultant, author, and instructor. She earned her PhD in applied mathematics from Rensselaer Polytechnic Institute, and she now works with clients from all around the world to solve data problems and provide technical education. Kimberly has decades of experience educating groups and individuals in corporate settings, at academic universities, via online platforms, and as director of a data science boot camp. Kimberly’s educational YouTube channel currently boasts over 20,000 subscribers. She loves rollerblading and considers herself extremely lucky to finally put her prize-winning middle school poetry writing to good use in the “Make it Stick” exercises of this book. Kimberly’s favorite part of her job is seeing a client or student have an “Aha!” moment, and she hopes Head First SQL is one big “Aha!” for you. Kimberly Fessel The real Abby
Page
11
Table of contents ix Table of Contents (summary) Intro: How to Use This Book xxxi 1 Databases and tables: Organizing Your Information 1 2 Inserting data: Adding Data to Tables 47 3 The SELECT statement: Finding Your Information 87 4 Better WHERE clauses: Filtering Rows 125 5 CRUD operations: Controlling Your Data 165 6 Advanced SELECT: Sorting and Aggregating 197 7 Data groups: Summarizing Categories 233 8 Keys and data relationships: Thoughtful Table Design 261 9 ALTER: Changing and Optimizing 305 10 Joins and unions: Multiple-Table Operations 345 11 Subqueries: Queries Within Queries 393 12 Temporary tables: Short-Term Storage 437 13 Functions and stored procedures: Reusable Code 465 14 Constraints and views: Protecting Data Quality 505 15 Transactions and locks: Concurrency Concepts 533 16 Security: Grant, Revoke, Repeat 563 17 Databases and the cloud: SQL in the Cloud 591 18 Other databases and tools: Life Beyond MySQL 617 i Leftovers: The Top Ten Topics We Didn’t Cover 647 ii MySQL installation: Get MySQL for Yourself 665 iii Toolbox roundup: All Your New SQL Tools 673 Index 685
Page
12
Table of contents x Table of Contents (the real thing) Your brain on SQL. Here you are trying to learn something, while here your brain is doing you a favor by making sure the learning doesn’t stick. Your brain’s thinking, “Better leave room for more important things, like which wild animals to avoid and whether naked snowboarding is a bad idea.” So how do you trick your brain into thinking that your life depends on knowing SQL? Intro Who is this book for? xxxii We know what you’re thinking xxxiii Metacognition: thinking about thinking xxxv Here’s what WE did xxxvi Here’s what YOU can do to bend your brain into submission xxxvii Read me xxxviii The technical review team xl Acknowledgments xli I wonder how I can trick my brain into remembering this stuff...
Page
13
Table of contents xi Defining your data 2 Think about your data in categories 7 What is SQL? 8 The anatomy of a table 9 What’s a database? 13 There are two types of SQL users 17 Take command! 18 Creating a SQL table 20 A selection of common data types 26 Your table, DESCribed 31 Wishing for new table properties 32 Dropping and recreating tables 36 Adding a new column 37 Hitting your cruising altitude 38 Your SQL toolbox 42 Organizing your information1 databases and tables 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. column1 column2 column3 column4 row1_data row1_data row1_data row1_data row2_data row2_data row2_data row2_data row3_data row3_data row3_data row3_data row4_data row4_data row4_data row4_data column1 column2 row1_data row1_data row2_data row2_data row3_data row3_data row4_data row4_data row5_data row5_data row6_data row6_data row7_data row7_data column1 column2 column3 row1_data row1_data row1_data row2_data row2_data row2_data row3_data row3_data row3_data column1 column2 row1_data row1_data row2_data row2_data row3_data row3_data my_database purchases customersitems stores
Page
14
Table of contents xii Adding data to tables Time to dress the walls? Creating databases and tables is great fun, but what’s the point of all that precious SQL structure without actual data installed? 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 some INSERT variations and meet that infamous NULL character you’ve heard gallery ghost stories about. But not to worry, you’re also going to tame those missing values with some minor adjustments to your CREATE TABLE statement. There’s a lot to do, so don’t delay your acquisition. Let’s secure the placement of your data. inserting data 2 Setting up a database with tables 48 Inserting data into tables 50 Creating your INSERT statement 53 See your table with SELECT 56 Records with missing values 59 Controlling NULLs... 66 ...and Setting DEFAULTs 67 Variations on INSERT 71 A punctuation problem 75 Unmatched single quotes 76 INSERT data with single quotes in it 77 It’s only up from here! 78 Your SQL toolbox 82 Martha’s Vineyard, MA, USA Budget: $1,500 Warm to cold weather Car for 6 hours including ferry ride Activities: Kayaking, Biking Attractions: Aquinnah Cliffs INSERT
Page
15
Table of contents xiii Searching for a destination 88 SELECT specific columns 92 Specify columns...and their order 93 An even better SELECT 97 WHERE to next? 98 WHERE filters out rows 102 Finding numeric values 106 Commenting code 107 Expanding a numeric search 108 Comparison operators 110 Finding numeric data with comparison operators 112 Comparison operators for text 115 Your SQL toolbox 120 Finding your information3 the SELECT statement Finders keepers? When it comes to databases, chances are you’ll need to retrieve your data more often than you’ll need to insert it. In this chapter, you’ll get an up-close look at the powerful SELECT statement and learn how to gain access to that important information you’ve been putting in your tables. You’ll even meet the WHERE clause, which will help you selectively get the data you need and avoid displaying the rows you don’t need. So what do you say, let’s get going and find some SQL data. Selecting specific columns is great, but there are still a lot of rows to sift through. I really just need places I can travel to by car. Can we narrow down the rows as well?
Page
16
Table of contents xiv Filtering rows Here’s your opportunity to dig in. You’ve already tried out WHERE for simple table row filters, but now you can perform an in-depth exploration of WHERE to see what it can really do. In this chapter, you’ll use AND to find rows that meet two or more requirements. You’ll switch to OR if you want rows that satisfy any of several conditions. And you will even unearth new operator artifacts to aid in your quest for missing items, ranges of values, or text patterns. So what are you waiting for? Turn the page and let the excavation begin. WHERE is your new best friend. better WHERE clauses 4 Misplaced identification 126 Multiple row requirements 127 Combining your queries 128 To be OR not to be 134 The difference between AND and OR 138 Use IS NULL to find NULLs 141 Selecting ranges using AND and comparison operators 143 Just BETWEEN us...there’s a better way 144 Save time with LIKE 148 I’d LIKE to buy a wildcard, please 149 You’re either IN... 153 ...or you are NOT IN 154 And that’s NOT all 155 WHERE for the win 160 Your SQL toolbox 162 WHERE country = 'USA' WHERE travel_mode = 'plane' AND
Page
17
Table of contents xv What’s for dinner? 166 Getting to know CRUD 171 Change your data with UPDATE 173 Updating multiple columns or rows 176 Revisiting CRUD 180 Getting rid of rows with DELETE 181 DELETE rules 182 DELETE (+SELECT) in your console 186 CRUD complete 188 Your SQL toolbox 190 Controlling your data5 CRUD operations Ready to have complete control over your data? The commands you’re about to learn will round out your knowledge, revealing you for the SQL powerhouse you truly are. You can already create any database you’d like, even one for nearby restaurants so you don’t have to keep those 39 takeout menus in your kitchen’s junk drawer anymore. You can add data about your favorite dives and diners and look up late-night joints that are open 24/7. But what happens if your local hangout changes its hours of operation? Or— horror—what if it closes all together and you need to remove it from your data? Not only does data need to be created, it also needs to be maintained by updating or deleting information when necessary. In this chapter, you’ll learn how to take full control of your database with all the necessary CRUD operations. CRUD is a good thing here, so let’s get CRUDy! C REATE D ELETE U PDATE R EAD
Page
18
Table of contents xvi Sorting and aggregating It’s time to take your SELECT to new heights. You already know how to SELECT data and use WHERE clauses. But sometimes your queries need a little more altitude than what SELECT and WHERE can achieve alone. In this chapter, you’ll learn how to sort your data in multiple ways. You’ll build mathematical calculations and aggregate values. And in CASE you need new categories, you’ll learn how to pull the rip cord with if-then-else logic for your own classifications. Make the SELECT jump and here we go! advanced SELECT 6 Shopping around 198 ORDER (BY) in the court! 199 ORDER with WHERE 200 Anatomy of ORDER BY 204 Reverse the ORDER with DESC 206 LIMIT the number of results 208 SUM to add values for us 210 COUNTing values 211 The AVG advantage 212 The COUNT of Monty Bristow 215 SELECT DISTINCT values 217 Your very own categorization 219 A CASE for new groups 220 Alias your columns with AS 224 A grateful and gloating mother 226 Your SQL toolbox 228 Neighborhoods, alphabetically A Z DataU Crud Row Querytown Index Junction Categories, alphabetically A Z bookstore boutique pet supplies music Names, alphabetically A Z I wonder how many Dataville business owners there are...
Page
19
Table of contents xvii 7 Group aggregates ASAP 234 SUM with WHERE 235 SUM all of them at once with GROUP BY 236 Imagine GROUP BY splitting your data 237 Sorting your groups 238 Getting group averages 241 MIN and MAX 242 Filtering groups 245 HAVING the right filter mechanism 246 Easy as S.F.W.G.H.O. 250 AS-thetically yours 251 An impressive list of abilities 254 Your SQL toolbox 256 Summarizing categories data groups Ready to host your own groupings? You should be feeling pretty confident with your ability to dish up SQL data by now. We think you’re ready to work the room and welcome a new guest to your queries: the GROUP BY clause. This chapter covers techniques for building and analyzing groups of table data. And if those groups must meet certain criteria to make it onto your RSVP list, there’s always HAVING to filter your group results. We’ll even teach you a classic mnemonic to be sure the clauses at your get- together take a seat in their assigned SQL order. The table’s set, the data’s ready, and we’ve sent the group invites—come on in. category employees bookstore 8 bookstore 12 bookstore 5 bookstore 3 bookstore 7 category employees boutique 3 boutique 4 boutique 6 category employees car repair 10 car repair 18 car repair 15 category employees grocery 35 grocery 8 grocery 10 grocery 25category employees hair salon 10 hair salon 7 hair salon 7category employees hardware 14 hardware 26 category employees music 19 music 6 category employees pet supplies 9 pet supplies 9 pet supplies 7 Think about SQL splitting up your rows–one group for each category–before computing the employee sums. 35 bookstore employees 40 43 13 78 25 music employees 24 25
Page
20
Table of contents xviii 8 Thoughtful table design Calling all architects and designers. You’ve been constructing tables without giving them much thought. And that’s fine, they work. You can do all the CRUD operations on them and write SELECT statements that are as elaborate as necessary. But as you get more data, you’ll start seeing things you wish you’d done to make your WHERE clauses simpler. Or perhaps your single table just isn’t big enough anymore, and you need to renovate your floor plans a bit. As your data becomes more complex, the KEY is to make your tables atomic and divide your data into multiple related tables. Who knows? Maybe your optimal blueprints result in plans for an entire skyscraper. Read on to find out. keys and data relationships Do you know the state of San Jose? 262 Naturally occurring primary keys 265 Primary key to success 266 The CREATE TABLE with a PRIMARY KEY 269 1, 2, 3...automatically 270 Adding a PRIMARY KEY to an existing table 273 Searching for adventure 275 A table is all about relationships 276 Atomic data 278 Aggravating activities and attractions 282 Abby’s database schema 283 Going from one table to two 284 FOREIGN KEY to success 285 Constraining your foreign key 286 CREATE a table with a FOREIGN KEY 288 A many-to-many relationship 291 We need a junction table 292 Other table relationships 293 Your SQL toolbox 300 locations location_id city state country budget weather travel_mode travel_hours attractions activities act_id activity loc_id