SQL Beginner Notes

Cover
Loading handbook...

Opening SQL Master 3D Handbook...

SQL MASTER 3D HANDBOOK BEGINNER SERIES

SQL Beginner Notes

Complete Interactive 3D Handbook

A curated step-by-step reference covering essential SQL querying syntax, relational database fundamentals, filtering logic, and aggregate analytics.

17 Chapters Β· All-in-One Book
TABLE OF CONTENTS

Part 1: Core Fundamentals

Ch 01–09 Β· Foundations & Filtering

01
SQL Introduction Understand what a database is, why SQL is the…
Pg 4
02
Database, Table, Row and Column Explore schemas, tables, rows, columns, data …
Pg 11
03
SELECT Master the primary command used to retrieve, …
Pg 18
04
FROM Specify the data source, use schema qualifica…
Pg 26
05
WHERE Filter rows with precision using conditions, …
Pg 31
06
Comparison Operators Compare values with equal, not equal, greater…
Pg 38
07
AND / OR / NOT Combine multiple search filters together to f…
Pg 45
08
IN Test whether a column value matches any item …
Pg 53
09
BETWEEN Filter records within an inclusive lower and …
Pg 59
TABLE OF CONTENTS

Part 2: Advanced Topics & Aggregates

Ch 10–17 Β· Conditions & Summaries

10
LIKE Search for specific text patterns and partial…
Pg 65
11
DISTINCT Eliminate duplicate values from your query re…
Pg 72
12
ORDER BY Sort query results in ascending or descending…
Pg 78
13
LIMIT Restrict the maximum number of rows returned …
Pg 85
14
Aggregate Functions Perform mathematical calculations across mult…
Pg 91
15
GROUP BY Group rows that share identical values into s…
Pg 99
16
HAVING Filter grouped summary rows based on aggregat…
Pg 106
17
CREATE DATABASE, CREATE TABLE, ALTER and MODIFY TABLE Master Data Definition Language (DDL) to crea…
Pg 112
CHAPTER {{ n.chapter_number|stringformat:"02d" }} 6 Parts

SQL Introduction

{{ n.short_description|default:"Essential SQL syntax rules, practical queries, step-by-step explanations, and best practices." }}

Topics in this chapter:
  • 1 What is a Database?
  • 2 What is SQL?
  • 3 Why Learn SQL?
  • 4 The Four Main SQL Operations: CRUD
  • 5 Where is SQL Used in Real Life?
  • 6 How to Read a SQL Query + Recap
CH 01 What is a Database?
Part 1 of 6

What is a Database?

A database is an organized electronic collection of structured information stored securely in a computer system. Unlike a plain text document, a database allows thousands of people to search, add, and update records at the exact same moment without corrupting the files. Modern software applications rely on databases to keep user accounts, banking balances, and inventory safe and organized.

Key Points
βœ“ Databases store massive amounts of structured information reliably and safely.
βœ“ They allow lightning-fast searches even when tables hold millions of records.
βœ“ Multiple authorized users can access and modify records at the same time.
βœ“ Relational databases organize related data into interconnected rectangular tables.
βœ“ Popular relational database management systems include MySQL, PostgreSQL, and SQLite.
Real-Life Example
Think of a database like a giant digital filing cabinet in a doctor's office. Each drawer represents a specific category such as Patients, Appointments, and Bills. Instead of flipping through paper folders by hand, the computerized cabinet retrieves the exact patient record you need in a fraction of a second.
Remember / Pro Tip
A database is the overall storage warehouse, while individual tables inside it hold the actual rows of data.
SQL Master Β· Beginner Series Pg 5
CH 01 What is SQL?
Part 2 of 6

What is SQL?

SQL stands for Structured Query Language. It is used to communicate with relational databases to retrieve, insert, update, and delete data.

Key Points
βœ“ SQL is pronounced as S-Q-L or Sequel.
βœ“ It is a standard language used with relational databases.
βœ“ SQL tells the database what information we need.
βœ“ It works with databases like MySQL, PostgreSQL, and Oracle.
βœ“ It is useful for websites, applications, and reports.
Real-Life Example
Imagine asking a bakery worker for three chocolate muffins. You tell them what you want, and they find the muffins for you.

SQL works similarly. You request specific information, and the database returns it
Remember / Pro Tip
SQL communicates with databases. It helps us manage and retrieve data, but it is not used to design user interfaces.
SQL Example
-- Simple SQL query asking the database for all employee records
SELECT *
FROM employees;

-- Output: Returns all 8 rows and all columns from the employees table
SQL Master Β· Beginner Series Pg 6
CH 01 Why Learn SQL?
Part 3 of 6

Why Learn SQL?

Spreadsheets like Microsoft Excel work wonderfully for small personal budgets, but they slow down and crash when tracking millions of records. Furthermore, spreadsheets struggle when hundreds of customers try to buy products simultaneously on an online store. SQL was specifically engineered to handle gigantic datasets, guarantee data accuracy, and coordinate multi-user web traffic seamlessly.

Key Points
βœ“ Blazing query speeds across tables holding millions or billions of rows.
βœ“ Strict relationship rules prevent duplicate accounts and accidental record deletion.
βœ“ Multi-user security controls ensure only authorized employees can view sensitive pay rates.
βœ“ SQL integrates directly into programming languages like Python, JavaScript, Java, and C#.
βœ“ It is the primary skill demanded by employers for data analysts, software engineers, and product managers.
Real-Life Example
Excel is like a friendly personal bicycle that is great for riding to the neighborhood corner store. SQL is like a high-speed electric cargo train designed to move thousands of heavy shipping containers across the country every single day without breaking down.
Remember / Pro Tip
Learning SQL gives you direct access to the truth behind any company's business data without waiting on manual reports.
SQL Example
-- Query calculating total payroll across departments in milliseconds
SELECT department, SUM(salary) AS total_payroll
FROM employees
GROUP BY department;

-- Output: Instant summary of payroll costs grouped by department
SQL Master Β· Beginner Series Pg 7
CH 01 The Four Main SQL Operations: CRUD
Part 4 of 6

The Four Main SQL Operations: CRUD

Nearly every database interaction in the world fits into four foundational operations known by the acronym CRUD: Create, Read, Update, and Delete. In SQL, these four actions are powered by the core statements INSERT, SELECT, UPDATE, and DELETE. Throughout this beginner handbook, our primary focus is the 'Read' operation using SELECT, which forms roughly 80% of everyday SQL work.

Key Points
βœ“ Create (INSERT): Adds brand new rows of data into a database table.
βœ“ Read (SELECT): Retrieves and displays existing data matching your request without altering it.
βœ“ Update (UPDATE): Modifies existing values inside specific rows in place.
βœ“ Delete (DELETE): Permanently removes unwanted rows from a table.
βœ“ Reading data with SELECT is completely non-destructive and safe to practice.
Real-Life Example
When you join a social media app, you Create your profile. When you scroll through your feed, the app Reads posts with SELECT. When you change your profile photo, it Updates your record. When you remove an old story, it Deletes that row.
Remember / Pro Tip
SELECT queries only inspect and display data; they never modify, overwrite, or destroy your original table records.
SQL Example
-- 1. Create (Insert a new row)
INSERT INTO employees (id, name, department, salary, city)
VALUES (9, 'Ian Malcolm', 'IT', 74000, 'Austin');

-- 2. Read (Retrieve rows)
SELECT name, salary FROM employees WHERE department = 'IT';

-- 3. Update (Modify existing row)
UPDATE employees SET salary = 78000 WHERE id = 1;

-- 4. Delete (Remove a row)
DELETE FROM employees WHERE id = 9;
SQL Master Β· Beginner Series Pg 8
CH 01 Where is SQL Used in Real Life?
Part 5 of 6

Where is SQL Used in Real Life?

SQL powers the digital backbone of virtually every major industry, web service, and smartphone application you use every single day. From e-commerce checkouts and mobile banking to hospital patient records and airline reservations, relational databases store the critical transactions that keep the modern world operating smoothly.

Key Points
βœ“ E-Commerce (Amazon, Shopify): Manages product catalogs, customer shopping carts, and order shipments.
βœ“ Banking & Finance: Tracks account balances, ATM withdrawals, and fraud detection logs with strict accuracy.
βœ“ Healthcare & Hospitals: Stores patient histories, prescription schedules, and doctor appointment slots.
βœ“ Social Media & Streaming (Netflix, Spotify): Tracks user watch histories, music playlists, and subscriber accounts.
βœ“ Top Database Systems: MySQL, PostgreSQL, Microsoft SQL Server, Oracle Database, and SQLite.
Real-Life Example
When you search for 'wireless headphones' on a shopping app, a SQL query runs behind the scenes. It filters inventory tables for matching products, checks if items are in stock in your nearest warehouse, and sorts them by customer rating in under twenty milliseconds.
Remember / Pro Tip
Regardless of whether a company uses MySQL, PostgreSQL, or SQL Server, standard SQL querying syntax remains nearly identical.
SQL Master Β· Beginner Series Pg 9
CH 01 How to Read a SQL Query + Recap
Part 6 of 6

How to Read a SQL Query + Recap

Reading SQL code is easy because it is intentionally written to mirror natural English sentences. A standard query is composed of clauses introduced by reserved keywords like SELECT, FROM, and WHERE. By understanding keywords, line formatting, comments, and the ending semicolon, you will be able to read and debug SQL statements with total confidence.

Key Points
βœ“ Keywords (SELECT, FROM, WHERE) are reserved words written in ALL CAPS by convention.
βœ“ Whitespace, tabs, and line breaks do not alter execution, so indent your code cleanly.
βœ“ SQL statements conventionally conclude with a terminating semicolon (;).
βœ“ Code comments begin with two hyphens (--) and are ignored by the database engine.
βœ“ Identifiers are the custom names of tables and columns you created.
Real-Life Example
Reading a SQL query is like reading an instructional recipe card: 'TAKE the name and salary columns FROM the employees binder WHERE the city is New York.' The structure is logical, direct, and unambiguous.
Remember / Pro Tip
Always write SQL keywords in UPPERCASE and column names in lowercase so your code is easy for teammates to scan.
SQL Example
-- Chapter 1 Mastery Query: Reading structure step by step
SELECT name, department, salary   -- 1. Which columns to retrieve
FROM employees                    -- 2. Which table to inspect
WHERE city = 'New York';          -- 3. What filtering condition to apply

-- Output:
-- name           | department | salary
-- Charlie Brown  | Sales      | 61000
-- Alice Martin   | IT         | 75000
SQL Master Β· Beginner Series Pg 10
CHAPTER {{ n.chapter_number|stringformat:"02d" }} 6 Parts

Database, Table, Row and Column

{{ n.short_description|default:"Essential SQL syntax rules, practical queries, step-by-step explanations, and best practices." }}

Topics in this chapter:
  • 1 Database = Storage Box
  • 2 What is a Table?
  • 3 Rows and Columns
  • 4 Our Sample Table: employees
  • 5 Data Types in Simple Words
  • 6 Primary Key + Recap
CH 02 Database = Storage Box
Part 1 of 6

Database = Storage Box

In relational systems, a database acts as the master container that holds all related tables, views, and security permissions for an entire project. A single database server can host multiple independent databases, keeping your company's Human Resources records completely separated from your Customer Orders.

Key Points
βœ“ A database is the highest-level named storage container on a database server.
βœ“ It groups all related tables belonging to a single software application or company department.
βœ“ Databases provide security isolation: users can be granted access to one database while blocked from others.
βœ“ You tell the database server which storage box to work inside using the USE command.
βœ“ Listing available databases on a server is done with the SHOW DATABASES command.
Real-Life Example
Think of a database like a large labeled storage plastic bin in an office archive. One storage bin is labeled 'Payroll System 2026' and another is labeled 'Customer Support'. Keeping tables inside distinct bins prevents files from getting mixed up.
Remember / Pro Tip
Before running any table query on a newly opened database server, make sure you activate the right database with USE database_name;.
SQL Example
-- 1. View all databases on the current server
SHOW DATABASES;

-- 2. Select the specific database you want to work with
USE company_db;

-- 3. Confirm which database is currently active
SELECT DATABASE();
SQL Master Β· Beginner Series Pg 12
CH 02 What is a Table?
Part 2 of 6

What is a Table?

A table is a structured, two-dimensional grid composed of vertical columns and horizontal rows that stores information about one specific subject. In relational database architecture, each table represents a distinct real-world entity such as employees, customers, products, or invoices. Keeping subjects separated into dedicated tables prevents messy duplicate records.

Key Points
βœ“ A table is a two-dimensional grid consisting of columns (vertical) and rows (horizontal).
βœ“ Each table models one distinct business entity (e.g., an 'employees' table should only hold employee data).
βœ“ Table names should generally be descriptive, lowercase, and plural by convention (e.g., 'employees', 'orders').
βœ“ Every table has a fixed schema: its column names and data types are defined before data is added.
βœ“ You inspect a table's structural blueprint using the DESCRIBE or EXPLAIN command.
Real-Life Example
Imagine an Excel workbook with multiple tabs along the bottom. One tab is named 'Employees', another tab is named 'Offices', and a third is named 'Projects'. In SQL, each of those separate tabbed sheets is called a table.
Remember / Pro Tip
Never combine unrelated business entities into one giant table; keep employees and departmental budgets in separate, clean tables.
SQL Example
-- Inspect the column structure and data types of our employees table
DESCRIBE employees;

-- Output shows: Field, Type, Null, Key, Default, Extra
-- id         | int          | NO   | PRI | NULL    | auto_increment
-- name       | varchar(100) | NO   |     | NULL    |
-- department | varchar(50)  | NO   |     | NULL    |
-- salary     | decimal(10,2)| NO   |     | NULL    |
-- city       | varchar(50)  | NO   |     | NULL    |
SQL Master Β· Beginner Series Pg 13
CH 02 Rows and Columns
Part 3 of 6

Rows and Columns

Understanding the difference between rows and columns is the fundamental secret to mastering SQL. A column represents a vertical attribute or property of the entity, such as 'salary' or 'city'. A row represents a complete single horizontal record belonging to one specific individual or transaction.

Key Points
βœ“ Column (Field / Attribute): Vertical slice storing one specific characteristic with a strict data type.
βœ“ Row (Record / Tuple): Horizontal slice representing one complete individual instance of the entity.
βœ“ Every row in a table contains the exact same columns, though some column values may be left empty (NULL).
βœ“ Adding a new employee creates a new horizontal row; adding a new feature creates a new vertical column.
βœ“ Tables grow vertically by thousands of rows every day, while columns stay relatively constant.
Real-Life Example
Consider a school student ID card. The labels printed on the cardβ€”'Student Name', 'Grade Level', and 'Emergency Phone'β€”are the columns. Your personal physical card with your specific photo and name filled in represents a single row.
Remember / Pro Tip
Columns define the questions you can ask ('What is the salary?'), while rows contain the actual answers for each record.
SQL Example
-- Selecting vertical columns:
SELECT name, department FROM employees;

-- Filtering for a single horizontal row:
SELECT * FROM employees WHERE id = 1;

-- Output: Returns the complete row for employee #1 (Alice Martin)
SQL Master Β· Beginner Series Pg 14
CH 02 Our Sample Table: employees
Part 4 of 6

Our Sample Table: employees

Throughout this entire handbook, we will practice every single SQL query against one clean, realistic sample table named 'employees'. By using the exact same eight employee records in all chapters, you will always know what data to expect, making it effortless to see how filtering, sorting, and grouping change your query results.

Key Points
βœ“ Table Name: employees
βœ“ Columns: id (integer), name (text), department (text), salary (numeric money), city (text).
βœ“ Sample Rows: Covering four departments (IT, HR, Sales, Finance) across four cities.
βœ“ Consistent Test Data: Allows you to verify query outputs and calculations instantly in your head.
βœ“ Practice Friendly: Designed to clearly demonstrate matching conditions, nulls, groupings, and salary maths.
Real-Life Example
Imagine you are the office manager of a modern technology company with branches in New York, Chicago, Austin, and Miami. The 'employees' table is your master staff roster where you track who works in which office and what they earn.
Remember / Pro Tip
Keep these eight employee rows in mind as you read; every example in later chapters builds directly on this dataset.
SQL Example
-- Our Canonical 8-Row employees Dataset:
-- id | name             | department | salary   | city
-- 1  | Alice Martin     | IT         | 75000.00 | New York
-- 2  | Bob Smith        | HR         | 52000.00 | Chicago
-- 3  | Charlie Brown    | Sales      | 61000.00 | New York
-- 4  | Diana Prince     | IT         | 82000.00 | Austin
-- 5  | Evan Wright      | Finance    | 68000.00 | Chicago
-- 6  | Fiona Gallagher  | Sales      | 59000.00 | Miami
-- 7  | George Clark     | HR         | 48000.00 | Austin
-- 8  | Hannah Abbott    | IT         | 71000.00 | Miami

SELECT * FROM employees;
SQL Master Β· Beginner Series Pg 15
CH 02 Data Types in Simple Words
Part 5 of 6

Data Types in Simple Words

Every column in a database table must be assigned a data type when the table is created. A data type is a strict rule that tells the database what kind of information is permitted in that column, such as whole numbers, text words, calendar dates, or decimal currency. Data types prevent bugs, enforce accuracy, and optimize disk storage.

Key Points
βœ“ INT / INTEGER: Whole numbers without decimals (e.g., employee IDs, ages, quantities).
βœ“ VARCHAR(n): Variable-length text strings up to 'n' characters (e.g., names, email addresses, cities).
βœ“ DECIMAL(p, s): Precise numerical values with decimals, ideal for money and financial balances.
βœ“ DATE: Calendar dates formatted strictly as 'YYYY-MM-DD' (e.g., hire dates, birthdays).
βœ“ The database rejects queries that attempt to store text inside an integer or date column.
Real-Life Example
Think of data types like the coin sorter tray in a cash register. The slot for dollar bills is sized for paper, while the slot for quarters only fits metal coins. You cannot force a paper bill into the coin slot; the system physically prevents invalid entries.
Remember / Pro Tip
Always use DECIMAL for currency and monetary salaries; never use floating-point types which suffer from rounding errors.
SQL Example
-- Demonstration of data types in the employees table schema:
-- id         -> INT             (e.g., 1, 2, 3)
-- name       -> VARCHAR(100)    (e.g., 'Alice Martin')
-- department -> VARCHAR(50)     (e.g., 'IT', 'Sales')
-- salary     -> DECIMAL(10, 2)  (e.g., 75000.00)
-- city       -> VARCHAR(50)     (e.g., 'New York')

SELECT id, name, salary
FROM employees
WHERE salary > 60000;
SQL Master Β· Beginner Series Pg 16
CH 02 Primary Key + Recap
Part 6 of 6

Primary Key + Recap

A Primary Key is a designated column (or set of columns) that guarantees every single row in a table is uniquely identifiable. Even if a company hires two distinct workers who share the exact same first and last name, their unique Primary Key ID values ensure the payroll system never mixes up their paycheck deposits or tax deductions.

Key Points
βœ“ Uniqueness: Every value in a Primary Key column must be completely unique across the table.
βœ“ Non-Null: A Primary Key can never be empty or NULL.
βœ“ Single Identity: A table can have only one Primary Key constraint defined.
βœ“ In our 'employees' table, the 'id' column serves as the Primary Key.
βœ“ Databases often automatically increment primary key IDs (1, 2, 3...) when new rows are added.
Real-Life Example
A Primary Key is just like a government Passport Number, a driver's license number, or a student ID. Two students at your school might both be named 'Michael Johnson', but their unique ID numbers ensure grades are entered on the right report card.
Remember / Pro Tip
Every production database table should have a Primary Key; it is the cornerstone of relational integrity.
SQL Example
-- Looking up an employee record by their unique Primary Key ID
SELECT *
FROM employees
WHERE id = 4;

-- Output:
-- id: 4 | name: Diana Prince | department: IT | salary: 82000.00 | city: Austin

-- Recap Practice: Try finding employee #7
SELECT name, department FROM employees WHERE id = 7;
-- Answer: George Clark | HR
SQL Master Β· Beginner Series Pg 17
CHAPTER {{ n.chapter_number|stringformat:"02d" }} 7 Parts

SELECT

{{ n.short_description|default:"Essential SQL syntax rules, practical queries, step-by-step explanations, and best practices." }}

Topics in this chapter:
  • 1 What does SELECT do?
  • 2 SELECT Syntax
  • 3 Select All Columns (*)
  • 4 Select Specific Columns
  • 5 Column Aliases (AS)
  • 6 Simple Calculations in SELECT
  • 7 Mistakes + Recap and Practice
CH 03 What does SELECT do?
Part 1 of 7

What does SELECT do?

The SELECT statement is the most essential and frequently executed keyword in the entire SQL language. It instructs the database engine: 'Here are the specific columns, calculated formulas, and rows I would like you to retrieve and present on my screen.' When querying databases for analytics, web pages, or reports, your work virtually always begins with SELECT.

