Page
1
(This page has no text content)
Page
2
Apress Pocket Guides Apress Pocket Guides present concise summaries of cutting-edge developments and working practices throughout the tech industry. Shorter in length, books in this series aims to deliver quick-to-read guides that are easy to absorb, perfect for the time-poor professional. This series covers the full spectrum of topics relevant to the modern industry, from security, AI, machine learning, cloud computing, web development, product design, to programming techniques and business topics too. Typical topics might include: A concise guide to a particular topic, method, function or framework Professional best practices and industry trends A snapshot of a hot or emerging topic Industry case studies Concise presentations of core concepts suited for students and those interested in entering the tech industry Short reference guides outlining ‘need-to-know’ concepts and practices. More information about this series at https://link.springer.com/bookseries/17385.
Page
3
Bhumika Shah and Devtosh Dubey SQL in a Week A Fast-Track Guide to Writing and Optimizing Queries Like a Pro
Page
4
Bhumika Shah Milford, USA Devtosh Dubey Milford, USA ISSN 3004-927X e-ISSN 3004-9288 Apress Pocket Guides ISBN 979-8-8688-2101-1 e-ISBN 979-8-8688-2102-8 https://doi.org/10.1007/979-8-8688-2102-8 © Bhumika Shah and Devtosh Dubey 2026 This work is subject to copyright. All rights are solely and exclusively licensed by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. The use of general descriptive names, registered names, trademarks, service marks, etc. in this publication does not imply, even in the absence of a specific statement, that such names are exempt from the relevant protective laws and regulations and therefore free for general use. The publisher, the authors and the editors are safe to assume that the advice and information in this book are believed to be true and accurate at the date of publication. Neither the publisher nor the authors or the editors give a warranty, expressed or implied, with respect to the material contained herein or for any errors or omissions that may have been made. The
Page
5
publisher remains neutral with regard to jurisdictional claims in published maps and institutional affiliations. Distributed to the book trade worldwide by Springer Science+Business Media New York, 1 New York Plaza, New York, NY 10004. Phone 1-800- SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm. comwww. springeronline. com, or visit . Apress Media, LLC is a Delaware LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.This Apress imprint is published by the registered company APress Media, LLC, part of Springer Nature. The registered company address is: 1 New York Plaza, New York, NY 10004, U.S.A.
Page
6
This book is dedicated to the learners, the doers, and the curious. SQL challenged us, changed us, and we hope it empowers you, too.
Page
7
Introduction In today's data-driven world, the ability to speak SQL is no longer a niche skill—it's a career advantage. Whether you're a data analyst preparing for interviews, a product manager trying to pull reports from a database, or a VP who wants to challenge assumptions with evidence, this book is for you. You don't need a computer science degree. You don't need prior coding experience. You need a structured, step-by-step guide that gets you from beginner to confident in one week. Even in the age of AI, where tools can auto-generate queries, understanding how SQL works gives you a real edge. You'll be able to ask more thoughtful questions, validate results, and avoid being misled by automation. AI can suggest syntax, but you bring the context, the logic, and the decision-making power. As data professionals who have worked in high-pressure industries for years, cracked interviews at Amazon and Meta, and taught SQL to hundreds of graduate students and professionals, we authors know what works—and what doesn't. This book doesn't overload you with theory. It teaches what matters in the real world—from writing your first SELECT query to optimizing performance like a pro. Every chapter builds on the last, so you can practice, progress, and retain what you learn. At the end of every chapter, you'll find Key Takeaways highlighting concepts you learned that day, best practices of the day, common mistakes to avoid, and how each topic keeps you relevant in the AI era—because knowing how and why SQL works matters more than ever. By the end of seven days, you'll be able to read, write, and debug SQL confidently—whether in a strategy meeting, product design session, or tech interview. This book takes you on a journey toward data fluency. No jargon. No fluff. Just powerful, practical SQL. The chapters are concise and focused, designed to build a strong foundation for our readers. In 2026 and beyond, almost anyone with this foundational knowledge can leverage SQL to support informed business decisions. Over the next seven days, this book will help you move from beginner to confident SQL user—not just writing queries, but writing them correctly.
Page
8
Getting Started/First Steps Before you write your first line of SQL (Structured Query Language), let's understand what SQL is—and why it's one of the most valuable tools in the digital age. SQL is used to communicate with relational databases. Whether you're working in healthcare, marketing, finance, or tech, most data is stored in a relational database. SQL is the language used to retrieve, insert, update, and delete data. As humans use English to communicate with the world, you can use SQL to communicate with databases. SQL is Declarative, which means the user can state what they want (not how to get it). SQL is Universal, i.e., almost every major organization relies on SQL-based systems, and SQL is Powerful since you can explore millions of records with a few lines of SQL. SQL basic concepts and its role in relational databases will be explored in greater depth in Chapter 1 of this book, but think of a relational database as an organized digital filing cabinet. Inside are tables that store your data, like spreadsheets, but smarter. Each table has rows (records) and columns (fields). Example: A “Customers” table might have columns like “CustomerID,” “Name,” “Email,” and “Country,” and each row contains data for one customer. Relational databases like MySQL, PostgreSQL, SQL Server, and Oracle follow structured rules that allow data to be connected and queried efficiently. Key SQL Building Blocks Before you dive into querying, here are some basic concepts you'll work with throughout this book (see Figure 1): Tables: Store data in rows and columns. Rows: Represent a single record. Columns: Represent a specific type of information (e.g., name, date). Primary Key: A unique identifier for each row.
Page
9
Foreign Key: A field in one table that links to the primary key in another. Data Types: Define the type of data a column can hold (e.g., “INT,” “VARCHAR,” “DATE”). Schema: The blueprint of your database—how tables are structured and related. Relationships connect tables using keys—this allows data to stay organized and consistent (like how your lover needs the key to your heart to stay in the relationship). Figure 1 Schema—Database blueprint How SQL Fits into the Real World? You don't have to be a software developer to benefit from SQL. If you're Product Managers: Stop waiting on analysts. With basic SQL, you can query customer data yourself and make faster, data-driven decisions. Business Analysts:
Page
10
SQL is your core tool. It helps you clean, transform, and extract insights from data efficiently. VPs and Executives: Dashboards are great, but knowing simple SQL lets you verify numbers and dig deeper when speed matters. Students and Job Seekers: SQL is a must-have for any data role. Strong SQL skills can set you apart in interviews and on the job. What Readers Will Need to Follow Along? To start learning SQL with this book, you’ll need a simple and easy-to-use SQL environment—and that’s where SQLite comes in. SQLite is a free, beginner-friendly database tool that lets you practice SQL without any complex setup. To help you get started, this book comes with a step-by-step setup instruction guide. Just follow along to download and install the software from https://sqlitebrowser.org, choose the right version for your system (Windows or Mac), and complete the installation. With your tools ready, you’ll be all set to begin your SQL journey—no experience needed. You’ll need a curious mindset and willingness to experiment. This book will walk you through every step. Starting Sunday, let's build your foundation and prepare for your first real SQL query! Hang Tight! Your New Journey Begins To make this learning experience more relatable and engaging, imagine yourself as the newly appointed CEO of DataNova Corp—a fast-growing startup with a team of 10 employees spread across the globe. Your workforce includes developers, marketers, analysts, and support staff in cities like New York, London, Bangalore, and Tokyo. You've inherited a basic employee database containing names, departments, salaries, locations, and start dates. Your mission? Use SQL to uncover insights, drive intelligent business decisions, and confidently lead your company. Each chapter in this book builds upon this evolving story, starting today by helping you understand who's on your team.
Page
11
Setup Instructions: Getting Ready to Learn SQL To follow along with this book, you'll need a working SQL environment. We'll use SQLite—a free, powerful tool that's widely used in the industry. Step 1: Download and Install SQLite 1. For the purposes of this book, we will be working with the SQLite Database. 2. Go to https://sqlitebrowser.org, head to the download section in the top menu. 3. Download the package based on your PC (Mac, Windows). 4. Run the software, and the installation process should go smoothly. Note You may also need SQL Server Express Edition if no database engine is currently installed on your system. It's also free and available on the Microsoft website. Step 2: Open DB Browser and Create Your Own Database 1. Launch DB Browser for SQLite. 2. Click New Database. Choose a location on your computer where you want to create the Database. Give your Database a name in the Save As field (mysqlweek). Step 3: Create Required Tables and Seed Data Once you hit save, a dialog box opens prompting you to create a table.
Page
12
"X" out the dialog box and run the following commands individually by pressing Cmd or Ctrl plus the Enter key. Run the following SQL script to set up all the required tables and insert basic sample data: -- CREATE TABLES -- 1. Employees Table (uses DepartmentID now) CREATE TABLE Employees ( EmployeeID INT PRIMARY KEY, FirstName VARCHAR(50), LastName VARCHAR(50), DepartmentID INT, Salary DECIMAL(10,2), Location VARCHAR(50), HireDate DATE, FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID) -- 2. Departments Table CREATE TABLE Departments ( DepartmentID INT PRIMARY KEY, DepartmentName VARCHAR(50), Manager VARCHAR(50) -- 3. Projects Table CREATE TABLE Projects ( ProjectID INT PRIMARY KEY, ProjectName VARCHAR(100), DepartmentID INT, Budget DECIMAL(12,2), StartDate DATE, FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID)
Page
13
-- 4. Assignments Table (Many-to-Many) CREATE TABLE Assignments ( EmployeeID INT, ProjectID INT, Role VARCHAR(50), HoursPerWeek INT, PRIMARY KEY (EmployeeID, ProjectID), FOREIGN KEY (EmployeeID) REFERENCES Employees(EmployeeID), FOREIGN KEY (ProjectID) REFERENCES Projects(ProjectID) -- INSERTING DATA IN DEPARTMENTS TABLE INSERT INTO Departments (DepartmentID, DepartmentName, Manager) VALUES (1, 'Marketing', 'Laura Diaz'), (2, 'Engineering', 'Sam Patel'), (3, 'HR', 'Tina Chen'), (4, 'Support', 'Rajiv Nair'); --INSERTING DATA IN EMPLOYEES TABLE INSERT INTO Employees (EmployeeID, FirstName, LastName, DepartmentID, Salary, Location, HireDate) VALUES (1, 'Alice', 'Johnson', 1, 72000.00, 'New York', '2021-04-01'), (2, 'Bob', 'Lee', 2, 95000.00, 'San Francisco', '2020-01-15'), (3, 'Carlos', 'Ramirez', 3, 65000.00, 'London', '2019-09-30'),
Page
14
(4, 'Diana', 'Wang', 4, 60000.00, 'Bangalore', '2022-06-10'), (5, 'Ethan', 'Kim', 2, 98000.00, 'Seoul', '2018-11-12'), (6, 'Fiona', 'Davis', 1, 71000.00, 'New York', '2022-02-01'), (7, 'George', 'Clark', 2, 105000.00, 'San Francisco', '2017-03-20'), (8, 'Hannah', 'Zhang', 3, 67000.00, 'London', '2020-07-18'), (9, 'Ivan', 'Petrov', 4, 59000.00, 'Bangalore', '2021-10-25'), (10,'Jenny', 'Nguyen', 2, 97000.00, 'Tokyo', '2019-12-03'); --INSERTING DATA IN Projects TABLE INSERT INTO Projects (ProjectID, ProjectName, DepartmentID, Budget, StartDate) VALUES (101, 'Brand Redesign', 1, 150000.00, '2023-01-01'), (102, 'AI Chatbot', 2, 300000.00, '2022-07-15'), (103, 'Recruitment Drive', 3, 80000.00, '2022-11-20'), (104, 'Helpdesk Upgrade', 4, 60000.00, '2023-04-10'), (105, 'Product Launch', 1, 200000.00, '2023-05-01'), (106, 'Cloud Migration', 2, 400000.00, '2021-09-10'), (107, 'Employee Onboarding', 3, 95000.00, '2022-03-15'), (108, 'Ticket System Revamp', 4, 75000.00, '2023-06-01');
Page
15
-- Assignments INSERT INTO Assignments (EmployeeID, ProjectID, Role, HoursPerWeek) VALUES (1, 101, 'Coordinator', 10), (2, 102, 'Developer', 20), (3, 103, 'HR Lead', 15), (4, 104, 'Support Agent', 25), (5, 102, 'AI Engineer', 30), (6, 105, 'Marketing Analyst', 12), (7, 106, 'Cloud Architect', 25), (8, 107, 'Trainer', 18), (9, 108, 'IT Support', 20), (10, 106, 'DevOps Engineer', 28), (1, 105, 'Content Creator', 10), (2, 106, 'Lead Engineer', 15); -- Create Table Timesheets CREATE TABLE Timesheets ( EmployeeID INT NOT NULL, ProjectID INT NOT NULL, WeekStart DATE NOT NULL, Hours DECIMAL(5, 2) NOT NULL, FOREIGN KEY (EmployeeID) REFERENCES Employees(EmployeeID) -- Insert Values in Timesheets table INSERT INTO Timesheets (EmployeeID, ProjectID, WeekStart, Hours) VALUES (1, 101, '2023-06-05', 10), (1, 105, '2023-06-05', 12), (2, 102, '2023-06-05', 18), (2, 106, '2023-06-05', 15), (5, 102, '2023-06-05', 30), (7, 106, '2023-06-05', 22), (10, 106, '2023-06-05', 25),
Page
16
(9, 108, '2023-06-05', 20), (1, 101, '2023-06-12', 8), (1, 105, '2023-06-12', 10), (2, 102, '2023-06-12', 20), (2, 106, '2023-06-12', 12), (5, 102, '2023-06-12', 28), (7, 106, '2023-06-12', 25), (10, 106, '2023-06-12', 28), (9, 108, '2023-06-12', 18); --- Create Table SalaryChanges CREATE TABLE SalaryChanges ( EmployeeID INT NOT NULL, EffectiveDate DATE NOT NULL, NewSalary DECIMAL(10, 2) NOT NULL, FOREIGN KEY (EmployeeID) REFERENCES Employees(EmployeeID) INSERT INTO SalaryChanges (EmployeeID, EffectiveDate, NewSalary) -- Insert Values into SalaryChanges VALUES (1, '2022-01-01', 68000.00), (1, '2023-04-01', 72000.00), (2, '2020-01-15', 90000.00), (2, '2022-08-01', 95000.00), (5, '2019-11-12', 92000.00), (5, '2022-05-01', 98000.00), (7, '2018-01-01', 99000.00), (7, '2021-03-01', 105000.00); You’re Ready! Your Database is now set up and populated with realistic data to support all seven days of SQL week learning. You can also view the tables by navigating to the Database Structure Tab, and make sure to refresh the
Page
17
Database to view the tables you just created. Happy coding!!!! Let's dive into Sunday!
Page
18
Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub. For more detailed information, please visit https:// www. apress. com/ gp/ services/ source-code.
Page
19
Acknowledgments This book would not have been possible without the patience, encouragement, and belief of the people around us. To the students and professionals who trusted us with their SQL questions, thank you for being the spark behind this project. Your curiosity showed us where learning gets hard and reminded us why making it easier matters. We are especially grateful to the learners and professionals who shared their SQL frustrations and successes with us over the years. Their experiences shaped the examples, scenarios, and teaching approach within these pages. We owe a special debt of gratitude to our parents, Mr. Raj Kumar Shah, Mrs. Preety Shah, Dr. Monika Dubey, and Dr. Ashutosh Kumar Dubey, for their love, belief, and unwavering support throughout this journey. Thank you for giving us the confidence to build, to teach, and to complete work we are truly proud of.
Page
20
Table of Contents Chapter 1: Sunday: Introduction to SQL—The Language of Data What Is SQL, and Why Is It So Important? Understanding Relational Databases Setting Up Your SQL Environment Your First SQL Query SQL Data Types Why Are Data Types Important? The Role of Size in Data Types Common SQL Data Types Key Takeaways Concepts You Learned Today Best Practice of the Day Common Mistakes to Avoid SQL in the Age of AI—Understanding Databases and SQL Chapter 2: Monday: Querying Data—Retrieving What You Need by Filtering and Sorting Monday at DataNova Corp: Starting to Ask Smart Questions SELECT: Choosing Specific Columns WHERE: Filtering Your Results SQL Operators Logical Operators: AND, OR, NOT ORDER BY: Sorting Your Data How to Write Comments in SQL