Key Points
βœ“ SELECT retrieves and reads existing data from database tables.
βœ“ It is a completely non-destructive command: running a SELECT query never changes or deletes records.
βœ“ You can select existing table columns, mathematical computations, or static text labels.
βœ“ The output of a SELECT query is returned as a clean temporary tabular result set.
βœ“ It is the first keyword written in standard SQL query statements.
Real-Life Example
Imagine walking into a library and asking the research assistant: 'Please bring me the title and author of the five newest history books.' The assistant retrieves the list and shows it to you on a sheet of paper without altering the actual books on the shelves.
Remember / Pro Tip
Because SELECT only reads data, beginners can experiment and practice queries freely without fear of breaking anything.
SQL Example
-- The most basic SELECT query
SELECT name
FROM employees;

-- Output: Returns the 8 employee names in order:
-- Alice Martin
-- Bob Smith
-- Charlie Brown
-- Diana Prince
-- Evan Wright
-- Fiona Gallagher
-- George Clark
-- Hannah Abbott
SQL Master Β· Beginner Series Pg 19
CH 03 SELECT Syntax
Part 2 of 7

SELECT Syntax

To write valid SQL queries, you must arrange your clauses in the specific structural order required by the database parser. A foundational SELECT query consists of the SELECT keyword followed by a comma-separated list of column names, followed by the FROM keyword, followed by the target table name, and ending with a semicolon.

Key Points
βœ“ Clause Order: SELECT column_list FROM table_name;
βœ“ Separate multiple column names with commas (e.g., name, department, salary).
βœ“ Never place a trailing comma after the final column name before the FROM keyword.
βœ“ Keywords are capitalized by developer convention for clean visual readability.
βœ“ Statements terminate with a semicolon (;) to indicate the completion of the command.
Real-Life Example
SQL syntax rules are like grammar rules in written language. In English, sentences start with a capital letter and end with a period. In SQL, queries start with an action keyword like SELECT and end with a semicolon.
Remember / Pro Tip
A missing comma between columns or an accidental comma right before FROM is the #1 syntax error beginners encounter.
SQL Example
-- Correct Syntax Pattern:
SELECT
    id,
    name,
    salary
FROM
    employees;

-- Output: A clean 3-column table showing id, name, and salary for all 8 rows
SQL Master Β· Beginner Series Pg 20
CH 03 Select All Columns (*)
Part 3 of 7

Select All Columns (*)

When you want to inspect every single column that exists in a table without typing out all column names individually, SQL provides the asterisk wildcard symbol (*). Writing 'SELECT *' instructs the database engine to retrieve all columns defined in the table schema in their default structural order.

Key Points
βœ“ The asterisk (*) represents 'all columns' in the target table.
βœ“ Extremely convenient for exploratory analysis, quick testing, and debugging.
βœ“ Production Best Practice Warning: Avoid 'SELECT *' in live web applications.
βœ“ Selecting unnecessary columns consumes excess server memory, bandwidth, and CPU time.
βœ“ Explicitly naming columns guarantees predictable application behavior even if table schemas change.
Real-Life Example
Using 'SELECT *' is like walking into a restaurant and telling the waiter: 'Bring me every single dish on the entire menu!' It is helpful when you want to see what the kitchen can make, but impractical when you only wanted a sandwich.
Remember / Pro Tip
Use SELECT * when exploring new datasets in your console, but name specific columns when writing production code.
SQL Example
-- Select all columns from our employees table
SELECT *
FROM employees;

-- Output: Returns all 5 columns (id, name, department, salary, city)
-- for all 8 rows in the table.
SQL Master Β· Beginner Series Pg 21
CH 03 Select Specific Columns
Part 4 of 7

Select Specific Columns

In real-world applications, you rarely need every piece of information stored in a table. Listing only the specific columns you need makes your queries dramatically faster, keeps your screen clean, and prevents confidential data like employee home addresses or internal IDs from being unnecessarily displayed.

Key Points
βœ“ Specify only the columns you want, separated by commas.
βœ“ The order in which you list columns in SELECT dictates their order in the query output.
βœ“ Reduces network data transfer between the database server and your frontend application.
βœ“ Helps keep reports focused on relevant metrics (e.g., just name and department).
βœ“ Column names must match the table schema spelling exactly.
Real-Life Example
When printing nametags for a company conference, the badge printer only needs each attendee's full name and department. Requesting their salary, home address, and emergency contact would clutter the badge and violate privacy.
Remember / Pro Tip
You can rearrange columns however you like: SELECT salary, name displays salary first, regardless of table design.
SQL Example
-- Requesting only the name and department columns
SELECT name, department
FROM employees;

-- Output:
-- name             | department
-- Alice Martin     | IT
-- Bob Smith        | HR
-- Charlie Brown    | Sales
-- Diana Prince     | IT
-- Evan Wright      | Finance
-- Fiona Gallagher  | Sales
-- George Clark     | HR
-- Hannah Abbott    | IT
SQL Master Β· Beginner Series Pg 22
CH 03 Column Aliases (AS)
Part 5 of 7

Column Aliases (AS)

By default, query results display the exact column names defined in the database table, which are often technical abbreviations like 'dept_id' or 'emp_sal'. Using the AS keyword, you can assign a temporary display nickname known as an alias to any column in your query output.

Key Points
βœ“ Syntax: SELECT column_name AS friendly_alias FROM table_name;
βœ“ Aliases only change the header label on the returned result; they never rename table columns permanently.
βœ“ If your alias contains spaces or special characters, wrap it in single or double quotes.
βœ“ The AS keyword is technically optional, but writing it explicitly is standard developer best practice.
βœ“ Essential for giving clear, readable labels to calculated formulas and mathematical expressions.
Real-Life Example
Imagine your official birth certificate lists your name as 'Alexander Robert Montgomery III'. In everyday casual conversation, you introduce yourself with the friendly nickname 'Alex'. An alias is simply a friendly nickname for report headers.
Remember / Pro Tip
Use aliases to make business reports look professional: 'annual_comp' is far easier for executives to understand than 'sal_calc_raw'.
SQL Example
-- Giving user-friendly labels to columns using AS
SELECT
    name AS employee_name,
    salary AS monthly_salary,
    city AS office_location
FROM employees;

-- Output headers:
-- employee_name | monthly_salary | office_location
SQL Master Β· Beginner Series Pg 23
CH 03 Simple Calculations in SELECT
Part 6 of 7

Simple Calculations in SELECT

The SELECT clause can perform arithmetic calculations directly on table numbers using standard mathematical operators: addition (+), subtraction (-), multiplication (*), and division (/). The database engine computes these operations row by row at ultra-fast speeds and displays the calculated results as new dynamic columns.

Key Points
βœ“ Operators supported: + (addition), - (subtraction), * (multiplication), / (division).
βœ“ Calculations do not alter stored table data; they are computed dynamically on the fly.
βœ“ Always assign an alias (AS) to calculated columns so they have clean header labels.
βœ“ You can calculate across columns (e.g., price * quantity) or combine columns with fixed constants.
βœ“ Standard order of operations (PEMDAS) applies: use parentheses to control precedence.
Real-Life Example
If you store monthly salaries in your database and leadership asks for an annual compensation report, you do not need to export data into Excel to multiply by 12. SQL calculates annual totals for all employees instantaneously.
Remember / Pro Tip
Wrap calculations in parentheses to avoid ambiguity and always provide an alias, like (salary * 12) AS annual_salary.
SQL Example
-- Calculating annual pay and a projected 10% holiday bonus
SELECT
    name,
    salary,
    (salary * 12) AS annual_salary,
    (salary * 0.10) AS holiday_bonus
FROM employees;

-- Output sample:
-- Alice Martin | 75000 | 900000 | 7500.00
-- Bob Smith    | 52000 | 624000 | 5200.00
SQL Master Β· Beginner Series Pg 24
CH 03 Mistakes + Recap and Practice
Part 7 of 7

Mistakes + Recap and Practice

Even experienced developers occasionally make minor syntax mistakes when writing SELECT statements. Learning to spot misplaced commas, misspelled column names, and forgotten keywords will save you hours of debugging frustration as you continue through this handbook.

Key Points
βœ“ Error 1: Trailing comma after the final column (SELECT name, salary, FROM employees; -> Remove the extra comma).
βœ“ Error 2: Misspelling a column name (Unknown column 'deparment' -> Check schema spelling).
βœ“ Error 3: Omitting the FROM clause entirely when requesting table columns.
βœ“ Error 4: Forgetting quotation marks when naming an alias with spaces.
βœ“ Recap: SELECT picks what to show; calculations work inline; aliases format the output.
Real-Life Example
Imagine writing a postal address and accidentally putting an extra comma after the postal code. The sorting machine stops and ejects the letter for manual review. SQL parsers are strict and stop on the exact character that violates syntax rules.
Remember / Pro Tip
When the database throws an error, read the line number and error message carefully; it usually pinpoints the exact typo.
SQL Example
-- WRONG: Trailing comma before FROM causes syntax error
-- SELECT name, department, FROM employees;

-- FIXED: Clean comma placement
SELECT name, department
FROM employees;

-- Mini Practice:
-- Q1: Select only name and city with alias 'home_city'.
-- Answer: SELECT name, city AS home_city FROM employees;

-- Q2: Show each employee's salary after a $500 monthly raise.
-- Answer: SELECT name, (salary + 500) AS new_salary FROM employees;
SQL Master Β· Beginner Series Pg 25
CHAPTER {{ n.chapter_number|stringformat:"02d" }} 4 Parts

FROM

{{ n.short_description|default:"Essential SQL syntax rules, practical queries, step-by-step explanations, and best practices." }}

Topics in this chapter:
  • 1 FROM Tells Where the Data Is
  • 2 FROM Syntax and Example
  • 3 Table Aliases
  • 4 Mistakes + Recap and Practice
CH 04 FROM Tells Where the Data Is
Part 1 of 4

FROM Tells Where the Data Is

The FROM clause specifies the exact table or data source from which the columns listed in the SELECT clause should be retrieved. While SELECT defines what attributes you want to view, FROM informs the database engine where those attributes live. A query cannot retrieve table data without a valid FROM clause.

Key Points
βœ“ The FROM clause establishes the primary data source for your query.
βœ“ It directly follows the column list of the SELECT statement.
βœ“ The database engine uses FROM to check whether the requested table exists in the schema.
βœ“ If any column in your SELECT list does not exist in the specified table, an error is raised.
βœ“ You can only query tables you have authorized permission to read.
Real-Life Example
If you ask an assistant to retrieve 'the sales records for July', their first question will be: 'Which binder should I pull those records from?' The FROM clause provides that exact answer by naming the target binder.
Remember / Pro Tip
Although written after SELECT, the database engine actually evaluates the FROM clause first to locate the data.
SQL Example
-- Basic FROM clause pointing directly to the employees table
SELECT name, department, salary
FROM employees;

-- Output: Successfully retrieves rows because 'employees' exists
-- and contains the columns name, department, and salary.
SQL Master Β· Beginner Series Pg 27
CH 04 FROM Syntax and Example
Part 2 of 4

FROM Syntax and Example

In larger corporate systems, multiple databases often live on the same physical server. When querying tables across schemas, you can specify the target table using full schema qualification with dot notation (database_name.table_name). This guarantees your query points to the correct table regardless of which database is currently active.

Key Points
βœ“ Standard Syntax: FROM table_name;
βœ“ Schema Qualified Syntax: FROM database_name.table_name;
βœ“ Dot notation explicitly routes the query to the proper database container.
βœ“ Useful in multi-tenant environments and scripts that span multiple company databases.
βœ“ Table names are case-sensitive on some operating systems (like Linux), so adhere to lowercase naming.
Real-Life Example
Imagine two people in your company named 'John Smith'β€”one works in the London office and one works in New York. Specifying 'london.employees' versus 'newyork.employees' ensures you pull data from the right branch office without ambiguity.
Remember / Pro Tip
If you are already inside your target database via USE company_db;, writing simply FROM employees; is sufficient.
SQL Example
-- 1. Standard FROM referencing current database
SELECT name, city
FROM employees;

-- 2. Fully qualified schema reference (database.table)
SELECT name, city
FROM company_db.employees;

-- Both queries return identical results when company_db is active.
SQL Master Β· Beginner Series Pg 28
CH 04 Table Aliases
Part 3 of 4

Table Aliases

Just as columns can be given display aliases, tables can be given short nickname aliases directly in the FROM clause. Table aliases save typing long table names repeatedly and are essential when writing multi-table queries and subqueries later in your SQL journey.

Key Points
βœ“ Syntax: FROM table_name AS alias_name OR simply FROM table_name alias_name.
βœ“ Convention: Developers typically use a single letter or short acronym (e.g., 'employees e' or 'emp e').
βœ“ Once defined in the FROM clause, you can prefix column names with the alias (e.g., e.name, e.salary).
βœ“ Table aliases improve code readability when queries become long and complex.
βœ“ Once assigned in FROM, you must use the alias throughout that query.
Real-Life Example
If you work at the 'International Business Machines Corporation', you and your colleagues simply say 'IBM' in conversation to save time. A table alias gives your table a quick, clean nickname for the duration of the query.
Remember / Pro Tip
Prefixing columns with table aliases (e.name) makes it immediately obvious to readers where each column originates.
SQL Example
-- Using table alias 'e' for the employees table
SELECT
    e.id,
    e.name,
    e.department,
    e.salary
FROM employees AS e;

-- Output: Returns the requested columns cleanly with alias prefixes
SQL Master Β· Beginner Series Pg 29
CH 04 Mistakes + Recap and Practice
Part 4 of 4

Mistakes + Recap and Practice

Errors in the FROM clause are typically caused by misspellings, querying tables that do not exist in the active database, or placing the FROM clause in the wrong grammatical order. Reviewing these common pitfalls will ensure your query foundations remain solid.

Key Points
βœ“ Error 1: Misspelling the table name (e.g., FROM employes; -> Table does not exist).
βœ“ Error 2: Putting FROM before SELECT (SQL requires SELECT first in written order).
βœ“ Error 3: Trying to query a table located in another database without switching or using dot notation.
βœ“ Error 4: Defining a table alias in FROM and then using the full original name inconsistently.
βœ“ Recap: FROM points to the data source; schema dot notation resolves ambiguity; aliases shorten code.
Real-Life Example
Trying to query a non-existent table is like sending mail to a street address that does not exist in the city directory. The postal worker cannot deliver the package and returns an 'address unknown' error notice.
Remember / Pro Tip
Always check which database you are connected to if SQL reports that your table cannot be found.
SQL Example
-- WRONG: Table name typo
-- SELECT name FROM employes;
-- Error: Table 'company_db.employes' doesn't exist

-- FIXED:
SELECT name FROM employees;

-- Mini Practice:
-- Q1: Write a query selecting name and salary using table alias 'emp'.
-- Answer: SELECT emp.name, emp.salary FROM employees AS emp;

-- Q2: Query all columns from employees using the schema prefix 'company_db'.
-- Answer: SELECT * FROM company_db.employees;
SQL Master Β· Beginner Series Pg 30
CHAPTER {{ n.chapter_number|stringformat:"02d" }} 6 Parts

WHERE

{{ n.short_description|default:"Essential SQL syntax rules, practical queries, step-by-step explanations, and best practices." }}

Topics in this chapter:
  • 1 What is WHERE?
  • 2 WHERE Syntax
  • 3 Filter Numbers
  • 4 Filter Text (quotes)
  • 5 Order of SELECT, FROM, WHERE
  • 6 Mistakes + Recap and Practice
CH 05 What is WHERE?
Part 1 of 6

What is WHERE?

The WHERE clause is SQL's primary filtering mechanism that allows you to extract only the specific rows that meet your criteria. Without WHERE, every query returns every single row in the table. By adding a WHERE condition, the database inspects each row individually and only keeps rows where your condition evaluates to TRUE.

Key Points
βœ“ The WHERE clause filters data row by row before results are sent back.
βœ“ It evaluates a condition for each row: if TRUE, the row is kept; if FALSE or NULL, it is dropped.
βœ“ Enables precise business questions: 'Which staff work in IT?' or 'Who earns over $70,000?'
βœ“ Prevents information overload by narrowing down massive tables to relevant subsets.
βœ“ Placed directly after the FROM clause in standard SQL statements.
Real-Life Example
Imagine a kitchen sieve or coffee filter. When you pour in liquid mixed with coffee grounds, the filter traps the grounds and allows only the pure liquid to pass into your cup. The WHERE clause acts as a sieve for your database rows.
Remember / Pro Tip
Without a WHERE clause, SQL will happily return all one million rows in a table; always filter your data!
SQL Example
-- Retrieve only employees located in Chicago
SELECT name, department, salary, city
FROM employees
WHERE city = 'Chicago';

-- Output:
-- Bob Smith   | HR      | 52000 | Chicago
-- Evan Wright | Finance | 68000 | Chicago
SQL Master Β· Beginner Series Pg 32
CH 05 WHERE Syntax
Part 2 of 6

WHERE Syntax

The WHERE clause follows a strict structural placement rule: it must appear immediately after the FROM clause. Writing WHERE before FROM or after ORDER BY breaks standard query grammar. A condition consists of a column name, a comparison operator, and the target comparison value.

Key Points
βœ“ Standard Structure: SELECT column_list FROM table_name WHERE condition;
βœ“ Condition Formula: [column] [comparison operator] [value]
βœ“ Examples of operators: =, !=, <>, >, <, >=, <=, LIKE, IN, BETWEEN.
βœ“ You can test numbers, text strings, dates, or computed expressions.
βœ“ Multiple conditions can be combined using logical operators like AND and OR.
Real-Life Example
Consider a building security guard checking visitor badges at the entrance door. The guard's instruction is: 'Allow entry WHERE visitor has a red badge.' The clause establishes the exact qualification criteria for passing through.
Remember / Pro Tip
Always verify the placement order: SELECT what you want, FROM which table, WHERE the condition holds true.
SQL Example
-- Syntax Pattern Demonstration
SELECT
    name,
    salary,
    department
FROM
    employees
WHERE
    department = 'IT';

-- Output: Returns the 3 IT staff members:
-- Alice Martin (75000), Diana Prince (82000), Hannah Abbott (71000)
SQL Master Β· Beginner Series Pg 33
CH 05 Filter Numbers
Part 3 of 6

Filter Numbers

When filtering numeric columns such as salaries, employee IDs, quantities, or ages, you write the numbers directly into your WHERE condition without quotes. Placing quotes around numbers is unnecessary and can confuse database index optimizers by forcing text conversions.

Key Points
βœ“ Numeric values must NEVER be wrapped in quotation marks (e.g., WHERE salary > 70000).
βœ“ Supported numeric comparisons: = (equals), > (greater than), < (less than), >=, <=, !=.
βœ“ Numbers with decimals are written with standard decimal points (e.g., salary >= 50000.50).
βœ“ Calculations can be performed inside the condition (e.g., WHERE salary * 12 > 800000).
βœ“ Fast execution: databases compare raw binary numbers significantly faster than text.
Real-Life Example
Imagine setting a minimum height rule at an amusement park roller coaster: 'Riders must be taller than 48 inches.' The gate measures your exact numeric height against the number 48 to decide if you may board.
Remember / Pro Tip
Write WHERE salary > 60000 without quotes; save quotes strictly for text words and calendar dates.
SQL Example
-- Filter employees with a salary strictly greater than $70,000
SELECT name, department, salary
FROM employees
WHERE salary > 70000;

-- Output:
-- Alice Martin | IT | 75000.00
-- Diana Prince | IT | 82000.00
-- Hannah Abbott| IT | 71000.00
SQL Master Β· Beginner Series Pg 34
CH 05 Filter Text (quotes)
Part 4 of 6

Filter Text (quotes)

Unlike numbers, text strings in SQL must always be wrapped inside single quotation marks ('text'). This tells the SQL parser that the text is a literal data value and not the name of a table or column. Omitting quotation marks around text values triggers syntax errors.

Key Points
βœ“ Always wrap text values in single quotation marks: WHERE city = 'New York';
βœ“ Do not use double quotes for text values in standard SQL (double quotes represent identifiers in many engines).
βœ“ Text comparisons are exact: 'IT' matches 'IT', but will not match 'Information Technology'.
βœ“ Case sensitivity depends on your database settings (MySQL is case-insensitive by default, PostgreSQL is case-sensitive).
βœ“ If a text value contains an apostrophe, escape it with two single quotes: 'O''Connor'.
Real-Life Example
Imagine looking for a package in a mail sorting facility labeled 'Austin'. If you don't put quotes around the word Austin, the computer thinks you are searching for an employee named Austin rather than the city named Austin.
Remember / Pro Tip
Single quotes are for literal values ('Chicago'); no quotes are for column names (city) and numbers (50000).
SQL Example
-- Filtering by text string columns wrapped in single quotes
SELECT name, department, city
FROM employees
WHERE city = 'Miami';

-- Output:
-- Fiona Gallagher | Sales | Miami
-- Hannah Abbott   | IT    | Miami
SQL Master Β· Beginner Series Pg 35
CH 05 Order of SELECT, FROM, WHERE
Part 5 of 6

Order of SELECT, FROM, WHERE

There is a famous quirk in SQL that every beginner must learn: the Written Order of clauses is completely different from their Logical Execution Order! While you write SELECT first on your keyboard, the database engine actually executes the FROM clause first, then the WHERE clause, and finally the SELECT clause.

Key Points
βœ“ Written Order: 1. SELECT -> 2. FROM -> 3. WHERE
βœ“ Execution Order: 1. FROM (Find table) -> 2. WHERE (Filter rows) -> 3. SELECT (Pick columns)
βœ“ Because WHERE executes before SELECT, you CANNOT use column aliases inside the WHERE clause!
βœ“ The database has not yet created your column alias when it evaluates the WHERE filter.
βœ“ Understanding execution order eliminates mysterious 'Unknown column' error messages.
Real-Life Example
Think of baking a cake: You must gather the ingredients from the pantry (FROM), filter out expired eggs (WHERE), and only then measure and decorate the slices to serve on the plate (SELECT). You cannot decorate slices before checking the ingredients!
Remember / Pro Tip
If you alias a column as (salary * 12) AS annual_pay, you must write WHERE (salary * 12) > 800000, not WHERE annual_pay > 800000.
SQL Example
-- Why column aliases fail in the WHERE clause:

-- WRONG (Causes error because 'annual_pay' does not exist yet):
-- SELECT name, (salary * 12) AS annual_pay
-- FROM employees
-- WHERE annual_pay > 800000;

-- CORRECT (Use the raw calculation in WHERE):
SELECT name, (salary * 12) AS annual_pay
FROM employees
WHERE (salary * 12) > 800000;

-- Output:
-- Alice Martin | 900000.00
-- Diana Prince | 984000.00
-- Hannah Abbott| 852000.00
SQL Master Β· Beginner Series Pg 36
CH 05 Mistakes + Recap and Practice
Part 6 of 6

Mistakes + Recap and Practice

Filtering data is the most common task in data querying, so avoiding simple WHERE mistakes will instantly make you a better programmer. Remember to wrap text in single quotes, keep numbers unquoted, avoid aliases in WHERE, and keep clause order strict.

Key Points
βœ“ Error 1: Forgetting quotes around text (WHERE department = IT; -> Throws unknown column 'IT' error).
βœ“ Error 2: Putting numbers in quotes (WHERE salary = '75000'; -> Works in MySQL, but bad habit for other databases).
βœ“ Error 3: Using a column alias in the WHERE filter.
βœ“ Error 4: Placing WHERE before FROM (SELECT name WHERE id = 1 FROM employees; -> Syntax error).
βœ“ Recap: WHERE filters rows; evaluates row by row; only rows evaluating to TRUE are returned.
Real-Life Example
Imagine writing a phone number search query and searching for the word 'Emergency' without quotes. The search engine tries to call a contact named Emergency instead of looking up the emergency contact number.
Remember / Pro Tip
When filtering, always verify your condition with sample rows: does Alice Martin satisfy city = 'New York'? Yes, so she is included!
SQL Example
-- WRONG: Missing quotes around string
-- SELECT * FROM employees WHERE department = HR;

-- FIXED:
SELECT * FROM employees WHERE department = 'HR';

-- Mini Practice:
-- Q1: Find all employees earning less than $55,000.
-- Answer: SELECT name, salary FROM employees WHERE salary < 55000;

-- Q2: Find all employees based in 'Austin'.
-- Answer: SELECT name, department FROM employees WHERE city = 'Austin';
SQL Master Β· Beginner Series Pg 37
CHAPTER {{ n.chapter_number|stringformat:"02d" }} 6 Parts

Comparison Operators

{{ n.short_description|default:"Essential SQL syntax rules, practical queries, step-by-step explanations, and best practices." }}

Topics in this chapter:
  • 1 What are Operators?
  • 2 Equal (=) and Not Equal (<> or !=)
  • 3 Greater / Less Than (>, <)
  • 4 Greater Than or Equal (>=, <=)
  • 5 NULL: IS NULL / IS NOT NULL
  • 6 Mistakes + Recap and Practice
CH 06 What are Operators?
Part 1 of 6

What are Operators?

Operators are special symbols and reserved keywords that instruct the database engine to perform a comparison between two values. In a WHERE clause, comparison operators evaluate an expression and produce a logical outcome: TRUE, FALSE, or UNKNOWN. They allow you to test for equality, numeric thresholds, and missing values.

Key Points
βœ“ Comparison operators compare an expression on the left with an expression on the right.
βœ“ Standard operators: = (equal), != or <> (not equal), > (greater), < (less), >=, <=.
βœ“ When a comparison evaluates to TRUE for a row, that row is included in the output.
βœ“ When a comparison evaluates to FALSE or UNKNOWN, that row is discarded.
βœ“ Operators work seamlessly with numbers, text strings, and calendar dates.
Real-Life Example
Think of comparison operators like the physical balance scales used in science class. You place a standard 1-kilogram weight on one side and an apple on the other. The scale immediately shows you if the apple is lighter, heavier, or equal in weight.
Remember / Pro Tip
Understanding operators is essential because they form the building blocks of every search condition in SQL.
SQL Example
-- Using multiple comparison operators in queries:
SELECT name, salary
FROM employees
WHERE salary = 75000;    -- Equal test

SELECT name, salary
FROM employees
WHERE salary != 75000;   -- Not equal test
SQL Master Β· Beginner Series Pg 39
CH 06 Equal (=) and Not Equal (<> or !=)
Part 2 of 6

Equal (=) and Not Equal (<> or !=)

The most common comparison in programming is testing whether two values match or differ. In SQL, equality is tested with a single equals sign (=). Inequality can be tested with either the ISO standard angle brackets (<>) or the modern exclamation-equal symbol (!=).

Key Points
βœ“ Equality operator: = (e.g., department = 'Sales').
βœ“ Inequality operators: <> (official standard SQL) and != (widely supported modern syntax).
βœ“ Both <> and != perform the exact same operation; <> is preferred for strict ANSI portability.
βœ“ Exact matching: text must match character for character.
βœ“ Warning: Neither = nor <> will match a NULL value; missing data requires IS NULL.
Real-Life Example
Imagine sorting mail into two bins. The first bin is labeled 'Local Delivery' where zip code = '10001'. The second bin is labeled 'Out of Town' where zip code <> '10001'. Every letter is sorted by whether it matches or differs.
Remember / Pro Tip
Use single = for equality in SQL. Unlike languages like JavaScript or Python, SQL does not use double equals (==).
SQL Example
-- 1. Equal to test (=)
SELECT name, department
FROM employees
WHERE department = 'Sales';
-- Returns: Charlie Brown, Fiona Gallagher

-- 2. Not equal to test (<> or !=)
SELECT name, department
FROM employees
WHERE department <> 'Sales';
-- Returns all 6 employees who do not work in Sales
SQL Master Β· Beginner Series Pg 40
CH 06 Greater / Less Than (>, <)
Part 3 of 6

Greater / Less Than (>, <)

The strictly greater than (>) and strictly less than (<) operators allow you to filter records that fall above or below a specific threshold. These operators exclude the exact boundary number itself; a salary of exactly $60,000 does NOT satisfy the condition salary > 60000.

Key Points
βœ“ Greater than (>): Returns rows where the column value is strictly larger than the target.
βœ“ Less than (<): Returns rows where the column value is strictly smaller than the target.
βœ“ Boundary values are strictly EXCLUDED: 60000 > 60000 evaluates to FALSE.
βœ“ Works with calendar dates: hire_date < '2025-01-01' finds staff hired before that date.
βœ“ Works with alphabetical text: name > 'M' finds names starting with letters N through Z.
Real-Life Example
If a roller coaster has a sign that reads 'Riders must be over 54 inches tall (> 54)', a child who measures exactly 54.0 inches cannot ride yet. They must be at least 54.1 inches to pass a strictly greater than rule.
Remember / Pro Tip
If you want to include the boundary value itself, use >= or <= instead of strict > or <.
SQL Example
-- 1. Strictly greater than $70,000
SELECT name, salary
FROM employees
WHERE salary > 70000;
-- Returns: Alice Martin (75k), Diana Prince (82k), Hannah Abbott (71k)

-- 2. Strictly less than $60,000
SELECT name, salary
FROM employees
WHERE salary < 60000;
-- Returns: Bob Smith (52k), Fiona Gallagher (59k), George Clark (48k)
SQL Master Β· Beginner Series Pg 41
CH 06 Greater Than or Equal (>=, <=)
Part 4 of 6

Greater Than or Equal (>=, <=)

When your filtering logic needs to include the boundary value itself, use the greater than or equal (>=) and less than or equal (<=) operators. These inclusive operators ensure that edge cases are not accidentally omitted from financial reports, performance reviews, or inventory warnings.

Key Points
βœ“ Greater than or equal (>=): Returns values that are larger than OR exactly equal to the target.
βœ“ Less than or equal (<=): Returns values that are smaller than OR exactly equal to the target.
βœ“ Syntax rule: The equal sign ALWAYS comes second (write >=, never =>; write <=, never =<).
βœ“ Inclusive filtering: salary >= 61000 includes Charlie Brown whose salary is exactly $61,000.
βœ“ Essential for milestone brackets like minimum passing test scores or tax tiers.
Real-Life Example
When taking a school driving exam, the passing rule states: 'Students with a score of 80% or higher pass the exam (score >= 80).' A student who scores exactly 80.0% passes with full credit.
Remember / Pro Tip
Writing => or =< is invalid SQL syntax and causes immediate parse errors; always type the bracket first: >= or <=.
SQL Example
-- Inclusive filtering: include employees earning exactly $61,000
SELECT name, department, salary
FROM employees
WHERE salary >= 61000;

-- Output:
-- Alice Martin   | IT      | 75000.00
-- Charlie Brown  | Sales   | 61000.00  <-- Boundary value included!
-- Diana Prince   | IT      | 82000.00
-- Evan Wright    | Finance | 68000.00
-- Hannah Abbott  | IT      | 71000.00
SQL Master Β· Beginner Series Pg 42
CH 06 NULL: IS NULL / IS NOT NULL
Part 5 of 6

NULL: IS NULL / IS NOT NULL

In relational databases, NULL represents missing, unknown, or unrecorded data. It is not equivalent to zero (0) and not equivalent to an empty text string (''). Because NULL represents the unknown, standard comparison operators like = NULL or != NULL never work and always evaluate to UNKNOWN! You must use IS NULL or IS NOT NULL.

Key Points
βœ“ NULL indicates that data was never entered or is currently unknown.
βœ“ The equality test column = NULL always fails and returns zero rows!
βœ“ Correct syntax for missing data: WHERE column IS NULL;
βœ“ Correct syntax for existing data: WHERE column IS NOT NULL;
βœ“ Any arithmetic performed on a NULL value (NULL + 100) results in NULL.
Real-Life Example
Imagine an application form with an optional field labeled 'Middle Name'. If an applicant leaves the box blank, that field is NULL. It does not mean their middle name is the word 'Nothing'; it means no data exists in that box.
Remember / Pro Tip
Never write = NULL or != NULL. Always write IS NULL or IS NOT NULL when checking for missing records.
SQL Example
-- Checking for missing or present values

-- WRONG (Always returns 0 rows!):
-- SELECT * FROM employees WHERE department = NULL;

-- CORRECT:
SELECT name, department
FROM employees
WHERE department IS NOT NULL;

-- All 8 employees have a recorded department, so all 8 rows return.
SQL Master Β· Beginner Series Pg 43
CH 06 Mistakes + Recap and Practice
Part 6 of 6

Mistakes + Recap and Practice

Comparison operators are simple once you memorize the syntax symbols. Use this page as a quick cheat sheet for equal, not equal, thresholds, inclusive bounds, and missing value checks.

Key Points
βœ“ Operator Cheat Sheet: = (equal), <> or != (not equal), > (greater), < (less), >=, <=, IS NULL.
βœ“ Common Mistake 1: Writing == instead of single = for equality tests.
βœ“ Common Mistake 2: Writing => instead of >=.
βœ“ Common Mistake 3: Trying to check missing values with = NULL instead of IS NULL.
βœ“ Common Mistake 4: Confusing strict inequalities (> 60000 excludes 60000) with inclusive ones (>= 60000).
Real-Life Example
Writing == in SQL is like putting a French accent mark over an English word; the reader might guess your meaning, but the language rules flag it as invalid. Stick strictly to standard SQL operator symbols.
Remember / Pro Tip
When you want everything except one department, use <>: WHERE department <> 'HR'.
SQL Example
-- Comparison Operator Practice Queries:

-- Q1: Find all employees who do NOT work in the 'IT' department.
SELECT name, department FROM employees WHERE department <> 'IT';
-- Answer: Bob, Charlie, Evan, Fiona, George (5 employees)

-- Q2: Find all employees who earn $68,000 or less.
SELECT name, salary FROM employees WHERE salary <= 68000;
-- Answer: Bob (52k), Charlie (61k), Evan (68k), Fiona (59k), George (48k)
SQL Master Β· Beginner Series Pg 44
CHAPTER {{ n.chapter_number|stringformat:"02d" }} 7 Parts

AND / OR / NOT

{{ n.short_description|default:"Essential SQL syntax rules, practical queries, step-by-step explanations, and best practices." }}

Topics in this chapter:
  • 1 Combining Conditions
  • 2 The AND Operator
  • 3 The OR Operator
  • 4 The NOT Operator
  • 5 AND + OR Together and Brackets
  • 6 Truth Table in Simple Form
  • 7 Mistakes + Recap and Practice
CH 07 Combining Conditions
Part 1 of 7

Combining Conditions

When filtering real-world tables, a single condition is rarely enough to find the exact records you need. SQL provides logical operators that allow you to string multiple test rules together inside a single WHERE clause. By connecting separate tests with AND, OR, and NOT, you can pinpoint very specific rows across massive corporate tables.

Key Points
βœ“ Logical operators evaluate whether combinations of tests produce TRUE, FALSE, or UNKNOWN.
βœ“ AND demands that every single connected condition must be TRUE for a row to match.
βœ“ OR requires only one condition out of the group to be TRUE.
βœ“ NOT flips the logical result: TRUE becomes FALSE, and FALSE becomes TRUE.
βœ“ You can link as many conditions together as needed to satisfy complex business questions.
Real-Life Example
Imagine you are searching an online job board for work. If you filter for jobs that offer remote work AND pay over $70,000, only listings meeting both criteria appear. If you search for remote jobs OR hybrid jobs, listings satisfying either preference will show up.
Remember / Pro Tip
Think of logical operators as traffic junctions: AND closes the gate unless both keys work, while OR opens the gate if either key works.
SQL Example
-- Previewing combined filtering on the employees table
SELECT name, department, salary, city
FROM employees
WHERE department = 'IT' AND city = 'New York';

-- Output:
-- | name         | department | salary | city     |
-- | Alice Martin | IT         |  75000 | New York |
SQL Master Β· Beginner Series Pg 46
CH 07 The AND Operator
Part 2 of 7

The AND Operator

The AND operator connects two or more filter conditions and requires all of them to evaluate to TRUE before including a row in the results. If even one test in the chain fails or evaluates to FALSE, the database engine immediately discards that entire row. This makes AND the ideal operator for narrowing down broad lists into tight, highly qualified groups.

Key Points
βœ“ Every condition connected by AND must evaluate to TRUE for a row to be returned.
βœ“ If any single condition is FALSE, the entire row fails the test.
βœ“ AND narrows down your result set, producing fewer rows than single conditions alone.
βœ“ You can chain three or more conditions together in sequence using repeated AND keywords.
βœ“ The order of conditions joined by AND does not change which rows are returned.
Real-Life Example
Imagine a bouncer at a concert venue checking attendees at the VIP entrance door. You must possess a VIP wristband AND be at least 21 years old to enter. Having only one of these qualifications gets you turned away at the door.
Remember / Pro Tip
Use AND when you want stricter filtering: the more AND conditions you add, the fewer rows you will see.
SQL Example
-- Find employees who work in IT AND earn more than 75000
SELECT id, name, department, salary, city
FROM employees
WHERE department = 'IT' AND salary > 75000;

-- Output:
-- | id | name         | department | salary | city   |
-- |  4 | Diana Prince | IT         |  82000 | Austin |
SQL Master Β· Beginner Series Pg 47
CH 07 The OR Operator
Part 3 of 7

The OR Operator

The OR operator connects multiple search conditions and includes a row in the results as long as at least one condition evaluates to TRUE. Unlike AND, which requires strict agreement across every test, OR gives rows multiple ways to qualify. As a result, using OR widens your search and returns a larger collection of matching rows.

Key Points
βœ“ A row is included if condition 1 is TRUE, or condition 2 is TRUE, or both are TRUE.
βœ“ A row is rejected only when all connected conditions evaluate to FALSE.
βœ“ OR broadens your results, typically returning more rows than a single condition alone.
βœ“ You can link multiple choices across different columns or check multiple values in the same column.
βœ“ OR is commonly used when you want records from either city A or city B.
Real-Life Example
Imagine a school cafeteria announcing that students can get a free lunch if they are on the honor roll OR playing on the soccer team. A student on the honor roll qualifies, a soccer player qualifies, and an athlete on the honor roll also qualifies.
Remember / Pro Tip
Use OR when you want flexible choices: a row only needs to pass one test to make it into the final output.
SQL Example
-- Find employees who work in HR OR live in Chicago
SELECT id, name, department, salary, city
FROM employees
WHERE department = 'HR' OR city = 'Chicago';

-- Output:
-- | id | name        | department | salary | city    |
-- |  2 | Bob Smith   | HR         |  52000 | Chicago |
-- |  5 | Evan Wright | Finance    |  68000 | Chicago |
-- |  7 | George Clark| HR         |  48000 | Austin  |
SQL Master Β· Beginner Series Pg 48
CH 07 The NOT Operator
Part 4 of 7

The NOT Operator

The NOT operator reverses the logical outcome of any condition that immediately follows it in a query. If a condition evaluates to TRUE for a row, NOT turns it into FALSE, causing the row to be rejected. If a condition evaluates to FALSE, NOT turns it into TRUE, allowing that row to appear in your result set.

Key Points
βœ“ NOT is placed immediately before a condition to invert its truth value.
βœ“ A condition that would normally match is excluded, while non-matching rows are included.
βœ“ NOT is often paired with operators like IN, BETWEEN, and LIKE for readable queries.
βœ“ It provides a clear, natural English way to write negative business criteria.
βœ“ Be careful with NULL values: NOT applied to a NULL test does not evaluate to TRUE.
Real-Life Example
Imagine you are packing for a vacation and your packing checklist says: 'Bring all clothes that are NOT winter jackets.' You pack your t-shirts, jeans, and swimwear, but leave heavy winter coats hanging in the wardrobe.
Remember / Pro Tip
NOT is your negative filter: it asks the database engine to find everything except the specified criteria.
SQL Example
-- Find all employees who do NOT work in the IT department
SELECT id, name, department, salary, city
FROM employees
WHERE NOT department = 'IT';

-- Output:
-- | id | name            | department | salary | city     |
-- |  2 | Bob Smith       | HR         |  52000 | Chicago  |
-- |  3 | Charlie Brown   | Sales      |  61000 | New York |
-- |  5 | Evan Wright     | Finance    |  68000 | Chicago  |
-- |  6 | Fiona Gallagher | Sales      |  59000 | Miami    |
-- |  7 | George Clark    | HR         |  48000 | Austin   |
SQL Master Β· Beginner Series Pg 49
CH 07 AND + OR Together and Brackets
Part 5 of 7

AND + OR Together and Brackets

When you mix AND and OR inside the same WHERE clause, SQL applies operator precedence rules that can cause surprising results if you are not careful. SQL always evaluates AND conditions before OR conditions, much like multiplication is calculated before addition in standard math. To ensure your query executes in the exact order you intend, always group related conditions inside parentheses.

Key Points
βœ“ AND has higher mathematical precedence than OR in SQL evaluations.
βœ“ Without brackets, SQL pairs conditions next to AND first, which can produce unexpected rows.
βœ“ Parentheses force the database engine to evaluate the inner conditions as a single group.
βœ“ Grouping related conditions with brackets makes your SQL code clear and self-documenting.
βœ“ When in doubt, always add parentheses to make your business logic unmistakable.
Real-Life Example
Consider the math expression 2 + 3 * 4. Multiplication happens first, giving 14. If you write (2 + 3) * 4, parentheses force addition first, giving 20. Brackets in SQL work the exact same way to control condition priority.
Remember / Pro Tip
Always wrap your OR conditions in parentheses whenever you combine them with an AND condition.
SQL Example
-- WRONG: Might return Sales employees from any city!
-- WHERE department = 'IT' OR department = 'Sales' AND city = 'Miami';

-- CORRECT: Parentheses guarantee department choice happens first
SELECT id, name, department, salary, city
FROM employees
WHERE (department = 'IT' OR department = 'Sales') AND city = 'Miami';

-- Output:
-- | id | name            | department | salary | city  |
-- |  6 | Fiona Gallagher | Sales      |  59000 | Miami |
-- |  8 | Hannah Abbott   | IT         |  71000 | Miami |
SQL Master Β· Beginner Series Pg 50
CH 07 Truth Table in Simple Form
Part 6 of 7

Truth Table in Simple Form

A truth table is a simple reference chart that shows what happens when you combine two conditions using AND, OR, or NOT. Because computer logic evaluates every test as either TRUE (T) or FALSE (F), seeing the combinations side by side makes it easy to predict how the database will handle your records. Mastering this table gives you total confidence when writing complex filters.

Key Points
βœ“ TRUE AND TRUE = TRUE (the only way AND succeeds).
βœ“ TRUE AND FALSE = FALSE (any false makes AND fail).
βœ“ FALSE OR FALSE = FALSE (the only way OR fails).
βœ“ TRUE OR FALSE = TRUE (a single true is enough for OR).
βœ“ NOT TRUE = FALSE, and NOT FALSE = TRUE (inversion).
Real-Life Example
Imagine two light switches on a wall. In an AND circuit, both switches must be turned UP for the hallway bulb to light up. In an OR circuit, flipping either switch UP turns the bulb on immediately.
Remember / Pro Tip
Memorize the golden rules: AND is strict and demands both to be TRUE; OR is generous and needs only one TRUE.
SQL Example
-- Truth Table Reference Demo:
-- Test 1 (department = 'IT') | Test 2 (city = 'Miami')
-- Alice:    TRUE  AND FALSE => FALSE  | TRUE  OR FALSE => TRUE
-- Bob:      FALSE AND FALSE => FALSE  | FALSE OR FALSE => FALSE
-- Hannah:   TRUE  AND TRUE  => TRUE   | TRUE  OR TRUE  => TRUE

SELECT name, department, city
FROM employees
WHERE (department = 'IT' AND city = 'Miami')
   OR (department = 'HR' AND city = 'Austin');

-- Output: George Clark (HR, Austin) and Hannah Abbott (IT, Miami)
SQL Master Β· Beginner Series Pg 51
CH 07 Mistakes + Recap and Practice
Part 7 of 7

Mistakes + Recap and Practice

Mixing logical operators is one of the most common places beginners introduce subtle bugs into SQL queries. The most frequent mistake is omitting parentheses around OR conditions, causing the query to return rows from unwanted categories. Another common slip is writing WHERE department = 'IT' OR 'HR', which is invalid syntax because each side of OR must be a complete test.

Key Points
βœ“ Both sides of AND or OR must be complete, independent comparisons.
βœ“ Never omit brackets when mixing AND and OR in the same query.
βœ“ Remember that NOT department = 'IT' can also be written cleanly as department != 'IT'.
βœ“ Always test your combined conditions with a small sample of rows to verify the logic.
Real-Life Example
Imagine writing a letter to a bank: 'I want accounts that are active and checking or savings.' Without clear punctuation, the teller might send you every savings account ever opened, even closed ones!
Remember / Pro Tip
Recap: AND shrinks results, OR expands results, NOT flips results, and brackets enforce your exact priority.
SQL Example
-- Practice 1: Find IT workers earning more than 70000 in Miami
-- Answer:
SELECT * FROM employees WHERE department = 'IT' AND salary > 70000 AND city = 'Miami';

-- Practice 2: Find employees living in Chicago OR New York
-- Answer:
SELECT * FROM employees WHERE city = 'Chicago' OR city = 'New York';

-- Practice 3: Find non-HR employees who earn at least 60000
-- Answer:
SELECT * FROM employees WHERE NOT department = 'HR' AND salary >= 60000;
SQL Master Β· Beginner Series Pg 52
CHAPTER {{ n.chapter_number|stringformat:"02d" }} 5 Parts

IN

{{ n.short_description|default:"Essential SQL syntax rules, practical queries, step-by-step explanations, and best practices." }}

Topics in this chapter:
  • 1 What is IN?
  • 2 IN Syntax and Example
  • 3 NOT IN
  • 4 IN vs Many ORs
  • 5 Mistakes + Recap and Practice
CH 08 What is IN?
Part 1 of 5

What is IN?

The IN operator allows you to check whether a column's value matches any value within a comma-separated list of options. Instead of chaining together five or six separate OR statements comparing the same column over and over, you write a single, clean expression. The database engine compares each row against the list and returns the row if an exact match is found.

Key Points
βœ“ IN tests if a column value exists within a provided set of values.
βœ“ It replaces long, messy chains of repeated OR comparisons.
βœ“ The list of values is enclosed inside parentheses and separated by commas.
βœ“ IN works with text strings, numbers, and dates.
βœ“ If a row's column value matches any item in the list, the condition evaluates to TRUE.
Real-Life Example
Imagine you are at an ice cream parlor with twenty flavors. You tell the server: 'I want a scoop if you have chocolate, strawberry, or pistachio.' Instead of asking three separate questions, you give one list of acceptable flavors.
Remember / Pro Tip
Use IN whenever you are comparing one column against multiple possible values to keep your SQL clean and concise.
SQL Example
-- Finding employees located in specific target cities using IN
SELECT id, name, department, city
FROM employees
WHERE city IN ('New York', 'Austin', 'Miami');

-- Output: Returns 6 employees whose city is New York, Austin, or Miami
-- (Only Bob Smith and Evan Wright from Chicago are excluded)
SQL Master Β· Beginner Series Pg 54
CH 08 IN Syntax and Example
Part 2 of 5

IN Syntax and Example

The syntax for the IN operator is remarkably simple and mirrors natural human speech. You place the column name first, followed by the keyword IN, and then enclose your list of target values in parentheses, separated by commas. Text values inside the list must be surrounded by single quotation marks, while numeric values are written plainly without quotes.

Key Points
βœ“ Syntax pattern: WHERE column_name IN (value1, value2, value3).
βœ“ Text items must be enclosed in single quotation marks: ('IT', 'HR').
βœ“ Numbers are written without quotes: (48000, 52000, 75000).
βœ“ The order of items inside the parentheses does not affect query performance or results.
βœ“ The database engine checks each row against every item in the list sequentially or via hash lookup.
Real-Life Example
Imagine looking up a phone directory for friends living in three specific zip codes. You write down the three zip codes on a note card and check every listing against your card until you find matches.
Remember / Pro Tip
Always separate items in your IN list with commas and match the data type of the column you are testing.
SQL Example
-- Syntax: SELECT columns FROM table WHERE column IN (list);
SELECT id, name, department, salary
FROM employees
WHERE department IN ('HR', 'Finance');

-- Output:
-- | id | name         | department | salary |
-- |  2 | Bob Smith    | HR         |  52000 |
-- |  5 | Evan Wright  | Finance    |  68000 |
-- |  7 | George Clark | HR         |  48000 |
SQL Master Β· Beginner Series Pg 55
CH 08 NOT IN
Part 3 of 5

NOT IN

The NOT IN operator does the exact opposite of IN: it returns all rows where the column's value does not match any item in your list. This is extremely helpful when you want to filter out a known group of departments, cities, or status codes in a single stroke. If a row's value appears anywhere inside the list, that row is immediately excluded from the results.

Key Points
βœ“ NOT IN excludes all records whose column value matches any item in the list.
βœ“ It is equivalent to writing multiple AND NOT conditions chained together.
βœ“ The row is returned only if its value is completely absent from the provided list.
βœ“ Beware of NULL values: if your NOT IN list contains a NULL value, the entire query may return zero rows.
βœ“ It is perfect for excluding known test accounts, inactive branches, or unwanted categories.
Real-Life Example
Imagine a company organizing a regional training seminar that invites every office except those located in Chicago and Austin. Any employee whose badge says Chicago or Austin is barred, while everyone else enters freely.
Remember / Pro Tip
Use NOT IN when it is faster and easier to specify what you want to exclude rather than what you want to include.
SQL Example
-- Find all employees who do NOT work in IT or Sales
SELECT id, name, department, salary, city
FROM employees
WHERE department NOT IN ('IT', 'Sales');

-- Output:
-- | id | name         | department | salary | city    |
-- |  2 | Bob Smith    | HR         |  52000 | Chicago |
-- |  5 | Evan Wright  | Finance    |  68000 | Chicago |
-- |  7 | George Clark | HR         |  48000 | Austin  |
SQL Master Β· Beginner Series Pg 56
CH 08 IN vs Many ORs
Part 4 of 5

IN vs Many ORs

Beginners often wonder whether there is a real difference between using IN and chaining multiple OR conditions. Both approaches produce identical rows from the database, but IN is vastly superior in readability, maintainability, and code brevity. Furthermore, many database query optimizers process an IN list faster than a lengthy sequence of separate OR expressions.

Key Points
βœ“ WHERE city IN ('NY', 'Austin') is functionally identical to WHERE city = 'NY' OR city = 'Austin'.
βœ“ IN saves considerable typing when testing against four, five, or ten possible values.
βœ“ IN reduces the risk of forgetting column names or making typos across multiple comparisons.
βœ“ Modern database optimizers can sort IN lists internally to speed up row evaluation.
βœ“ IN queries are much easier for other developers to read and maintain during code reviews.
Real-Life Example
Imagine writing a grocery list. You write: 'Buy fruit: apples, pears, oranges, bananas.' You would never write: 'Buy apples, or buy pears, or buy oranges, or buy bananas.' The list format is faster to read and far less cluttered.
Remember / Pro Tip
Whenever you catch yourself writing the same column name more than twice with OR, refactor immediately to IN.
SQL Example
-- CLUTTERED APPROACH (Repeated ORs):
-- WHERE city = 'New York' OR city = 'Chicago' OR city = 'Miami';

-- CLEAN PROFESSIONAL APPROACH (IN operator):
SELECT name, department, city
FROM employees
WHERE city IN ('New York', 'Chicago', 'Miami');

-- Output: Returns 6 employees residing in the three requested cities
SQL Master Β· Beginner Series Pg 57
CH 08 Mistakes + Recap and Practice
Part 5 of 5

Mistakes + Recap and Practice

A common beginner mistake when using IN is forgetting to put single quotation marks around text items, which causes a syntax error because SQL treats unquoted words as column names. Another frequent mistake is writing commas outside the parentheses or using square brackets instead of round brackets. Finally, remember that IN performs exact matches; it does not do partial text matching like LIKE.

Key Points
βœ“ Always wrap text list items in single quotes: ('IT', 'HR') not (IT, HR).
βœ“ Always use round parentheses () for the list, never curly {} or square brackets [].
βœ“ Separate each item inside the parentheses with a single comma.
βœ“ IN checks for exact equality, not partial string matches.
Real-Life Example
Imagine handing a shopping list to a clerk with words stuck together without commas: 'applesbananasmilkcereal'. The clerk will be confused and unable to fulfill your request until you add commas.
Remember / Pro Tip
Recap: IN tests membership in a list, NOT IN excludes the list, and both make multi-value filters effortless.
SQL Example
-- Practice 1: Select employees whose ID is 1, 3, or 5
-- Answer:
SELECT * FROM employees WHERE id IN (1, 3, 5);

-- Practice 2: Select employees who live in Austin or Chicago
-- Answer:
SELECT * FROM employees WHERE city IN ('Austin', 'Chicago');

-- Practice 3: Select employees who are NOT in HR or Finance
-- Answer:
SELECT * FROM employees WHERE department NOT IN ('HR', 'Finance');
SQL Master Β· Beginner Series Pg 58
CHAPTER {{ n.chapter_number|stringformat:"02d" }} 5 Parts

BETWEEN

{{ n.short_description|default:"Essential SQL syntax rules, practical queries, step-by-step explanations, and best practices." }}

Topics in this chapter:
  • 1 What is BETWEEN? (inclusive)
  • 2 BETWEEN with Numbers
  • 3 BETWEEN with Dates
  • 4 NOT BETWEEN
  • 5 Mistakes + Recap and Practice
CH 09 What is BETWEEN? (inclusive)
Part 1 of 5

What is BETWEEN? (inclusive)

The BETWEEN operator allows you to filter rows where a column value falls within a specified low and high boundary. Instead of writing two separate comparisons joined by AND, you state the range in one clean, natural English clause. The most critical rule to remember about SQL's BETWEEN operator is that it is completely inclusive of both boundary endpoints.

Key Points
βœ“ BETWEEN tests if a value falls between a minimum and a maximum limit.
βœ“ It is fully INCLUSIVE: both the start value and end value are included in the results.
βœ“ Syntax pattern: WHERE column_name BETWEEN low_value AND high_value.
βœ“ It replaces writing: WHERE column >= low_value AND column <= high_value.
βœ“ The lower boundary must always be written before the higher boundary.
Real-Life Example
Imagine a movie theater offering discounted tickets for youth between the ages of 12 and 18. A 12-year-old receives the discount, an 18-year-old receives the discount, and everyone aged 13 through 17 qualifies as well.
Remember / Pro Tip
Because BETWEEN includes both endpoints, a salary range of 50000 to 70000 includes people earning exactly 50000 and 70000.
SQL Example
-- Finding employees with salaries between 50000 and 70000 (inclusive)
SELECT id, name, department, salary
FROM employees
WHERE salary BETWEEN 50000 AND 70000;

-- Output:
-- | id | name            | department | salary |
-- |  2 | Bob Smith       | HR         |  52000 |
-- |  3 | Charlie Brown   | Sales      |  61000 |
-- |  5 | Evan Wright     | Finance    |  68000 |
-- |  6 | Fiona Gallagher | Sales      |  59000 |
SQL Master Β· Beginner Series Pg 60
CH 09 BETWEEN with Numbers
Part 2 of 5

BETWEEN with Numbers

Using BETWEEN with numeric columns like salaries, prices, quantities, and ages is one of the most common everyday tasks in SQL. It creates clean, human-readable queries that are easy for both technical developers and business analysts to understand. When filtering numbers, write the lower number first, followed by AND, and then the higher number without quotation marks.

Key Points
βœ“ Always specify the smaller number first and the larger number second.
βœ“ Do not put quotation marks or dollar signs around numbers: use 50000, not '$50,000'.
βœ“ BETWEEN 60000 AND 80000 includes any employee earning 60000, 80000, or any amount in between.
βœ“ If you accidentally write the larger number first, SQL will return zero rows without error.
βœ“ BETWEEN works seamlessly with both whole integers and decimal numbers.
Real-Life Example
Imagine setting a price filter on a real estate website looking for apartments priced between $1,500 and $2,200 per month. The search engine displays units priced at $1,500, $2,200, and everything inside that bracket.
Remember / Pro Tip
If your BETWEEN query returns zero rows unexpectedly, check if you wrote the higher number first by mistake.
SQL Example
-- Find employees earning between 60000 and 80000
SELECT id, name, department, salary
FROM employees
WHERE salary BETWEEN 60000 AND 80000;

-- Output:
-- | id | name          | department | salary |
-- |  1 | Alice Martin  | IT         |  75000 |
-- |  3 | Charlie Brown | Sales      |  61000 |
-- |  5 | Evan Wright   | Finance    |  68000 |
-- |  8 | Hannah Abbott | IT         |  71000 |
SQL Master Β· Beginner Series Pg 61
CH 09 BETWEEN with Dates
Part 3 of 5

BETWEEN with Dates

The BETWEEN operator is frequently used to filter chronological events such as order dates, employee hire dates, or registration timestamps. In standard SQL, dates must be written in the ISO standard format 'YYYY-MM-DD' and enclosed inside single quotation marks. Just like with numbers, the earlier calendar date must come first and the later date second.

Key Points
βœ“ Dates must follow the standard 'YYYY-MM-DD' format (Year-Month-Day).
βœ“ Date literals must always be enclosed in single quotation marks.
βœ“ The earlier calendar date must be specified first, followed by AND, then the later date.
βœ“ If a column contains time information (timestamps), BETWEEN '2024-01-01' AND '2024-01-31' stops at midnight.
βœ“ Use date functions or explicit end-of-day timestamps when querying datetime fields.
Real-Life Example
Imagine a company running a summer discount campaign that starts on June 1st and ends on August 31st. Any transaction recorded on or between those dates qualifies for the promotion.
Remember / Pro Tip
Always format dates as 'YYYY-MM-DD': writing '12/05/2024' can cause errors or confuse month and day.
SQL Example
-- Demonstration: Filtering hire dates using BETWEEN
-- (Assuming an optional hire_date column formatted as YYYY-MM-DD)
-- SELECT name, hire_date
-- FROM employees
-- WHERE hire_date BETWEEN '2022-01-01' AND '2023-12-31';

-- Numeric range comparison on our standard employees table:
SELECT id, name, salary
FROM employees
WHERE salary BETWEEN 70000 AND 85000;

-- Output: Alice Martin (75000), Diana Prince (82000), Hannah Abbott (71000)
SQL Master Β· Beginner Series Pg 62
CH 09 NOT BETWEEN
Part 4 of 5

NOT BETWEEN

The NOT BETWEEN operator selects records whose column value falls completely outside the specified lower and upper boundaries. A row is included if its value is strictly less than the minimum boundary OR strictly greater than the maximum boundary. This provides an effortless way to identify outlier values or exclude a specific middle range of data.

Key Points
βœ“ NOT BETWEEN excludes values that fall inside the inclusive boundary.
βœ“ A row qualifies if column < low_value OR column > high_value.
βœ“ The boundary values themselves are excluded from the result set.
βœ“ Syntax pattern: WHERE column_name NOT BETWEEN low_value AND high_value.
βœ“ It is ideal for identifying extreme values such as junior trainees and top executives.
Real-Life Example
Imagine a school clothing drive asking for donations for toddlers (under 5 years) and teenagers (over 12 years). They announce: 'Please do NOT bring clothing between ages 5 and 12.' The middle bracket is omitted.
Remember / Pro Tip
NOT BETWEEN is the exact inverse of BETWEEN: it keeps the outer wings and chops out the middle range.
SQL Example
-- Find employees whose salary is NOT between 55000 and 75000
SELECT id, name, department, salary
FROM employees
WHERE salary NOT BETWEEN 55000 AND 75000;

-- Output:
-- | id | name         | department | salary |
-- |  2 | Bob Smith    | HR         |  52000 | (below 55000)
-- |  4 | Diana Prince | IT         |  82000 | (above 75000)
-- |  7 | George Clark | HR         |  48000 | (below 55000)
SQL Master Β· Beginner Series Pg 63
CH 09 Mistakes + Recap and Practice
Part 5 of 5

Mistakes + Recap and Practice

The number one beginner trap with BETWEEN is reversing the two boundary values, such as writing WHERE salary BETWEEN 80000 AND 50000. In SQL, no number can be simultaneously greater than or equal to 80000 and less than or equal to 50000, so the query quietly returns zero rows. Another common error is assuming BETWEEN is exclusive and excludes the edges; remember that the edge values are always included!

Key Points
βœ“ Never put the high value first: low value MUST always precede the high value.
βœ“ Remember that both endpoints are inclusive: 50000 AND 60000 includes 50000 and 60000.
βœ“ When filtering text ranges alphabetically, 'Z' boundaries can behave unexpectedly.
βœ“ With datetime columns, remember that a date without a time defaults to 00:00:00 (midnight).
Real-Life Example
Imagine reading a thermometer scale: you cannot measure temperatures between 100 degrees and 30 degrees. You must read from the lower temperature upward to the higher temperature.
Remember / Pro Tip
Recap: BETWEEN is inclusive, needs low AND high in order, and NOT BETWEEN keeps only the outer ends.
SQL Example
-- Practice 1: Find employees with ID between 2 and 5 (inclusive)
-- Answer:
SELECT * FROM employees WHERE id BETWEEN 2 AND 5;

-- Practice 2: Find employees earning between 45000 and 60000
-- Answer:
SELECT * FROM employees WHERE salary BETWEEN 45000 AND 60000;

-- Practice 3: Find employees whose salary is NOT between 60000 and 80000
-- Answer:
SELECT * FROM employees WHERE salary NOT BETWEEN 60000 AND 80000;
SQL Master Β· Beginner Series Pg 64
CHAPTER {{ n.chapter_number|stringformat:"02d" }} 6 Parts

LIKE

{{ n.short_description|default:"Essential SQL syntax rules, practical queries, step-by-step explanations, and best practices." }}

Topics in this chapter:
  • 1 What is LIKE?
  • 2 The % Wildcard
  • 3 The _ Wildcard
  • 4 Starts With / Ends With / Contains
  • 5 NOT LIKE and Case Sensitivity
  • 6 Mistakes + Recap and Practice
CH 10 What is LIKE?
Part 1 of 6

What is LIKE?

The LIKE operator allows you to search for text patterns inside a column rather than matching an exact word. When users search for products on an e-commerce website or look up contacts on their phone, they rarely type the full, exact name. By pairing the LIKE operator with special wildcard symbols, SQL can find strings that start with, end with, or contain specific characters.

Key Points
βœ“ LIKE performs pattern matching searches on text (VARCHAR / CHAR) columns.
βœ“ The equality operator (=) requires an exact match, whereas LIKE allows flexible patterns.
βœ“ SQL provides two standard wildcard characters: percent sign (%) and underscore (_).
βœ“ The percent sign (%) represents zero, one, or multiple characters.
βœ“ The underscore sign (_) represents exactly one single character.
Real-Life Example
Imagine searching your smartphone contact list for someone named 'Rob'. Typing 'Rob' displays Robert, Robbie, Robin, and Robinson. The LIKE operator provides this exact search functionality for database tables.
Remember / Pro Tip
Use the equality operator (=) when you know the exact string, and use LIKE when you only know a part of it.
SQL Example
-- Finding employees whose name starts with the letter 'A'
SELECT id, name, department, city
FROM employees
WHERE name LIKE 'A%';

-- Output:
-- | id | name         | department | city     |
-- |  1 | Alice Martin | IT         | New York |
SQL Master Β· Beginner Series Pg 66
CH 10 The % Wildcard
Part 2 of 6

The % Wildcard

The percent sign (%) is the most versatile wildcard in SQL because it matches any sequence of characters of any length, including zero characters. When you place % at the end of a string, it matches any text starting with that prefix. When placed at both ends, it matches any row where the characters appear anywhere in the middle of the text.

Key Points
βœ“ % represents zero, one, or any number of characters.
βœ“ 'A%' matches any text starting with capital A ('Alice', 'Austin', 'A').
βœ“ '%k' matches any text ending with lowercase k ('New York', 'Clark').
βœ“ '%ar%' matches any text containing 'ar' anywhere ('Martin', 'Charlie', 'Clark').
βœ“ You can use multiple percent signs within a single search pattern if needed.
Real-Life Example
Imagine looking for a book in a library catalog when you only remember one word from the title: 'Potter'. You search for '%Potter%' and the system pulls up every book that has 'Potter' in the title, regardless of other words.
Remember / Pro Tip
Putting % on both sides of a keyword like '%sale%' is the classic 'contains' search used in website search bars.
SQL Example
-- Find all employees whose city contains the letters 'am'
SELECT id, name, department, city
FROM employees
WHERE city LIKE '%am%';

-- Output:
-- | id | name            | department | city  |
-- |  6 | Fiona Gallagher | Sales      | Miami |
-- |  8 | Hannah Abbott   | IT         | Miami |
SQL Master Β· Beginner Series Pg 67
CH 10 The _ Wildcard
Part 3 of 6

The _ Wildcard

The underscore wildcard (_) matches exactly one single character, no more and no less. While the percent wildcard (%) is open-ended and matches any number of characters, the underscore acts as a strict single-letter placeholder. You can use multiple underscores in a row to represent a precise number of missing characters in fixed-length codes or names.

Key Points
βœ“ The underscore (_) represents exactly one single character.
βœ“ 'H_n%' matches words starting with H, followed by any single letter, then 'n', then anything.
βœ“ '____' (four underscores) matches any text value that is exactly four characters long.
βœ“ Combining _ and % gives you powerful control over structured codes and product serial numbers.
βœ“ It is widely used to validate zip codes, telephone area codes, and standard license plates.
Real-Life Example
Imagine playing a word puzzle game like Wordle or Hangman where you see the clue 'C_T'. The blank can be filled by 'A' for CAT, 'O' for COT, or 'U' for CUT. Each underscore represents exactly one missing letter.
Remember / Pro Tip
Use % when you don't know the length, and use _ when you know the exact number of characters.
SQL Example
-- Find employees whose city has 'i' as the second letter and is 5 characters long
SELECT id, name, department, city
FROM employees
WHERE city LIKE '_i___';

-- Explanation:
-- Miami: M (1), i (2), a (3), m (4), i (5) => Matches exactly!
-- Output: Fiona Gallagher (Miami) and Hannah Abbott (Miami)
SQL Master Β· Beginner Series Pg 68
CH 10 Starts With / Ends With / Contains
Part 4 of 6

Starts With / Ends With / Contains

Mastering the three primary wildcard placement patterns covers almost every text search you will ever need to perform in SQL. By placing the percent sign at the beginning, end, or both sides of your search keyword, you can quickly answer questions about prefixes, suffixes, and internal substrings. Keep this cheat table handy whenever writing search filters.

Key Points
βœ“ 'Prefix%' -> Starts With: Matches strings beginning with the specified characters.
βœ“ '%Suffix' -> Ends With: Matches strings terminating with the specified characters.
βœ“ '%Keyword%' -> Contains: Matches strings containing the keyword anywhere inside.
βœ“ 'A%Z' -> Starts with A and ends with Z with anything in between.
βœ“ '_%' -> Must have at least one character.
Real-Life Example
Think of searching an email inbox: searching 'support@%' finds emails sent from any address at support, while '%@gmail.com' finds all emails originating from Google accounts.
Remember / Pro Tip
Pattern Cheat Sheet: 'A%' = Starts with A; '%A' = Ends with A; '%A%' = Contains A.
SQL Example
-- 1. Starts with 'Ch':
SELECT name, city FROM employees WHERE city LIKE 'Ch%';
-- Output: Bob Smith (Chicago), Evan Wright (Chicago)

-- 2. Ends with 'k':
SELECT name, city FROM employees WHERE city LIKE '%k';
-- Output: Alice Martin (New York), Charlie Brown (New York)

-- 3. Contains 'Prince':
SELECT name FROM employees WHERE name LIKE '%Prince%';
-- Output: Diana Prince
SQL Master Β· Beginner Series Pg 69
CH 10 NOT LIKE and Case Sensitivity
Part 5 of 6

NOT LIKE and Case Sensitivity

The NOT LIKE operator inverts pattern matching to return all rows that do not match the specified wildcard pattern. Additionally, it is critical to understand how your database engine handles letter casing during pattern searches. In MySQL, LIKE searches are case-insensitive by default, whereas in PostgreSQL, LIKE is strictly case-sensitive unless you use the ILIKE operator.

Key Points
βœ“ NOT LIKE excludes all rows matching the specified pattern.
βœ“ In MySQL, LIKE 'a%' matches both 'Alice' and 'alice' by default.
βœ“ In PostgreSQL, LIKE is case-sensitive, while ILIKE is used for case-insensitive searches.
βœ“ In SQLite and SQL Server, case sensitivity depends on the database collation settings.
βœ“ To ensure case-insensitive matching across any database, convert the column to LOWER(column).
Real-Life Example
Imagine an email newsletter list removing all temporary throwaway email accounts before sending a campaign. The query filters for: email NOT LIKE '%@tempmail.com' to keep only real subscribers.
Remember / Pro Tip
If your LIKE query unexpectedly returns no rows on PostgreSQL, use ILIKE instead of LIKE for case-insensitivity.
SQL Example
-- Find employees whose name does NOT start with 'A'
SELECT id, name, department
FROM employees
WHERE name NOT LIKE 'A%';

-- Universal case-insensitive technique (works on all SQL engines):
SELECT name, city
FROM employees
WHERE LOWER(city) LIKE '%york%';

-- Output: Alice Martin (New York), Charlie Brown (New York)
SQL Master Β· Beginner Series Pg 70
CH 10 Mistakes + Recap and Practice
Part 6 of 6

Mistakes + Recap and Practice

A very common beginner blunder is using the equality operator (=) with wildcard characters, such as writing WHERE name = 'A%'. The equal sign looks for a person whose literal name is the two characters 'A' followed by a percent sign, which will return nothing! Always use the keyword LIKE whenever your search pattern contains % or _. Another mistake is forgetting quotation marks around pattern strings.

Key Points
βœ“ Always use LIKE with wildcards (% and _), never the equal sign (=).
βœ“ Always enclose the pattern in single quotes: LIKE '%text%', not LIKE %text%.
βœ“ Remember that % matches zero or more characters, while _ matches exactly one character.
βœ“ Extensive use of leading wildcards like '%text' can be slow on very large tables without full-text indexes.
Real-Life Example
Imagine using a metal detector: if you turn off the sensor and only look with your eyes, you won't find coins buried under the sand. The LIKE operator turns on the pattern sensor; the equal sign does not.
Remember / Pro Tip
Recap: LIKE enables pattern matching; % matches any length; _ matches one character; never use = with wildcards.
SQL Example
-- Practice 1: Find employees whose name starts with 'D'
-- Answer:
SELECT * FROM employees WHERE name LIKE 'D%';

-- Practice 2: Find employees whose name ends with 'n'
-- Answer:
SELECT * FROM employees WHERE name LIKE '%n';

-- Practice 3: Find employees whose department contains 'a'
-- Answer:
SELECT * FROM employees WHERE department LIKE '%a%';
SQL Master Β· Beginner Series Pg 71
CHAPTER {{ n.chapter_number|stringformat:"02d" }} 5 Parts

DISTINCT

{{ n.short_description|default:"Essential SQL syntax rules, practical queries, step-by-step explanations, and best practices." }}

Topics in this chapter:
  • 1 The Duplicate Problem
  • 2 DISTINCT Syntax and Example
  • 3 DISTINCT on Multiple Columns
  • 4 Count Unique Values (Preview of COUNT)
  • 5 Mistakes + Recap and Practice
CH 11 The Duplicate Problem
Part 1 of 5

The Duplicate Problem

When you query a single column from a table, SQL returns the value from every single row by default, even if the exact same value appears dozens of times. For example, if you ask for all departments from an employee table with eight people, 'IT' might appear three times and 'HR' twice. While this raw output accurately reflects the table, it makes answering simple questions like 'What departments exist?' frustratingly messy.

Key Points
βœ“ SQL queries return duplicate values by default whenever rows share identical values.
βœ“ Seeing duplicates clutters reports and obscures the true variety of data in a column.
βœ“ Business analysts frequently need unique lists of categories, locations, or statuses.
βœ“ Eliminating duplicates manually from thousands of rows is tedious and error-prone.
βœ“ SQL provides the DISTINCT keyword specifically to remove redundant duplicates automatically.
Real-Life Example
Imagine asking a teacher: 'What countries are the students in your classroom from?' You want a clean list like: 'Canada, Mexico, and Japan.' You do not want the teacher chanting 'Canada, Canada, Canada, Mexico, Canada, Japan!'
Remember / Pro Tip
Raw column queries show every row's value; DISTINCT condenses identical rows into a single unique mention.
SQL Example
-- Without DISTINCT: Shows duplicate departments
SELECT department
FROM employees;
-- Output: IT, HR, Sales, IT, Finance, Sales, HR, IT (8 rows, duplicates!)

-- With DISTINCT: Shows only unique departments
SELECT DISTINCT department
FROM employees;
-- Output: IT, HR, Sales, Finance (4 clean unique rows)
SQL Master Β· Beginner Series Pg 73
CH 11 DISTINCT Syntax and Example
Part 2 of 5

DISTINCT Syntax and Example

The DISTINCT keyword is placed immediately after the SELECT keyword and before the column names you wish to retrieve. When the database engine processes this instruction, it scans the matching rows, sorts or hashes the results, and discards all subsequent duplicate entries. The result set displays each distinct value exactly once.

Key Points
βœ“ Syntax pattern: SELECT DISTINCT column_name FROM table_name;
βœ“ DISTINCT must appear directly after SELECT, before any column names.
βœ“ You do not put parentheses around the column name in standard SQL.
βœ“ DISTINCT operates on the final output rows after filtering with WHERE.
βœ“ It works on text, numbers, dates, and any standard SQL data type.
Real-Life Example
Imagine taking a roll call of guests at a large wedding reception to compile a list of hometowns represented. As guests call out their cities, you only write each city name once on your clipboard.
Remember / Pro Tip
Place DISTINCT right after SELECT: writing SELECT column DISTINCT FROM table is a syntax error.
SQL Example
-- Find all unique cities where employees live
SELECT DISTINCT city
FROM employees;

-- Output:
-- | city     |
-- | New York |
-- | Chicago  |
-- | Austin   |
-- | Miami    |
-- (8 employees condensed into 4 unique cities)
SQL Master Β· Beginner Series Pg 74
CH 11 DISTINCT on Multiple Columns
Part 3 of 5

DISTINCT on Multiple Columns

When you specify multiple columns after SELECT DISTINCT, SQL evaluates the entire combination of columns together as a single unit. A row is only considered a duplicate and eliminated if every single column listed has identical values to another row. If even one column differs between two rows, both rows are kept in the final output.

Key Points
βœ“ DISTINCT applies to the entire row of selected columns, not just the first column.
βœ“ Rows are only filtered out if the combination of all listed columns is identical.
βœ“ SELECT DISTINCT department, city looks for unique department-and-city pairs.
βœ“ If IT has employees in both New York and Austin, both pairs are displayed.
βœ“ This is invaluable for finding unique combinations such as customer-product pairings.
Real-Life Example
Imagine cataloging car models by Make and Color. A red sedan and a blue sedan share the same body type, but their combination of (sedan, color) is distinct, so both remain on your showroom list.
Remember / Pro Tip
DISTINCT is not a function that applies to one column; it acts on the entire combination of selected columns.
SQL Example
-- Find all unique department and city combinations
SELECT DISTINCT department, city
FROM employees;

-- Output:
-- | department | city     |
-- | IT         | New York |
-- | HR         | Chicago  |
-- | Sales      | New York |
-- | IT         | Austin   |
-- | Finance    | Chicago  |
-- | Sales      | Miami    |
-- | HR         | Austin   |
-- | IT         | Miami    |
SQL Master Β· Beginner Series Pg 75
CH 11 Count Unique Values (Preview of COUNT)
Part 4 of 5

Count Unique Values (Preview of COUNT)

In real-world reporting, business leaders frequently ask 'How many unique departments do we have?' rather than asking to see the names written out. You can combine the DISTINCT keyword with SQL's COUNT aggregate function to calculate the exact number of unique values in a column. Wrapping DISTINCT inside COUNT gives you an instant numeric summary.

Key Points
βœ“ Syntax pattern: SELECT COUNT(DISTINCT column_name) FROM table_name;
βœ“ Here, DISTINCT is placed inside the parentheses of the COUNT function.
βœ“ The database first filters the column down to unique values, then counts them.
βœ“ Any NULL values in the column are automatically ignored during the count.
βœ“ This is one of the most widely used metric queries in business intelligence and dashboards.
Real-Life Example
Imagine an online retail store reviewing web traffic. They do not just want to know that 10,000 page views occurred; they want to know how many distinct visitors (COUNT DISTINCT user_id) visited the site.
Remember / Pro Tip
Write COUNT(DISTINCT column) inside parentheses: writing DISTINCT COUNT(column) will count all rows first.
SQL Example
-- Count total rows vs unique departments
SELECT 
    COUNT(department) AS total_department_entries,
    COUNT(DISTINCT department) AS unique_departments,
    COUNT(DISTINCT city) AS unique_cities
FROM employees;

-- Output:
-- | total_department_entries | unique_departments | unique_cities |
-- |                        8 |                  4 |             4 |
SQL Master Β· Beginner Series Pg 76
CH 11 Mistakes + Recap and Practice
Part 5 of 5

Mistakes + Recap and Practice

A frequent mistake among beginners is believing that DISTINCT only applies to the first column written after SELECT. Beginners will write SELECT DISTINCT department, salary expecting only departments to be deduplicated, but SQL treats the pair (department, salary) as the uniqueness key. Another common mistake is placing DISTINCT after FROM or WHERE, which results in an immediate syntax error.

Key Points
βœ“ DISTINCT must always appear immediately after SELECT: SELECT DISTINCT ...
βœ“ It evaluates the combination of all requested columns together.
βœ“ DISTINCT requires the database engine to sort or hash data, which can take time on huge tables.
βœ“ Only use DISTINCT when you actually need unique rows; do not add it out of habit.
Real-Life Example
Imagine sorting laundry by socks: if you sort by color alone, you get 3 piles. If you sort by (color, size), you get 8 piles. Adding columns to DISTINCT increases the number of unique combinations.
Remember / Pro Tip
Recap: DISTINCT removes duplicates, applies across all selected columns, and pairs with COUNT for metrics.
SQL Example
-- Practice 1: List all distinct cities where employees live
-- Answer:
SELECT DISTINCT city FROM employees;

-- Practice 2: List all distinct departments in the company
-- Answer:
SELECT DISTINCT department FROM employees;

-- Practice 3: Count how many distinct cities employees reside in
-- Answer:
SELECT COUNT(DISTINCT city) FROM employees;
SQL Master Β· Beginner Series Pg 77
CHAPTER {{ n.chapter_number|stringformat:"02d" }} 6 Parts

ORDER BY

{{ n.short_description|default:"Essential SQL syntax rules, practical queries, step-by-step explanations, and best practices." }}

Topics in this chapter:
  • 1 What is ORDER BY?
  • 2 ASC (Ascending Sort)
  • 3 DESC (Descending Sort)
  • 4 Sort by Multiple Columns
  • 5 Sorting Text and Dates
  • 6 Mistakes + Recap and Practice
CH 12 What is ORDER BY?
Part 1 of 6

What is ORDER BY?

By default, relational databases do not guarantee any particular order for rows returned by a query. Rows are stored wherever disk space is available, meaning results can appear in unpredictable sequences unless you explicitly tell the database how to arrange them. The ORDER BY clause instructs the database engine to sort the final result set before displaying it on your screen.

Key Points
βœ“ Relational databases store and retrieve rows in an unspecified order by default.
βœ“ The ORDER BY clause sorts output rows based on one or more columns.
βœ“ ORDER BY is placed near the end of your query, right after the WHERE clause.
βœ“ You can sort data in ascending order (A-Z, lowest to highest) or descending order (Z-A, highest to lowest).
βœ“ Sorting happens as the very last processing step before results are presented.
Real-Life Example
Imagine receiving a shuffled deck of playing cards. Before playing, you arrange them neatly in order from Ace up to King by suit. The ORDER BY clause is your personal deck organizer for database tables.
Remember / Pro Tip
Never assume rows will come out sorted by ID; always use ORDER BY whenever order matters to you or your users.
SQL Example
-- Sorting employees by salary from lowest to highest
SELECT id, name, department, salary
FROM employees
ORDER BY salary;

-- Output: George Clark (48000), Bob Smith (52000) ... up to Diana Prince (82000)
SQL Master Β· Beginner Series Pg 79
CH 12 ASC (Ascending Sort)
Part 2 of 6

ASC (Ascending Sort)

The ASC keyword sorts query results in ascending order, which means smallest to largest for numbers, chronological order from oldest to newest for dates, and alphabetical order from A to Z for text. Because ascending order is the default sorting behavior in SQL, omitting the ASC keyword produces the exact same sorted outcome.

Key Points
βœ“ ASC stands for Ascending order.
βœ“ Numbers sort from smallest to largest: 1, 2, 3, 10, 100.
βœ“ Text strings sort alphabetically from A to Z: Alice, Bob, Charlie.
βœ“ Dates sort from earliest calendar date to latest date.
βœ“ Because ASC is the default, ORDER BY salary is identical to ORDER BY salary ASC.
Real-Life Example
Think of an English dictionary or an encyclopedia: words are arranged in ascending alphabetical order from A to Z so that readers can quickly find entries.
Remember / Pro Tip
While ASC is optional, writing it explicitly makes your intentions clear to other developers reading your SQL.
SQL Example
-- Explicitly sorting employees alphabetically by name in ascending order
SELECT id, name, department, city
FROM employees
ORDER BY name ASC;

-- Output:
-- | id | name            | department | city     |
-- |  1 | Alice Martin    | IT         | New York |
-- |  2 | Bob Smith       | HR         | Chicago  |
-- |  3 | Charlie Brown   | Sales      | New York |
-- |  4 | Diana Prince    | IT         | Austin   |
-- |  5 | Evan Wright     | Finance    | Chicago  |
-- |  6 | Fiona Gallagher | Sales      | Miami    |
-- |  7 | George Clark    | HR         | Austin   |
-- |  8 | Hannah Abbott   | IT         | Miami    |
SQL Master Β· Beginner Series Pg 80
CH 12 DESC (Descending Sort)
Part 3 of 6

DESC (Descending Sort)

The DESC keyword sorts query results in descending order, reversing the default sequence completely. When you sort numbers with DESC, the largest number appears first and the smallest appears last. For text, words are arranged from Z down to A, and for dates, the newest calendar dates appear before older ones. This is the primary tool for creating leaderboards and ranking top earners.

Key Points
βœ“ DESC stands for Descending order.
βœ“ Numbers sort from largest down to smallest: 100, 10, 3, 2, 1.
βœ“ Text strings sort in reverse alphabetical order from Z down to A.
βœ“ Dates sort from newest (most recent) down to oldest.
βœ“ Unlike ASC, the DESC keyword is never optional; you must write DESC explicitly.
Real-Life Example
Imagine looking at a leaderboard in a video game or sports tournament. The player with the highest score sits at the very top of the screen in position number 1, with lower scores listed beneath.
Remember / Pro Tip
Whenever you want to find the 'top', 'highest', 'most expensive', or 'newest' records, sort using DESC.
SQL Example
-- Ranking employees from highest paid to lowest paid
SELECT id, name, department, salary
FROM employees
ORDER BY salary DESC;

-- Output:
-- | id | name            | department | salary |
-- |  4 | Diana Prince    | IT         |  82000 |
-- |  1 | Alice Martin    | IT         |  75000 |
-- |  8 | Hannah Abbott   | IT         |  71000 |
-- |  5 | Evan Wright     | Finance    |  68000 |
-- |  3 | Charlie Brown   | Sales      |  61000 |
-- |  6 | Fiona Gallagher | Sales      |  59000 |
-- |  2 | Bob Smith       | HR         |  52000 |
-- |  7 | George Clark    | HR         |  48000 |
SQL Master Β· Beginner Series Pg 81
CH 12 Sort by Multiple Columns
Part 4 of 6

Sort by Multiple Columns

In many situations, sorting by a single column produces ties where multiple rows share the exact same value. For example, if you sort employees by department, there will be three rows with 'IT'. You can specify multiple columns in your ORDER BY clause, separated by commas, to create secondary and tertiary tie-breakers.

Key Points
βœ“ Separate multiple sort columns with commas: ORDER BY col1, col2.
βœ“ SQL sorts by the first column first; ties are then resolved by the second column.
βœ“ Each column can have its own individual sorting direction (ASC or DESC).
βœ“ ORDER BY department ASC, salary DESC groups departments A-Z, with top earners first inside each department.
βœ“ The column order in ORDER BY determines sorting priority.
Real-Life Example
Think of an Olympic medal table: countries are sorted first by Gold medals. If two countries have the same number of Golds, ties are broken by Silver medals, and then by Bronze medals.
Remember / Pro Tip
You can mix directions freely: ORDER BY department ASC, salary DESC sorts departments A-Z, then salaries high-low.
SQL Example
-- Group by department alphabetically, then rank by salary descending
SELECT name, department, salary
FROM employees
ORDER BY department ASC, salary DESC;

-- Output:
-- Finance: Evan Wright (68000)
-- HR:      Bob Smith (52000), George Clark (48000)
-- IT:      Diana Prince (82000), Alice Martin (75000), Hannah Abbott (71000)
-- Sales:   Charlie Brown (61000), Fiona Gallagher (59000)
SQL Master Β· Beginner Series Pg 82
CH 12 Sorting Text and Dates
Part 5 of 6

Sorting Text and Dates

Sorting text and dates follows clear rules that every SQL developer should understand. Text is sorted according to character encoding (alphabetical order), but numbers stored as text strings sort alphabetically rather than numerically (e.g., '10' comes before '2'). Dates stored in proper DATE format sort chronologically without any formatting issues.

Key Points
βœ“ Proper DATE columns sort by actual calendar time, not alphabetical letter order.
βœ“ Numbers stored in VARCHAR columns sort alphabetically: '1', '10', '2', '20'.
βœ“ Always store numeric data in INT or DECIMAL types so ORDER BY sorts values numerically.
βœ“ In MySQL, NULL values sort first in ASC order and last in DESC order.
βœ“ In PostgreSQL and Oracle, you can explicitly state NULLS FIRST or NULLS LAST.
Real-Life Example
Imagine sorting file folders labeled 'Chapter 1', 'Chapter 2', and 'Chapter 10'. If your computer treats them as plain text, Chapter 10 will mistakenly appear before Chapter 2 on your screen.
Remember / Pro Tip
Always use proper numeric and date data types so ORDER BY sorts your values by their true real-world order.
SQL Example
-- Sorting text alphabetically by city, then by employee name
SELECT city, name, department
FROM employees
ORDER BY city ASC, name ASC;

-- Output:
-- Austin:   Diana Prince, George Clark
-- Chicago:  Bob Smith, Evan Wright
-- Miami:    Fiona Gallagher, Hannah Abbott
-- New York: Alice Martin, Charlie Brown
SQL Master Β· Beginner Series Pg 83
CH 12 Mistakes + Recap and Practice
Part 6 of 6

Mistakes + Recap and Practice

A common beginner mistake is placing the ORDER BY clause before the WHERE clause. SQL enforces a strict clause order: SELECT comes first, followed by FROM, then WHERE, and finally ORDER BY. Another frequent mistake is writing DESC after the first column and expecting all subsequent columns to be descending; each column requires its own explicit DESC keyword if you want descending order.

Key Points
βœ“ Clause order is strictly enforced: SELECT -> FROM -> WHERE -> ORDER BY.
βœ“ Each column needs its own DESC keyword if you want descending on both: ORDER BY col1 DESC, col2 DESC.
βœ“ Avoid sorting by column numbers (e.g. ORDER BY 2) in production code; use column names.
βœ“ Sorting huge datasets without proper database indexes can slow down query response times.
Real-Life Example
Imagine assembling a burger: you cannot put the patty on the table before the bottom bun. In SQL, you cannot sort rows (ORDER BY) before choosing where they come from (FROM) or filtering them (WHERE).
Remember / Pro Tip
Recap: ORDER BY sorts results; ASC is default low-to-high; DESC is high-to-low; always place ORDER BY at the end.
SQL Example
-- Practice 1: Sort all employees by salary from highest to lowest
-- Answer:
SELECT * FROM employees ORDER BY salary DESC;

-- Practice 2: Sort employees alphabetically by city
-- Answer:
SELECT * FROM employees ORDER BY city ASC;

-- Practice 3: Find IT employees and sort them by salary descending
-- Answer:
SELECT * FROM employees WHERE department = 'IT' ORDER BY salary DESC;
SQL Master Β· Beginner Series Pg 84
CHAPTER {{ n.chapter_number|stringformat:"02d" }} 5 Parts

LIMIT

{{ n.short_description|default:"Essential SQL syntax rules, practical queries, step-by-step explanations, and best practices." }}

Topics in this chapter:
  • 1 What is LIMIT?
  • 2 LIMIT Syntax and Example
  • 3 Top N Queries (ORDER BY + LIMIT)
  • 4 OFFSET and Pagination
  • 5 Mistakes + Recap and SQL Dialects
CH 13 What is LIMIT?
Part 1 of 5

What is LIMIT?

The LIMIT clause restricts the maximum number of rows that a query returns to your screen or application. Real-world database tables often contain hundreds of thousands or even millions of records. Asking the database to transfer every single record across a network would freeze your application and crash user browsers, making LIMIT an essential performance tool.

Key Points
βœ“ LIMIT specifies the maximum row count to return from a query.
βœ“ It prevents client applications from freezing when querying massive tables.
βœ“ LIMIT is placed at the very end of your SQL query after ORDER BY.
βœ“ It provides a quick way to inspect table contents without pulling huge datasets.
βœ“ Combined with sorting, LIMIT enables top-performer and leaderboard queries.
Real-Life Example
Imagine asking a search engine like Google for recipes. You do not want 20 million matching web pages dumped onto a single endless screen; you want to see just the top 10 most relevant results first.
Remember / Pro Tip
Always use LIMIT when testing queries on live production tables to avoid freezing the database with millions of rows.
SQL Example
-- Returning only the first 3 rows from the employees table
SELECT id, name, department, salary
FROM employees
LIMIT 3;

-- Output:
-- | id | name          | department | salary |
-- |  1 | Alice Martin  | IT         |  75000 |
-- |  2 | Bob Smith     | HR         |  52000 |
-- |  3 | Charlie Brown | Sales      |  61000 |
SQL Master Β· Beginner Series Pg 86
CH 13 LIMIT Syntax and Example
Part 2 of 5

LIMIT Syntax and Example

The LIMIT clause is one of the simplest clauses in all of SQL to write. You append the keyword LIMIT followed by a positive integer to the very end of your query. The database engine retrieves records as usual, but the moment it reaches the specified number of rows, it immediately stops scanning and delivers the results.

Key Points
βœ“ Syntax pattern: SELECT columns FROM table LIMIT number;
βœ“ The limit number must always be a non-negative whole integer.
βœ“ If the table contains fewer rows than the limit, SQL returns all available rows without error.
βœ“ LIMIT is supported natively by MySQL, PostgreSQL, SQLite, and MariaDB.
βœ“ It executes after WHERE filters and ORDER BY sorting have completed.
Real-Life Example
Imagine walking into a bakery with a box designed to hold exactly six pastries. As soon as the clerk places six pastries into your box, the transaction stops, even though the bakery has hundreds more on display.
Remember / Pro Tip
Place LIMIT as the final keyword of your query: writing LIMIT before WHERE or FROM causes a syntax error.
SQL Example
-- Retrieve only 4 employees who work in IT or Sales
SELECT id, name, department, city
FROM employees
WHERE department IN ('IT', 'Sales')
LIMIT 4;

-- Output:
-- | id | name            | department | city     |
-- |  1 | Alice Martin    | IT         | New York |
-- |  3 | Charlie Brown   | Sales      | New York |
-- |  4 | Diana Prince    | IT         | Austin   |
-- |  6 | Fiona Gallagher | Sales      | Miami    |
SQL Master Β· Beginner Series Pg 87
CH 13 Top N Queries (ORDER BY + LIMIT)
Part 3 of 5

Top N Queries (ORDER BY + LIMIT)

The true power of the LIMIT clause appears when you pair it with the ORDER BY clause. This combination allows you to answer the classic business question known as a 'Top N query', such as 'Who are our top 3 highest-earning employees?' By sorting your records first and then truncating the list with LIMIT, you create leaderboards with mathematical certainty.

Key Points
βœ“ Pairing ORDER BY with LIMIT produces exact top or bottom rankings.
βœ“ ORDER BY salary DESC LIMIT 3 finds the top 3 highest-paid individuals.
βœ“ ORDER BY salary ASC LIMIT 3 finds the 3 lowest-paid individuals.
βœ“ Sorting happens before LIMIT: SQL sorts all matching rows first, then returns the top subset.
βœ“ Without ORDER BY, LIMIT returns an unpredictable, arbitrary group of rows.
Real-Life Example
Think of an awards podium at the Olympics: officials sort all athletes by their race completion times and then give medals only to the top 3 finishers, ignoring the rest of the field.
Remember / Pro Tip
Never write a LIMIT query for rankings without ORDER BY, or your 'top' results will just be random rows!
SQL Example
-- Find the top 3 highest-earning employees in the company
SELECT id, name, department, salary
FROM employees
ORDER BY salary DESC
LIMIT 3;

-- Output:
-- | id | name          | department | salary |
-- |  4 | Diana Prince  | IT         |  82000 |
-- |  1 | Alice Martin  | IT         |  75000 |
-- |  8 | Hannah Abbott | IT         |  71000 |
SQL Master Β· Beginner Series Pg 88
CH 13 OFFSET and Pagination
Part 4 of 5

OFFSET and Pagination

When building web applications, pagination divides massive lists of data into discrete pages (e.g., Page 1, Page 2, Page 3). The OFFSET clause tells the database how many rows to skip before it begins returning results for LIMIT. By adjusting the OFFSET value, your application can effortlessly serve consecutive pages of records to users.

Key Points
βœ“ OFFSET specifies how many matching rows to skip before returning data.
βœ“ Syntax pattern: SELECT columns FROM table LIMIT count OFFSET skip_count.
βœ“ MySQL shorthand: LIMIT skip_count, count (skips skip_count, returns count rows).
βœ“ Page 1: LIMIT 3 OFFSET 0 (rows 1-3).
βœ“ Page 2: LIMIT 3 OFFSET 3 (rows 4-6).
βœ“ Page 3: LIMIT 3 OFFSET 6 (rows 7-8).
Real-Life Example
Imagine reading a book: when you finish reading pages 1 to 3, you flip forward to start reading page 4. The OFFSET clause tells the database to skip the first 3 pages and start reading from page 4.
Remember / Pro Tip
Pagination formula: OFFSET = (page_number - 1) * page_size. For page 2 with size 10, OFFSET is (2-1)*10 = 10.
SQL Example
-- Page 1: Top 3 earners (skip 0)
SELECT name, salary FROM employees ORDER BY salary DESC LIMIT 3 OFFSET 0;
-- Diana Prince (82000), Alice Martin (75000), Hannah Abbott (71000)

-- Page 2: Next 3 earners (skip 3)
SELECT name, salary FROM employees ORDER BY salary DESC LIMIT 3 OFFSET 3;
-- Evan Wright (68000), Charlie Brown (61000), Fiona Gallagher (59000)

-- Page 3: Final 2 earners (skip 6)
SELECT name, salary FROM employees ORDER BY salary DESC LIMIT 3 OFFSET 6;
-- Bob Smith (52000), George Clark (48000)
SQL Master Β· Beginner Series Pg 89
CH 13 Mistakes + Recap and SQL Dialects
Part 5 of 5

Mistakes + Recap and SQL Dialects

While LIMIT is standard across MySQL, PostgreSQL, and SQLite, different database management systems use alternative dialect keywords for row restriction. Microsoft SQL Server uses TOP at the beginning of the SELECT clause, while Oracle Database traditionally uses FETCH FIRST rows. Knowing these differences prevents confusion when switching between database platforms.

Key Points
βœ“ MySQL, PostgreSQL, and SQLite use: LIMIT n OFFSET m.
βœ“ Microsoft SQL Server uses: SELECT TOP n columns FROM table.
βœ“ Oracle and modern ANSI SQL use: FETCH FIRST n ROWS ONLY.
βœ“ A common mistake is placing LIMIT before WHERE; LIMIT must always come last.
βœ“ High OFFSET values on tables with millions of rows can become slow; consider keyset pagination.
Real-Life Example
Think of travel power adapters: in the USA, electrical plugs have flat prongs, while in Europe they have round pins. Both deliver electricity, just as LIMIT, TOP, and FETCH FIRST all restrict query row counts.
Remember / Pro Tip
Recap: LIMIT caps rows, OFFSET skips rows, pair with ORDER BY for rankings, and remember SQL Server uses TOP.
SQL Example
-- Dialect Comparison Cheat Sheet:
-- MySQL / Postgres / SQLite:
SELECT name, salary FROM employees ORDER BY salary DESC LIMIT 5;

-- SQL Server (T-SQL):
-- SELECT TOP 5 name, salary FROM employees ORDER BY salary DESC;

-- Oracle (12c+ / ANSI Standard):
-- SELECT name, salary FROM employees ORDER BY salary DESC FETCH FIRST 5 ROWS ONLY;

-- Practice: Find the single lowest paid employee
-- Answer: SELECT * FROM employees ORDER BY salary ASC LIMIT 1;
SQL Master Β· Beginner Series Pg 90
CHAPTER {{ n.chapter_number|stringformat:"02d" }} 7 Parts

Aggregate Functions

{{ n.short_description|default:"Essential SQL syntax rules, practical queries, step-by-step explanations, and best practices." }}

Topics in this chapter:
  • 1 What are Aggregate Functions?
  • 2 The COUNT Function
  • 3 The SUM Function
  • 4 The AVG Function
  • 5 MIN and MAX
  • 6 Aggregates with WHERE
  • 7 Mistakes + Recap and NULL Behavior
CH 14 What are Aggregate Functions?
Part 1 of 7

What are Aggregate Functions?

Aggregate functions perform a calculation on a set of values across multiple rows and return a single summarizing value. Rather than displaying raw individual employee salaries, business executives often need the total payroll, the company-wide average salary, or the total employee count. SQL provides five primary aggregate functions to calculate these vital summary metrics instantly.

Key Points
βœ“ Aggregate functions take multiple values from a column and return a single result.
βœ“ The five core functions are COUNT, SUM, AVG, MIN, and MAX.
βœ“ They operate vertically down a column across all matching rows.
βœ“ They summarize data to answer executive-level business questions.
βœ“ Aggregate functions automatically ignore NULL values (except COUNT(*)).
Real-Life Example
Imagine a sports referee at the end of a match. Instead of listing every individual pass, tackle, and foul made by players, the referee announces the final aggregate score: 3 goals to 1.
Remember / Pro Tip
Aggregate functions collapse multiple input rows into a single summary number.
SQL Example
-- Running all 5 aggregate functions together on our employees table
SELECT 
    COUNT(*) AS total_staff,
    SUM(salary) AS total_payroll,
    AVG(salary) AS average_salary,
    MIN(salary) AS lowest_salary,
    MAX(salary) AS highest_salary
FROM employees;

-- Output:
-- | total_staff | total_payroll | average_salary | lowest_salary | highest_salary |
-- |           8 |        516000 |       64500.00 |         48000 |          82000 |
SQL Master Β· Beginner Series Pg 92
CH 14 The COUNT Function
Part 2 of 7

The COUNT Function

The COUNT function tallies the number of rows that match your query criteria. You can use COUNT(*) to count all rows regardless of content, or COUNT(column_name) to count only rows where that specific column contains a non-NULL value. It is one of the most frequently executed functions in backend development for checking inventory counts and user totals.

Key Points
βœ“ COUNT(*) counts all matching rows in the table, including rows containing NULLs.
βœ“ COUNT(column_name) counts only rows where the specified column is NOT NULL.
βœ“ COUNT(DISTINCT column) counts the number of unique non-NULL values.
βœ“ COUNT always returns a whole integer (0 or greater).
βœ“ It is commonly combined with WHERE to count specific categories of records.
Real-Life Example
Imagine an airplane flight attendant clicking a handheld tally counter as passengers board the aircraft. Every time a person steps through the door, the counter clicks up by one until everyone is seated.
Remember / Pro Tip
Use COUNT(*) when you want total row count, and COUNT(column) when you specifically want to ignore NULLs.
SQL Example
-- Counting total employees vs employees in the IT department
SELECT 
    COUNT(*) AS total_employees,
    COUNT(CASE WHEN department = 'IT' THEN 1 END) AS it_employees
FROM employees;

-- Output:
-- | total_employees | it_employees |
-- |               8 |            3 |

-- Simple direct count with WHERE:
SELECT COUNT(*) AS miami_staff FROM employees WHERE city = 'Miami';
-- Output: 2
SQL Master Β· Beginner Series Pg 93
CH 14 The SUM Function
Part 3 of 7

The SUM Function

The SUM function calculates the mathematical total of all values in a numeric column. It adds together every number across matching rows and returns the grand total as a single value. SUM can only be used on numeric columns such as integers and decimals; attempting to calculate the SUM of text strings or dates causes an error.

Key Points
βœ“ SUM calculates the total sum of all values in a numeric column.
βœ“ It only works on numeric data types (INT, DECIMAL, FLOAT).
βœ“ NULL values are automatically ignored and treated as zero in the calculation.
βœ“ If all values in the column are NULL, SUM returns NULL.
βœ“ It is widely used to calculate financial totals such as revenue, expenses, and payroll.
Real-Life Example
Imagine a cash register tape at a grocery checkout counter. As items are scanned, the register adds the price of each item to produce the final grand total you pay at the terminal.
Remember / Pro Tip
Never pass text columns to SUM: SUM('Alice') is invalid and will immediately produce a database error.
SQL Example
-- Calculate the total monthly salary expense for the IT department
SELECT SUM(salary) AS total_it_payroll
FROM employees
WHERE department = 'IT';

-- Calculation:
-- Alice Martin (75000) + Diana Prince (82000) + Hannah Abbott (71000) = 228000
-- Output:
-- | total_it_payroll |
-- |           228000 |
SQL Master Β· Beginner Series Pg 94
CH 14 The AVG Function
Part 4 of 7

The AVG Function

The AVG function calculates the arithmetic mean of all numeric values in a column. It works internally by summing up all non-NULL values and then dividing that sum by the count of non-NULL rows. The resulting average is typically returned as a decimal number with floating-point precision, making aliases and rounding functions useful for clean display.

Key Points
βœ“ AVG computes the arithmetic mean: sum of values divided by count of values.
βœ“ It operates strictly on numeric columns.
βœ“ NULL values are completely ignored and do NOT lower the average count divisor.
βœ“ The result is usually a floating-point decimal number (e.g. 64500.00).
βœ“ You can pair AVG with the ROUND() function to format decimals to two decimal places.
Real-Life Example
Imagine calculating a student's grade point average across four exams with scores 80, 90, 85, and 95. You add the scores together (350) and divide by the number of exams (4) to get the average score of 87.5.
Remember / Pro Tip
Remember that AVG ignores NULLs: if 4 people earn 100 and 1 has NULL, AVG is 100/4 = 25, not 100/5 = 20!
SQL Example
-- Calculate the average salary across all employees, rounded to 2 decimal places
SELECT 
    AVG(salary) AS raw_average,
    ROUND(AVG(salary), 2) AS clean_average
FROM employees;

-- Calculation: Total salary 516000 / 8 employees = 64500.00
-- Output:
-- | raw_average | clean_average |
-- |    64500.00 |      64500.00 |
SQL Master Β· Beginner Series Pg 95
CH 14 MIN and MAX
Part 5 of 7

MIN and MAX

The MIN and MAX functions find the extreme values in a column: MIN returns the lowest value, while MAX returns the highest value. Unlike SUM and AVG, which only work with numbers, MIN and MAX work seamlessly across numbers, text strings (alphabetical first and last), and dates (earliest and latest calendar dates).

Key Points
βœ“ MIN finds the smallest number, earliest date, or alphabetically first string.
βœ“ MAX finds the largest number, latest date, or alphabetically last string.
βœ“ Both functions automatically ignore NULL values.
βœ“ MIN(salary) finds the lowest paid employee's salary.
βœ“ MAX(name) finds the name closest to 'Z' in alphabetical ordering.
Real-Life Example
Imagine checking a weather forecast application for your city. The app prominently displays the day's predicted MIN temperature (e.g., 55Β°F) and MAX temperature (e.g., 78Β°F) so you know what jacket to wear.
Remember / Pro Tip
MIN and MAX work with text and dates too: MIN(name) returns 'Alice Martin', the first name alphabetically!
SQL Example
-- Finding the salary range and alphabetical extremes in the company
SELECT 
    MIN(salary) AS lowest_salary,
    MAX(salary) AS highest_salary,
    MIN(name) AS first_name_alpha,
    MAX(name) AS last_name_alpha
FROM employees;

-- Output:
-- | lowest_salary | highest_salary | first_name_alpha | last_name_alpha |
-- |         48000 |          82000 | Alice Martin     | Hannah Abbott   |
SQL Master Β· Beginner Series Pg 96
CH 14 Aggregates with WHERE
Part 6 of 7

Aggregates with WHERE

You can combine any aggregate function with a WHERE clause to calculate metrics for a specific subset of records. When a WHERE clause is present, the database engine filters rows first, keeping only those that pass the condition. The aggregate function then computes its calculation solely on the remaining filtered rows.

Key Points
βœ“ The WHERE clause filters rows BEFORE aggregate functions perform their calculation.
βœ“ Only rows that evaluate to TRUE in the WHERE clause are passed to the aggregate function.
βœ“ This allows targeted metrics like 'average salary of IT workers in Austin'.
βœ“ Syntax pattern: SELECT AGG_FUNC(col) FROM table WHERE condition;
βœ“ You can combine multiple conditions with AND and OR inside the WHERE clause.
Real-Life Example
Imagine a school principal calculating the average math test score, but only for students enrolled in the 10th grade. All other grades are filtered out before the class average is calculated.
Remember / Pro Tip
WHERE filters raw individual rows before aggregation occurs; it cannot filter aggregate results itself.
SQL Example
-- Calculate salary statistics specifically for the Sales department
SELECT 
    COUNT(*) AS sales_headcount,
    SUM(salary) AS total_sales_payroll,
    AVG(salary) AS avg_sales_salary
FROM employees
WHERE department = 'Sales';

-- Output:
-- | sales_headcount | total_sales_payroll | avg_sales_salary |
-- |               2 |              120000 |         60000.00 |
SQL Master Β· Beginner Series Pg 97
CH 14 Mistakes + Recap and NULL Behavior
Part 7 of 7

Mistakes + Recap and NULL Behavior

The single biggest mistake beginners make with aggregate functions is trying to mix individual row columns with aggregate functions without a GROUP BY clause, such as writing SELECT name, MAX(salary) FROM employees. SQL cannot return one summary salary next to eight different names without grouping instructions. Another vital rule is remembering how NULLs are handled: aggregates skip NULLs completely.

Key Points
βœ“ Never select individual column names alongside aggregate functions without GROUP BY.
βœ“ Aggregates ignore NULLs: COUNT(col), SUM(col), and AVG(col) do not count NULL rows.
βœ“ COUNT(*) is the only aggregate function that counts rows containing NULL values.
βœ“ If all rows in a column are NULL, SUM, AVG, MIN, and MAX return NULL, while COUNT returns 0.
Real-Life Example
Imagine a class of 5 students where 4 score 100 on a test and 1 student was absent (NULL). The average of the scores taken is 100. If you counted the absent student as 0, the average would unfairly drop to 80.
Remember / Pro Tip
Recap: COUNT tallies rows, SUM adds, AVG means, MIN/MAX find extremes; all ignore NULLs except COUNT(*).
SQL Example
-- WRONG: Mixing non-aggregated column with aggregate function!
-- SELECT name, AVG(salary) FROM employees; -- Error in standard SQL!

-- CORRECT: Use subquery or pure aggregate
SELECT AVG(salary) AS avg_salary FROM employees;

-- Practice 1: Find total headcount of employees in Chicago
-- Answer: SELECT COUNT(*) FROM employees WHERE city = 'Chicago';

-- Practice 2: Find the maximum salary in the HR department
-- Answer: SELECT MAX(salary) FROM employees WHERE department = 'HR';
SQL Master Β· Beginner Series Pg 98
CHAPTER {{ n.chapter_number|stringformat:"02d" }} 6 Parts

GROUP BY

{{ n.short_description|default:"Essential SQL syntax rules, practical queries, step-by-step explanations, and best practices." }}

Topics in this chapter:
  • 1 The Grouping Idea
  • 2 GROUP BY Syntax
  • 3 GROUP BY + COUNT
  • 4 GROUP BY + SUM / AVG
  • 5 Group by Multiple Columns
  • 6 Mistakes + Recap and Practice
CH 15 The Grouping Idea
Part 1 of 6

The Grouping Idea

In previous lessons, aggregate functions calculated a single summary number for the entire table. However, business leaders rarely want just one grand total; they want to see metrics broken down by category, such as 'What is the average salary in each department?' or 'How many employees live in each city?' The GROUP BY clause groups rows with identical values into summary buckets so aggregates run on each bucket independently.

Key Points
βœ“ GROUP BY collapses rows sharing identical values into distinct summary groups.
βœ“ Aggregate functions then calculate metrics for each separate group individually.
βœ“ It transforms detailed transaction rows into categorized management summaries.
βœ“ GROUP BY is placed immediately after the WHERE clause and before ORDER BY.
βœ“ Every unique value in the grouping column becomes a single output row.
Real-Life Example
Imagine sorting laundry into separate baskets: one basket for white clothes, one for darks, and one for colored garments. Once sorted into buckets, you can count the items or wash each basket independently.
Remember / Pro Tip
GROUP BY divides your table into categorical buckets so aggregate functions calculate metrics for each bucket.
SQL Example
-- Grouping employees by department to see headcount per department
SELECT department, COUNT(*) AS staff_count
FROM employees
GROUP BY department;

-- Output:
-- | department | staff_count |
-- | IT         |           3 |
-- | HR         |           2 |
-- | Sales      |           2 |
-- | Finance    |           1 |
SQL Master Β· Beginner Series Pg 100
CH 15 GROUP BY Syntax
Part 2 of 6

GROUP BY Syntax

The syntax of the GROUP BY clause requires careful attention to the columns listed in the SELECT line. Any non-aggregated column that appears in your SELECT list MUST also be included in your GROUP BY clause. If you select a column that is neither in GROUP BY nor wrapped inside an aggregate function, standard SQL will reject the query with an error.

Key Points
βœ“ Syntax pattern: SELECT group_col, AGG_FUNC(val_col) FROM table GROUP BY group_col;
βœ“ The Golden Rule: Every non-aggregate column in SELECT must be in GROUP BY.
βœ“ The grouping column creates the categories; the aggregate function computes the metric.
βœ“ You can sort the final grouped results by using ORDER BY at the end.
βœ“ GROUP BY processes rows after WHERE has filtered out unwanted records.
Real-Life Example
Imagine a school report card displaying class subjects. You cannot list student names next to overall class grade averages without saying which class group you are summarizing.
Remember / Pro Tip
The Golden Rule: If a column is in SELECT and has no aggregate function around it, it MUST be in GROUP BY!
SQL Example
-- Department-level salary summary with proper syntax
SELECT 
    department, 
    COUNT(*) AS total_employees,
    AVG(salary) AS average_salary
FROM employees
GROUP BY department
ORDER BY average_salary DESC;

-- Output:
-- | department | total_employees | average_salary |
-- | IT         |               3 |       76000.00 |
-- | Finance    |               1 |       68000.00 |
-- | Sales      |               2 |       60000.00 |
-- | HR         |               2 |       50000.00 |
SQL Master Β· Beginner Series Pg 101
CH 15 GROUP BY + COUNT
Part 3 of 6

GROUP BY + COUNT

Pairing GROUP BY with the COUNT function is the standard technique for building category breakdowns and distribution tables. Whether you are counting how many products belong to each category, how many orders each customer placed, or how many employees live in each city, this combination delivers concise, high-value business insights in two lines of SQL.

Key Points
βœ“ GROUP BY + COUNT tallies the number of rows belonging to each group.
βœ“ GROUP BY city with COUNT(*) reveals employee geographical distribution.
βœ“ Departments or categories with zero rows in the table will not appear in the results.
βœ“ You can sort the counts with ORDER BY COUNT(*) DESC to show largest groups first.
βœ“ Use column aliases like AS headcount to give the metric a professional name.
Real-Life Example
Imagine an election night tally where ballots are sorted into piles by candidate name. Once sorted, poll workers count the number of paper ballots in each candidate's pile to determine vote totals.
Remember / Pro Tip
Use ORDER BY COUNT(*) DESC with GROUP BY to instantly create ranked popularity or frequency charts.
SQL Example
-- Count how many employees reside in each city, sorted from most to least
SELECT city, COUNT(*) AS employee_count
FROM employees
GROUP BY city
ORDER BY employee_count DESC;

-- Output:
-- | city     | employee_count |
-- | New York |              2 |
-- | Chicago  |              2 |
-- | Austin   |              2 |
-- | Miami    |              2 |
SQL Master Β· Beginner Series Pg 102
CH 15 GROUP BY + SUM / AVG
Part 4 of 6

GROUP BY + SUM / AVG

Combining GROUP BY with financial functions like SUM and AVG enables deep departmental and regional financial analysis. Business leaders need to know which departments consume the largest share of corporate payroll, or which regional sales offices achieve the highest average transaction value. You can run multiple aggregates simultaneously on each group.

Key Points
βœ“ SUM inside GROUP BY calculates the total value per category (e.g. payroll by department).
βœ“ AVG inside GROUP BY calculates the typical average value per category.
βœ“ You can include COUNT, SUM, and AVG together in the same SELECT statement.
βœ“ All aggregates in the SELECT line evaluate within the boundaries of each group.
βœ“ Formatting averages with ROUND() keeps financial reports neat and readable.
Real-Life Example
Imagine an online marketplace calculating both total revenue (SUM) and average order value (AVG) for each product category like Electronics, Books, and Clothing to see which niche is most profitable.
Remember / Pro Tip
You can calculate multiple metrics for each group at the same time: COUNT, SUM, AVG, MIN, and MAX together!
SQL Example
-- Complete departmental financial breakdown
SELECT 
    department,
    COUNT(*) AS headcount,
    SUM(salary) AS total_department_payroll,
    ROUND(AVG(salary), 2) AS avg_department_salary
FROM employees
GROUP BY department;

-- Output:
-- | department | headcount | total_department_payroll | avg_department_salary |
-- | IT         |         3 |                   228000 |              76000.00 |
-- | HR         |         2 |                   100000 |              50000.00 |
-- | Sales      |         2 |                   120000 |              60000.00 |
-- | Finance    |         1 |                    68000 |              68000.00 |
SQL Master Β· Beginner Series Pg 103
CH 15 Group by Multiple Columns
Part 5 of 6

Group by Multiple Columns

You are not restricted to grouping by a single column; SQL allows you to group by two, three, or more columns simultaneously. When you specify multiple columns in your GROUP BY clause, SQL creates a distinct bucket for every unique combination of those column values. This allows you to explore subcategories, such as departmental staffing broken down city by city.

Key Points
βœ“ Separate multiple grouping columns with commas: GROUP BY department, city.
βœ“ SQL creates a group for each unique combination of the listed columns.
βœ“ Rows only combine if they share identical values in ALL specified grouping columns.
βœ“ All non-aggregate columns in SELECT must be present in the GROUP BY clause.
βœ“ This provides multi-dimensional matrix reporting directly from standard SQL queries.
Real-Life Example
Imagine organizing a school science fair by Grade level AND Category (e.g. Grade 9 Biology, Grade 9 Chemistry, Grade 10 Biology). Each distinct combination forms its own judging station.
Remember / Pro Tip
Grouping by two columns creates sub-groups: department + city shows how each department is staffed in each city.
SQL Example
-- Group by department AND city to see multi-level staffing
SELECT department, city, COUNT(*) AS staff_count
FROM employees
GROUP BY department, city
ORDER BY department, city;

-- Output:
-- | department | city     | staff_count |
-- | Finance    | Chicago  |           1 |
-- | HR         | Austin   |           1 |
-- | HR         | Chicago  |           1 |
-- | IT         | Austin   |           1 |
-- | IT         | Miami    |           1 |
-- | IT         | New York |           1 |
-- | Sales      | Miami    |           1 |
-- | Sales      | New York |           1 |
SQL Master Β· Beginner Series Pg 104
CH 15 Mistakes + Recap and Practice
Part 6 of 6

Mistakes + Recap and Practice

The most notorious error in SQL is selecting an unaggregated column that is omitted from the GROUP BY clause, such as SELECT department, name, AVG(salary) FROM employees GROUP BY department. Which employee's name should SQL display for IT when three different employees exist? The database engine refuses to guess and throws an error. Always verify that every raw column in SELECT appears in GROUP BY.

Key Points
βœ“ Every unaggregated column in SELECT MUST appear in GROUP BY.
βœ“ GROUP BY comes AFTER WHERE and BEFORE ORDER BY.
βœ“ WHERE filters rows BEFORE grouping occurs.
βœ“ Never use GROUP BY on columns with unique values (like Primary Key ID) unless intended.
Real-Life Example
Imagine asking: 'What is the average height of students in each classroom, and tell me the name of the student?' You cannot attach a single student's name to an entire room's average without ambiguity.
Remember / Pro Tip
Recap: GROUP BY creates category buckets; aggregates calculate per bucket; never leave raw columns out of GROUP BY.
SQL Example
-- WRONG: 'name' is neither aggregated nor in GROUP BY!
-- SELECT department, name, AVG(salary) FROM employees GROUP BY department;

-- CORRECT: Either aggregate name or remove it
SELECT department, COUNT(name) AS staff_count, AVG(salary) AS avg_sal
FROM employees
GROUP BY department;

-- Practice 1: Find total salary per city
-- Answer: SELECT city, SUM(salary) FROM employees GROUP BY city;

-- Practice 2: Find average salary per department sorted highest to lowest
-- Answer: SELECT department, AVG(salary) FROM employees GROUP BY department ORDER BY AVG(salary) DESC;
SQL Master Β· Beginner Series Pg 105
CHAPTER {{ n.chapter_number|stringformat:"02d" }} 5 Parts

HAVING

{{ n.short_description|default:"Essential SQL syntax rules, practical queries, step-by-step explanations, and best practices." }}

Topics in this chapter:
  • 1 Why WHERE Is Not Enough
  • 2 HAVING Syntax and Example
  • 3 WHERE vs HAVING (Side-by-Side)
  • 4 Full Query Order: The Complete Flow
  • 5 Mistakes + Final Recap and Practice
CH 16 Why WHERE Is Not Enough
Part 1 of 5

Why WHERE Is Not Enough

Beginners often try to filter grouped results using the WHERE clause, writing queries like WHERE AVG(salary) > 60000 or WHERE COUNT(*) >= 2. However, SQL immediately rejects these queries with an error. The reason lies in the strict order of execution: the WHERE clause evaluates individual rows BEFORE any groups are formed or aggregates are calculated. To filter aggregated group results, SQL created the HAVING clause.

Key Points
βœ“ WHERE filters individual records BEFORE rows are grouped together.
βœ“ Aggregate functions like AVG() and COUNT() do not exist yet when WHERE executes.
βœ“ Attempting to place an aggregate function in a WHERE clause causes a syntax error.
βœ“ The HAVING clause was created specifically to filter groups AFTER aggregation.
βœ“ HAVING acts like a second WHERE clause that operates exclusively on group summaries.
Real-Life Example
Imagine sorting fruit into crates: WHERE is inspecting each apple to throw away rotten ones before putting them in crates. HAVING is weighing the whole crate afterwards to reject crates lighter than 50 pounds.
Remember / Pro Tip
WHERE filters individual raw rows before grouping; HAVING filters aggregated groups after grouping.
SQL Example
-- WRONG: Cannot use aggregate function in WHERE!
-- SELECT department, COUNT(*) FROM employees WHERE COUNT(*) > 2 GROUP BY department;

-- CORRECT: Use HAVING to filter the aggregated group count
SELECT department, COUNT(*) AS staff_count
FROM employees
GROUP BY department
HAVING COUNT(*) > 2;

-- Output:
-- | department | staff_count |
-- | IT         |           3 |
SQL Master Β· Beginner Series Pg 107
CH 16 HAVING Syntax and Example
Part 2 of 5

HAVING Syntax and Example

The HAVING clause is written immediately after the GROUP BY clause and before the ORDER BY clause. Inside the HAVING clause, you write conditions that test aggregate functions such as COUNT(*), AVG(column), or SUM(column). If a group's calculated metric satisfies the HAVING condition, that group's summary row appears in the output; otherwise, the entire group is dropped.

Key Points
βœ“ Syntax pattern: SELECT col, AGG(val) FROM table GROUP BY col HAVING AGG(val) > limit;
βœ“ HAVING is positioned directly after GROUP BY and before ORDER BY.
βœ“ It tests aggregate calculations like HAVING AVG(salary) > 65000.
βœ“ You can combine multiple group conditions using AND and OR inside HAVING.
βœ“ Groups that fail the HAVING condition are omitted from the final result set.
Real-Life Example
Imagine an athletic league committee reviewing teams. The committee sets a rule: 'Only teams with an average player height over 6 feet (HAVING AVG(height) > 6) may participate in the tournament.'
Remember / Pro Tip
Place HAVING immediately after GROUP BY: it filters the summary rows produced by your grouping buckets.
SQL Example
-- Find departments whose average salary exceeds 60000
SELECT 
    department, 
    ROUND(AVG(salary), 2) AS average_salary,
    COUNT(*) AS headcount
FROM employees
GROUP BY department
HAVING AVG(salary) > 60000;

-- Output:
-- | department | average_salary | headcount |
-- | IT         |       76000.00 |         3 |
-- | Finance    |       68000.00 |         1 |
-- (HR at 50000 and Sales at 60000 are excluded because they do not exceed 60000)
SQL Master Β· Beginner Series Pg 108
CH 16 WHERE vs HAVING (Side-by-Side)
Part 3 of 5

WHERE vs HAVING (Side-by-Side)

Understanding the distinct differences between WHERE and HAVING is a major milestone in mastering SQL. Both clauses filter data, but they operate at completely different stages of query execution on completely different data structures. Comparing their rules side by side cements the proper usage of each clause in your developer mindset.

Key Points
βœ“ WHERE filters individual rows; HAVING filters summary groups.
βœ“ WHERE executes BEFORE grouping; HAVING executes AFTER grouping.
βœ“ WHERE cannot contain aggregate functions; HAVING is designed specifically for aggregate functions.
βœ“ WHERE can be used without GROUP BY; HAVING almost always requires GROUP BY.
βœ“ A single query can use BOTH WHERE and HAVING together to filter rows and groups!
Real-Life Example
Think of hiring job candidates: WHERE screens out individual applicants who lack a high school diploma. HAVING screens entire branch offices to ensure only branches with more than 5 certified employees receive funding.
Remember / Pro Tip
Comparison Rule: If filtering raw rows (salary > 50000), use WHERE. If filtering metrics (AVG(salary) > 50000), use HAVING.
SQL Example
-- Using BOTH WHERE and HAVING together in the same query:
-- 1. WHERE filters individual employees earning at least 50000
-- 2. GROUP BY organizes remaining employees into departments
-- 3. HAVING keeps only departments with at least 2 such employees
SELECT department, COUNT(*) AS qualifying_staff, AVG(salary) AS avg_sal
FROM employees
WHERE salary >= 50000
GROUP BY department
HAVING COUNT(*) >= 2;

-- Output:
-- IT (3 staff, avg 76000) and Sales (2 staff, avg 60000) qualify!
SQL Master Β· Beginner Series Pg 109
CH 16 Full Query Order: The Complete Flow
Part 4 of 5

Full Query Order: The Complete Flow

You have now learned all the major query clauses in beginner SQL! However, SQL has two orders: the Syntax Order (how you write the query in code) and the Execution Order (how the database engine actually processes the data behind the scenes). Understanding both flows prevents syntax errors and makes query logic intuitive.

Key Points
βœ“ Written Syntax Order: SELECT -> FROM -> WHERE -> GROUP BY -> HAVING -> ORDER BY -> LIMIT.
βœ“ Internal Execution Order: FROM -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BY -> LIMIT.
βœ“ FROM identifies the table first; WHERE filters individual rows second.
βœ“ GROUP BY creates buckets third; HAVING filters buckets fourth.
βœ“ SELECT picks and aliases columns fifth; ORDER BY sorts sixth; LIMIT truncates last!
Real-Life Example
Think of baking a cake: You gather ingredients (FROM), sift out lumps (WHERE), mix batter into tins (GROUP BY), discard underweight tins (HAVING), bake and slice (SELECT), decorate (ORDER BY), and serve 2 slices (LIMIT).
Remember / Pro Tip
Memorize the syntax acronym: 'Sweaty Frogs Wear Glasses, Having Orange Lemonade' (SELECT FROM WHERE GROUP-BY HAVING ORDER-BY LIMIT).
SQL Example
-- The Ultimate Complete Beginner SQL Query
SELECT department, COUNT(*) AS staff_count, ROUND(AVG(salary), 2) AS avg_sal
FROM employees
WHERE salary >= 50000
GROUP BY department
HAVING COUNT(*) >= 2
ORDER BY avg_sal DESC
LIMIT 1;

-- Output:
-- | department | staff_count | avg_sal  |
-- | IT         |           3 | 76000.00 |
SQL Master Β· Beginner Series Pg 110
CH 16 Mistakes + Final Recap and Practice
Part 5 of 5

Mistakes + Final Recap and Practice

The most common HAVING mistake is using HAVING when WHERE should have been used, such as writing HAVING department = 'IT'. While some database engines permit this, it forces the database to group every row before filtering, which is drastically slower than filtering rows first with WHERE. Reserve HAVING strictly for aggregate conditions.

Key Points
βœ“ Do not use HAVING for simple column filters; use WHERE to filter early and speed up queries.
βœ“ Remember that HAVING requires an aggregate function or a column present in GROUP BY.
βœ“ Clause order is strictly enforced: SELECT -> FROM -> WHERE -> GROUP BY -> HAVING -> ORDER BY -> LIMIT.
βœ“ Always test complex multi-clause queries step by step, adding one clause at a time.
Real-Life Example
Imagine washing dishes: you scrape large food scraps into the compost bin before loading dishes into the dishwasher. Using HAVING for simple column filters is like washing full plates of food in the dishwasher!
Remember / Pro Tip
Recap: WHERE filters rows early, GROUP BY makes buckets, HAVING filters buckets, ORDER BY sorts, and LIMIT caps rows.
SQL Example
-- Practice 1: Find departments with total payroll greater than 150000
-- Answer:
SELECT department, SUM(salary) AS total_pay FROM employees GROUP BY department HAVING SUM(salary) > 150000;

-- Practice 2: Find cities having more than 1 employee
-- Answer:
SELECT city, COUNT(*) AS count FROM employees GROUP BY city HAVING COUNT(*) > 1;

-- Practice 3: Complete query - Cities with average salary > 65000 sorted descending
-- Answer:
SELECT city, AVG(salary) AS avg_sal FROM employees GROUP BY city HAVING AVG(salary) > 65000 ORDER BY avg_sal DESC;
SQL Master Β· Beginner Series Pg 111
CHAPTER {{ n.chapter_number|stringformat:"02d" }} 10 Parts

CREATE DATABASE, CREATE TABLE, ALTER and MODIFY TABLE

{{ n.short_description|default:"Essential SQL syntax rules, practical queries, step-by-step explanations, and best practices." }}

Topics in this chapter:
  • 1 What is DDL?
  • 2 CREATE DATABASE (create, SHOW, USE)
  • 3 CREATE TABLE (Columns + Data Types)
  • 4 Constraints: PRIMARY KEY, NOT NULL, UNIQUE, DEFAULT
  • 5 ALTER TABLE: ADD COLUMN
  • 6 MODIFY COLUMN (Change Type or Size)
  • 7 RENAME COLUMN and RENAME TABLE
  • 8 DROP COLUMN
  • 9 DROP TABLE vs DROP DATABASE
  • 10 Mistakes + Recap and Practice
CH 17 What is DDL?
Part 1 of 10

What is DDL?

Up until now, you have focused on querying data using SELECT statements, which belong to Data Query Language (DQL). But before you can query, insert, or update records, someone must first construct the actual database and table structures. Data Definition Language (DDL) is the subset of SQL commands used to build, alter, and delete database structures themselves.

Key Points
βœ“ DDL stands for Data Definition Language.
βœ“ DDL commands build, alter, and destroy the structural containers that hold data.
βœ“ The core DDL commands are CREATE, ALTER, and DROP.
βœ“ Unlike DML changes (INSERT, UPDATE), DDL changes often auto-commit immediately.
βœ“ DDL commands manage metadata (table architecture) rather than individual row contents.
Real-Life Example
Imagine constructing an office building: DDL is the architecture blueprints, pouring the concrete foundation, framing walls, and building storage rooms. DML is moving desks, computers, and employees into those finished rooms.
Remember / Pro Tip
DQL and DML work with the data inside tables; DDL builds and modifies the structure of the tables themselves.
SQL Example
-- Summary of the core DDL commands:
-- CREATE : Builds a new database, table, or index
-- ALTER  : Modifies the schema of an existing table
-- DROP   : Permanently destroys a table or database
-- TRUNCATE: Empties all records from a table while keeping the table structure

-- Checking database version and connection
SELECT VERSION() AS database_engine_version;
SQL Master Β· Beginner Series Pg 113
CH 17 CREATE DATABASE (create, SHOW, USE)
Part 2 of 10

CREATE DATABASE (create, SHOW, USE)

The first step in any new software project is creating the database container that will house all your application's tables, views, and indexes. In MySQL and MariaDB, you use CREATE DATABASE to build the storage container, SHOW DATABASES to list existing containers, and USE to select the active database for your upcoming queries.

Key Points
βœ“ Syntax: CREATE DATABASE database_name; creates a new empty database.
βœ“ Syntax: SHOW DATABASES; lists all databases available on the current database server.
βœ“ Syntax: USE database_name; switches your active connection to that database.
βœ“ Use CREATE DATABASE IF NOT EXISTS db_name; to prevent errors if the database already exists.
βœ“ Database names should be lowercase, descriptive, and avoid spaces or special characters.
Real-Life Example
Imagine moving into a brand-new warehouse: CREATE DATABASE buys an empty warehouse building, SHOW DATABASES lists your company's properties, and USE walks through the front door of that specific warehouse to start work.
Remember / Pro Tip
Always run USE database_name before creating tables so your new tables are created in the correct database!
SQL Example
-- Step 1: Create a new company database safely
CREATE DATABASE IF NOT EXISTS company_db;

-- Step 2: View all databases on the server
SHOW DATABASES;

-- Step 3: Switch into our new database
USE company_db;

-- Output: Database changed. You are now working inside company_db.
SQL Master Β· Beginner Series Pg 114
CH 17 CREATE TABLE (Columns + Data Types)
Part 3 of 10

CREATE TABLE (Columns + Data Types)

The CREATE TABLE statement creates a new rectangular table inside your active database. When defining a table, you must specify the table's name along with an ordered list of column names and their respective data types. Choosing appropriate data types ensures data integrity, prevents corrupt records, and maximizes storage efficiency.

Key Points
βœ“ Syntax: CREATE TABLE table_name (column1 datatype, column2 datatype, ...);
βœ“ Every column must be assigned a valid SQL data type (INT, VARCHAR, DATE, DECIMAL).
βœ“ Text columns like VARCHAR must specify a maximum length in parentheses: VARCHAR(50).
βœ“ Table definitions are wrapped inside parentheses and separated by commas.
βœ“ Use CREATE TABLE IF NOT EXISTS table_name to avoid runtime errors during script deployment.
Real-Life Example
Imagine designing a blank paper form for job applicants: you draw vertical columns labeled 'First Name', 'Age', and 'Hire Date', and define the box sizes so applicants know what to write.
Remember / Pro Tip
Always plan your column data types carefully: storing numbers as text prevents mathematical calculations later.
SQL Example
-- Creating our canonical employees table from scratch
CREATE TABLE IF NOT EXISTS employees (
    id INT PRIMARY KEY,
    name VARCHAR(50) NOT NULL,
    department VARCHAR(50) NOT NULL,
    salary INT NOT NULL,
    city VARCHAR(50) NOT NULL
);

-- Inspect table structure in MySQL:
DESCRIBE employees;
-- Output: Displays column names, types, nullability, and primary key status
SQL Master Β· Beginner Series Pg 115
CH 17 Constraints: PRIMARY KEY, NOT NULL, UNIQUE, DEFAULT
Part 4 of 10

Constraints: PRIMARY KEY, NOT NULL, UNIQUE, DEFAULT

Constraints are validation rules enforced by the database engine on table columns to prevent invalid or garbage data from ever entering your system. If an INSERT or UPDATE statement violates a constraint rule, the database immediately rejects the transaction with an error. The four most essential constraints for beginners are PRIMARY KEY, NOT NULL, UNIQUE, and DEFAULT.

Key Points
βœ“ PRIMARY KEY: Uniquely identifies each row; values must be unique and cannot be NULL.
βœ“ NOT NULL: Guarantees that a column can never hold empty NULL values.
βœ“ UNIQUE: Ensures all values in a column are distinct from each other (e.g. email addresses).
βœ“ DEFAULT: Supplies an automatic fallback value if no value is provided during an INSERT.
βœ“ AUTO_INCREMENT (MySQL) / SERIAL (Postgres): Automatically generates consecutive IDs (1, 2, 3...).
Real-Life Example
Think of passport security rules: Every passport must have a unique number (PRIMARY KEY), must have a legal name printed (NOT NULL), no two citizens have the same number (UNIQUE), and country defaults to USA (DEFAULT).
Remember / Pro Tip
Always enforce business rules with database constraints rather than relying solely on frontend website code.
SQL Example
-- Creating a robust table with all 4 major constraints
CREATE TABLE employee_accounts (
    account_id INT PRIMARY KEY AUTO_INCREMENT,
    email VARCHAR(100) NOT NULL UNIQUE,
    full_name VARCHAR(50) NOT NULL,
    is_active BOOLEAN DEFAULT TRUE,
    created_at DATE DEFAULT (CURRENT_DATE)
);

-- Inserting without is_active automatically uses default value TRUE:
INSERT INTO employee_accounts (email, full_name)
VALUES ('alice@company.com', 'Alice Martin');
SQL Master Β· Beginner Series Pg 116
CH 17 ALTER TABLE: ADD COLUMN
Part 5 of 10

ALTER TABLE: ADD COLUMN

As software applications evolve over time, business requirements inevitably change, requiring new fields to be added to existing tables. The ALTER TABLE statement modifies the schema of an existing table without destroying or erasing any of the existing records already stored inside it. Adding a new column with ADD COLUMN is the most common table alteration.

Key Points
βœ“ ALTER TABLE modifies an existing table's schema while preserving existing data.
βœ“ Syntax: ALTER TABLE table_name ADD COLUMN column_name datatype;
βœ“ The keyword COLUMN is optional in most SQL dialects: ADD column_name datatype works too.
βœ“ Newly added columns will initially contain NULL for all existing rows unless given a DEFAULT.
βœ“ In MySQL, you can use FIRST or AFTER existing_col to control the physical placement of the column.
Real-Life Example
Imagine adding an extra column for 'Emergency Contact Phone' onto existing paper personnel files in HR. You do not throw away the existing employee records; you simply stamp the new box onto every file.
Remember / Pro Tip
When adding a NOT NULL column to a table that already has data, you MUST provide a DEFAULT value!
SQL Example
-- Add an email column to our existing employees table
ALTER TABLE employees
ADD COLUMN email VARCHAR(100);

-- Add a status column with a safe default value
ALTER TABLE employees
ADD COLUMN status VARCHAR(20) DEFAULT 'Active';

-- Verify the new columns exist:
SELECT id, name, email, status FROM employees LIMIT 2;
-- Output: Shows existing employees with NULL email and 'Active' status
SQL Master Β· Beginner Series Pg 117
CH 17 MODIFY COLUMN (Change Type or Size)
Part 6 of 10

MODIFY COLUMN (Change Type or Size)

Sometimes a column's data type or length needs to be adjusted after a table has been in use. For example, a VARCHAR(20) phone column might need to expand to VARCHAR(50) to support international country codes. In MySQL, you use MODIFY COLUMN to alter a column's type, size, or constraints, while PostgreSQL and SQL Server use ALTER COLUMN.

Key Points
βœ“ MySQL / MariaDB syntax: ALTER TABLE table_name MODIFY COLUMN col_name new_datatype;
βœ“ PostgreSQL / SQL Server syntax: ALTER TABLE table_name ALTER COLUMN col_name TYPE new_datatype;
βœ“ Expanding column length (e.g. VARCHAR(50) to VARCHAR(100)) is safe and instant.
βœ“ Shrinking column length will fail if existing data values exceed the new smaller limit.
βœ“ Converting between incompatible data types (e.g. text to integer) can cause data loss or errors.
Real-Life Example
Imagine expanding the size of mailboxes in an apartment lobby. Replacing small slots with larger boxes is simple and holds more mail; shrinking them would crush existing letters inside.
Remember / Pro Tip
Dialect Alert: MySQL uses MODIFY COLUMN, while PostgreSQL and SQL Server use ALTER COLUMN!
SQL Example
-- MySQL: Expanding department column size from VARCHAR(50) to VARCHAR(100)
ALTER TABLE employees
MODIFY COLUMN department VARCHAR(100) NOT NULL;

-- Dialect note: PostgreSQL and SQL Server equivalent:
-- ALTER TABLE employees ALTER COLUMN department TYPE VARCHAR(100);

-- Verify the change in MySQL:
DESCRIBE employees;
-- Output: department column now displays Type: varchar(100)
SQL Master Β· Beginner Series Pg 118
CH 17 RENAME COLUMN and RENAME TABLE
Part 7 of 10

RENAME COLUMN and RENAME TABLE

Clear naming conventions are vital for readable code and long-term project maintenance. If a column or table was given an awkward, confusing, or misspelled name during early development, SQL provides DDL statements to rename schema objects cleanly. Renaming updates database metadata instantly without copying or rewriting the underlying row data.

Key Points
βœ“ Syntax: ALTER TABLE table_name RENAME COLUMN old_name TO new_name;
βœ“ Syntax: ALTER TABLE old_table_name RENAME TO new_table_name;
βœ“ Modern SQL standards support RENAME COLUMN across MySQL 8.0+, PostgreSQL, and SQLite.
βœ“ Renaming updates internal table metadata in milliseconds.
βœ“ WARNING: Renaming a column or table will break any backend application queries using the old name!
Real-Life Example
Imagine updating a department sign on an office wall from 'Personnel' to 'Human Resources'. The employees, desks, and filing cabinets inside do not move; only the nameplate on the door changes.
Remember / Pro Tip
Always search your application codebase for the old column name before renaming it in the database!
SQL Example
-- Rename 'city' column to 'office_location'
ALTER TABLE employees
RENAME COLUMN city TO office_location;

-- Rename the column back to 'city' to keep our standard schema intact
ALTER TABLE employees
RENAME COLUMN office_location TO city;

-- Rename an entire table:
-- ALTER TABLE employees RENAME TO staff_members;
SQL Master Β· Beginner Series Pg 119
CH 17 DROP COLUMN
Part 8 of 10

DROP COLUMN

When a column is no longer needed by your business applications, you can permanently remove it from the table schema using ALTER TABLE DROP COLUMN. Dropping a column immediately purges that column's definition and deletes all data stored within it across every row in the table. Because this action cannot be undone, it must be performed with extreme caution.

Key Points
βœ“ Syntax: ALTER TABLE table_name DROP COLUMN column_name;
βœ“ The column and all data stored inside it across all rows are permanently deleted.
βœ“ Dropping a column is irreversible; there is no 'Ctrl+Z' undo command in SQL.
βœ“ You cannot drop a column if it is the only remaining column in the table.
βœ“ Check for database indexes or foreign keys that reference the column before dropping it.
Real-Life Example
Imagine tearing down a dividing wall in your house with a sledgehammer. Once the wall and its electrical wiring are demolished and removed, you cannot snap your fingers to put it back.
Remember / Pro Tip
Always create a database backup before executing DROP COLUMN commands on production databases!
SQL Example
-- Add a temporary scratch column for demonstration
ALTER TABLE employees ADD COLUMN temp_notes VARCHAR(100);

-- Permanently drop the column from the table
ALTER TABLE employees
DROP COLUMN temp_notes;

-- Verify the column has been completely removed:
DESCRIBE employees;
-- Output: temp_notes no longer appears in the table definition
SQL Master Β· Beginner Series Pg 120
CH 17 DROP TABLE vs DROP DATABASE
Part 9 of 10

DROP TABLE vs DROP DATABASE

The DROP TABLE and DROP DATABASE statements are the most destructive commands in the entire SQL language. DROP TABLE completely destroys a table, its schema definition, and every row of data stored within it. DROP DATABASE goes even further, wiping out the entire database container and every single table inside it. These commands execute instantly without a confirmation prompt.

Key Points
βœ“ DROP TABLE table_name; permanently deletes the table and all its rows.
βœ“ DROP DATABASE db_name; permanently deletes the entire database and all contained tables.
βœ“ Neither command asks 'Are you sure?'; execution is immediate and irreversible.
βœ“ Use IF EXISTS to prevent runtime errors: DROP TABLE IF EXISTS test_table;
βœ“ TRUNCATE TABLE empties all rows quickly but preserves the empty table structure for future use.
Real-Life Example
Imagine an office building: TRUNCATE is taking all paper files out and shredding them while keeping the filing cabinet. DROP TABLE is taking the filing cabinet to a junkyard. DROP DATABASE is demolishing the entire building!
Remember / Pro Tip
EXTREME CAUTION: Double-check your active database connection before typing DROP DATABASE!
SQL Example
-- Safe syntax using IF EXISTS:
DROP TABLE IF EXISTS temporary_logs;

-- Empty all rows without destroying the table structure:
-- TRUNCATE TABLE test_table;

-- Danger Zone: Completely deletes an entire database and all tables!
-- DROP DATABASE IF EXISTS test_sandbox_db;

-- Verification:
SHOW TABLES;
SQL Master Β· Beginner Series Pg 121
CH 17 Mistakes + Recap and Practice
Part 10 of 10

Mistakes + Recap and Practice

The most catastrophic mistakes in software engineering involve accidental DROP or ALTER commands on production databases without a recent backup. Other frequent beginner DDL errors include forgetting comma separators between column definitions in CREATE TABLE, trying to add a NOT NULL column without a DEFAULT to an existing table with rows, and mixing up DROP (DDL) with DELETE (DML).

Key Points
βœ“ DROP destroys table structure (DDL); DELETE removes individual rows (DML).
βœ“ Remember dialect differences: MySQL uses MODIFY COLUMN; Postgres uses ALTER COLUMN TYPE.
βœ“ Always use IF EXISTS / IF NOT EXISTS in automated deployment scripts.
βœ“ Always verify your active database (SELECT DATABASE();) before running DDL scripts.
Real-Life Example
Imagine an airline pilot running a pre-flight checklist before takeoff: verifying switches takes 30 seconds but prevents disaster. Verifying your database name before running DDL prevents career-ending accidents!
Remember / Pro Tip
Congratulations! You have mastered SQL foundations: DQL queries, operators, filtering, aggregation, and DDL!
SQL Example
-- Final DDL Practice:
-- Practice 1: Create a projects table with id, project_name, and budget
CREATE TABLE IF NOT EXISTS projects (
    id INT PRIMARY KEY,
    project_name VARCHAR(100) NOT NULL,
    budget DECIMAL(10,2) DEFAULT 0.00
);

-- Practice 2: Add a deadline column to projects
ALTER TABLE projects ADD COLUMN deadline DATE;

-- Practice 3: Clean up test table safely
DROP TABLE IF EXISTS projects;
SQL Master Β· Beginner Series Pg 122

Beginner Level Completed!

Congratulations! You have flipped through all 17 chapters of the SQL Beginner Handbook. Now test your skills by running live queries in the practice console!