D426 Chapter 2A Notes – SQL, Tables & Row Changes
Source: built from Raul's printouts of the zyBooks Data Management – Foundations (WGU D426, v3) Chapter 2, sections 2.1–2.6, plus the task text of LABs 2.11–2.15. §2.5 Null values didn't print, so it was transcribed from the live zyBook instead. Sections 2.7–2.10 and LABs 2.16–2.18 are in Chapter 2B. Where a printed animation step disagrees with its figure, these notes follow the figure. Citations like (§2.3) are zyBook sections. These notes are not official WGU or zyBooks material.
Big idea: SQL is the standard language of relational databases: five sublanguages, statements built from keywords, identifiers, literals, expressions, and comments, organized as clauses, with each statement ending in a semicolon (§2.1). A database system instance holds databases you create, USE, SHOW, and drop (§2.2). A table is a name, a fixed sequence of columns (each with a data type) and a varying set of rows, and it obeys four relational rules, including data independence; CREATE / ALTER / DROP TABLE manage it (§2.3). Pick the smallest data type that fits (§2.4). NULL means unknown or inapplicable (not zero or blank), and NOT NULL makes the database reject it (§2.5). INSERT, UPDATE, and DELETE change rows: no WHERE means every row, and a column left out of an INSERT gets NULL or its DEFAULT (§2.6).
Course competency: C2 (run queries that create and manipulate data in relational databases) and C3 (explain attributes of databases, tables, and SQL commands) (WGU program guide).
1. Structured Query Language (§2.1)
SQL = the standard query language of relational databases; preferred pronunciation "S-Q-L" (commonly "seekwəl") (§2.1).
Sublanguages
Five sublanguages, each an informal grouping of statements. The book covers the first four in detail; DCL is mainly of interest to database administrators (§2.1).
Sublanguage | Does what | Book's example |
|---|---|---|
DDL Data Definition Language | defines database structure |
|
DQL Data Query Language | retrieves data |
|
DML Data Manipulation Language | inserts, updates, deletes data |
|
DTL Data Transaction Language | manages transactions |
|
DCL Data Control Language | specifies user access to data |
|
Language elements
Literal = explicit value; strings go in single or double quotes (
'Maria',129). Keyword = special meaning, defined by the database system (SELECT). Identifier = name of a database object, specified by the programmer (City) (§2.1).Expression = literals, identifiers, and operations that evaluate to one value (
Population > 1000 OR Name = 'Tokyo'). Comment = ignored:--(two dashes plus a space) or/* ... */(§2.1).Statement = complete, executable instruction ending in a semicolon, made of one or more clauses; each clause starts with a keyword. Line breaks are ignored; good practice is one clause per line (§2.1).
String literals are always case-sensitive; keyword and identifier case-sensitivity varies by database system (not case-sensitive in the book's sandbox). MySQL lets a keyword serve as an identifier (
Name) (§2.1).
-- This is an example comment <- comment (ignored)
SELECT Name <- clause: keyword SELECT + identifier Name
FROM City <- clause: keyword FROM + identifier City
WHERE Population > 10000; <- clause: keyword WHERE + expression
(identifier Population, literal 10000)Syntax definitions
MySQL notation: UPPERCASE = keyword; lowercase = identifier or expression you supply; [ ] = optional; { } = alternatives split by |, exactly one required; ... = may repeat; ( ) and commas are typed as shown (§2.1).
INSERT [INTO] tbl_name
[(col_name [, col_name] ...)]
{VALUES | VALUE} (value_list) [, (value_list)] ...
-- value_list: value [, value] ... value: {expr | DEFAULT}So: INTO and the column list are optional (no list → values for all columns); each value list = one new row; a value is an expression or DEFAULT (§2.1).
The SQL standard
SQL standard = official syntax and behavior of SQL statements, published jointly by ANSI and ISO; first published 1986; the 2023 version has 16 parts (11 active). MySQL implements the most important parts, with limited differences and custom extensions (§2.1).
Part = a formal specification of syntax and behavior; sublanguage = an informal grouping of statements. All five sublanguages are specified in the part Foundation (§2.1).
MySQL implements Foundation, SQL/PSM (procedural statements: loops, procedures), SQL/Schemata (the information_schema database), and SQL/XML functions (not the XML data type). Framework defines concepts and terms (§2.1).
2. Managing databases (§2.2)
CREATE DATABASE and DROP DATABASE
Database system instance = a single executing copy of a database system. PCs usually run one, shared (e.g., cloud) computers several; each holds system and user databases. The mysql database is installed automatically for system administration (§2.2).
CREATE DATABASE DatabaseName; -- creates a new database
DROP DATABASE DatabaseName; -- deletes it, including all its tablesUSE and SHOW
USE DatabaseName; -- default database for subsequent statements
SHOW DATABASES; -- all databases in the instance
SHOW TABLES [FROM DatabaseName]; -- tables in the default (or a named) database
SHOW COLUMNS FROM TableName; -- one row per column: Field, Type, Null, Key, Default, Extra
SHOW CREATE TABLE TableName; -- the table's CREATE TABLE statementSHOW TABLES, SHOW COLUMNS, and SHOW CREATE TABLE work on the default database, so USE comes first (or add FROM DatabaseName to SHOW TABLES) (§2.2).
3. Tables (§2.3)
Tables, columns, and rows
Table = a name, a fixed sequence of columns, and a varying set of rows. Column = name + data type. Row = unnamed sequence of values, each belonging to its column's data type. Cell = one column of one row (§2.3).
At least one column, any number of rows; no rows = empty table (§2.3).
column names -> | ID | Name | Salary | column = name + data type
row (unnamed) -> | 2538 | Lisa Ellison | 45000 |
| 5384 | Sam Snead | 30500 |
^ cell: one column of one row, exactly one valueRules governing tables
Exactly one value per cell; unknown data = NULL (§2.3).
No duplicate column names within a table (allowed across tables) (§2.3).
No duplicate rows (no two rows identical in all columns) (§2.3).
No row order: how rows are stored never affects query results. This is data independence, which lets DBAs reorganize storage to improve performance without changing results (§2.3). - Rules 3 and 4 follow from table = set of rows. Most databases still allow duplicate rows, usually in temporary tables; duplicates are normally removed as data moves to a permanent table (§2.3).
CREATE TABLE and DROP TABLE
CREATE TABLE [IF NOT EXISTS] TableName (
Column1 DATA_TYPE,
Column2 DATA_TYPE,
...
ColumnN DATA_TYPE
);
DROP TABLE [IF EXISTS] TableName;CREATE TABLE = table name + column names + data types, such as INT/INTEGER, VARCHAR(N) (0 to N characters), DATE, DECIMAL(M, D) (M digits, D after the point) (§2.3).
DROP TABLE deletes the table and all its rows (§2.3).
CREATE TABLE fails if the table exists, DROP TABLE if it doesn't; IF NOT EXISTS / IF EXISTS avoid the failures (§2.3).
ALTER TABLE
ALTER TABLE adds, deletes, or modifies columns of an existing table: table name, then one clause (§2.3).
ALTER TABLE TableName ADD ColumnName DataType;
ALTER TABLE TableName CHANGE CurrentColumnName NewColumnName NewDataType;
ALTER TABLE TableName DROP ColumnName;Book: ADD Salary DECIMAL(7,2) → CHANGE Salary AnnualSalary INT (new name and type) → DROP AnnualSalary (§2.3).
4. Data types (§2.4)
Data type categories
Data type = a named set of values from which column values are drawn (§2.4).
Category | Represents | Common types |
|---|---|---|
Integer | positive and negative integers | INT (4 bytes), SMALLINT (2 bytes) |
Decimal | numbers with fractional values | FLOAT, DECIMAL |
Character | textual characters | CHAR (fixed), VARCHAR (variable) |
Date and time | date, time, or both | DATE, TIME, DATETIME, TIMESTAMP |
Binary | data bit for bit, as in memory or files | BLOB, BINARY, VARBINARY, IMAGE |
Spatial | lines, polygons, map coordinates | POLYGON, POINT, GEOMETRY |
Document | structured text (XML or JSON) | XML |
Specialized types: MONEY, BOOLEAN, BIT, ENUM (a small, fixed set of values) (§2.4).
MySQL data types
Signed = may be negative; unsigned = cannot be, and stores larger numbers than the signed version. Character types use 1–2 bytes per character; integer types a fixed number of bytes (§2.4).
Use the smallest type that fits to minimize table size (ex: -100 to 100 → TINYINT, 1 byte) (§2.4).
Table 2.4.2 (§2.4)
TINYINT 1 byte signed -128..127 unsigned 0..255
SMALLINT 2 bytes signed -32,768..32,767 unsigned 0..65,535
MEDIUMINT 3 bytes signed -8,388,608..8,388,607 unsigned 0..16,777,215
INT/INTEGER 4 bytes signed -2,147,483,648..2,147,483,647 unsigned 0..4,294,967,295
BIGINT 8 bytes signed -2^63..2^63-1 unsigned 0..2^64-1
DECIMAL(M,D) varies exact; M significant digits, D after the point
FLOAT 4 bytes approximate; -3.4E+38..3.4E+38
DOUBLE 8 bytes approximate; -1.8E+308..1.8E+308
DATE 3 bytes YYYY-MM-DD; '1000-01-01'..'9999-12-31'
TIME 3 bytes hh:mm:ss
DATETIME 5 bytes YYYY-MM-DD hh:mm:ss; '1000-01-01 00:00:00'..'9999-12-31 23:59:59'
CHAR(N) N bytes fixed length; 0 ≤ N ≤ 255
VARCHAR(N) chars + 1 byte (N ≤ 255) or + 2 (N > 255); max N chars; 0 ≤ N ≤ 65,535
TEXT chars + 2 bytes; max 65,535 charactersSpec phrase → type: never negative → UNSIGNED; fixed-length → CHAR(N); variable up to N → VARCHAR(N); exact, D decimals → DECIMAL(M,D); approximate → FLOAT/DOUBLE; date and time → DATETIME (§2.4).
5. Null values (§2.5)
NULL
NULL is a special value that represents either unknown or inapplicable data. It is not the same as zero for numeric data types or blanks for character data types (§2.5).
A zero bonus means the employee can, but has not, earned a bonus: known and applicable, so it's 0, not NULL (§2.5).
Book's Compensation table: a NULL BirthDate means unknown (all employees have a birth date); a NULL Bonus for an Engineering employee, if Engineering pays no bonuses, means inapplicable (§2.5).
NOT NULL constraint
Columns may contain NULL by default, but some never should (ex: a business requires a name for every employee) (§2.5).
NOT NULL prevents a column from having a NULL value: statements that insert NULL or update a value to NULL are automatically rejected. It follows the column name and data type in CREATE TABLE (§2.5).
CREATE TABLE Employee (
ID SMALLINT UNSIGNED,
Name VARCHAR(60) NOT NULL, -- NULL Name -> rejected
BirthDate DATE, -- NULL allowed (default)
Salary DECIMAL(7,2)
);A column that identifies rows and must contain valid data (the ID column of the book's Compensation table) is designated NOT NULL (§2.5).
Tie-in: an omitted column with no DEFAULT is assigned NULL, so an INSERT that omits such a NOT NULL column is rejected (§2.5, §2.6).
6. Inserting, updating, and deleting rows (§2.6)
INSERT
INSERT INTO names the table and columns (INTO is optional); VALUES gives the values, for any number of rows (§2.6).
INSERT [INTO] TableName (Column1, Column2, ...)
VALUES (Value1, Value2, ...);Value order = column order in the INTO clause. Omit the column names only if VALUES lists all values in the table's column order. Several rows:
VALUES (...), (...);(§2.6).
DEFAULT values
An omitted column gets NULL, unless it has a DEFAULT (then that value) or NOT NULL (then the insert is rejected). DEFAULT and its value follow the column's data type in CREATE TABLE (§2.6):
CREATE TABLE Employee (
ID SMALLINT UNSIGNED,
Name VARCHAR(60), -- omitted -> NULL
BirthDate DATE DEFAULT '2000-01-01', -- omitted -> '2000-01-01'
Salary DECIMAL(7,2) DEFAULT 0.00 -- omitted -> 0.00
);UPDATE
UPDATE modifies existing rows; SET gives the new values; an optional WHERE picks the rows; no WHERE → all rows updated (§2.6).
UPDATE TableName
SET Column1 = Value1, Column2 = Value2, ...
WHERE condition;DELETE and TRUNCATE
DELETE removes existing rows; FROM names the table; an optional WHERE picks rows; no WHERE → all rows deleted. TRUNCATE deletes all rows, nearly identical to DELETE without WHERE (minor differences by database system) (§2.6).
DELETE FROM TableName
WHERE condition; -- ex: WHERE Salary > 40000 AND Salary < 80000
TRUNCATE TABLE TableName;7. LAB skills (§2.11–2.15)
2.11: CREATE TABLE from a plain-English column list; check with
SHOW TABLES;(§2.11).2.12: ALTER TABLE to ADD a column, DROP a column, and CHANGE a name and type; check with
SHOW COLUMNS FROM ...;(§2.12).2.13–2.15: INSERT rows (one with NULL); UPDATE by ID, two columns at once, and by date; DELETE by ID, by either of two values, and by date. Check with
SELECT * FROM ...;(§2.13–2.15).Only task text printed; no solutions here. The LABs' auto increment, primary key, and allowed-value or range rules belong to Chapter 2B (§2.13–2.15).
8. How the pieces connect
database system instance (§2.2)
+-- database CREATE DATABASE / USE / SHOW / DROP DATABASE
+-- table CREATE / ALTER / DROP TABLE (§2.3)
+-- columns name + smallest fitting data type (§2.3, §2.4)
| [NOT NULL] [DEFAULT value] (§2.5, §2.6)
+-- rows INSERT / UPDATE / DELETE / TRUNCATE (§2.6)
+-- cells one value each; NULL = unknown (§2.3, §2.5)
or inapplicableDDL defines, DML fills: CREATE/ALTER/DROP TABLE shape the columns (and their NOT NULL and DEFAULT settings); INSERT/UPDATE/DELETE change the rows, each value belonging to its column's data type, with WHERE scoping UPDATE and DELETE, and any statement that would put NULL in a NOT NULL column rejected (§2.1, §2.3, §2.5, §2.6).
9. Commonly confused
NULL vs zero vs blank: NULL = unknown or inapplicable, not the same as zero (numeric) or blanks (character); a known, applicable zero bonus is 0, not NULL (§2.5).
NOT NULL vs DEFAULT: NOT NULL rejects an insert or update that would leave the column NULL; DEFAULT supplies a value when the column is omitted from an INSERT (§2.5, §2.6).
DELETE vs TRUNCATE vs DROP TABLE: DELETE removes the WHERE-chosen rows (no WHERE = all); TRUNCATE removes all rows; both keep the table (an empty table once every row is gone). DROP TABLE removes the table itself with its rows (§2.3, §2.6).
ALTER TABLE ... DROP vs DROP TABLE vs DROP DATABASE: a column vs a table vs a database with all its tables (§2.2, §2.3).
UPDATE vs ALTER TABLE ... CHANGE: values in rows vs a column's name and data type (§2.3, §2.6).
INSERT vs ALTER TABLE ... ADD: a new row vs a new column (§2.3, §2.6).
DDL vs DQL vs DML: defines structure vs retrieves vs inserts, updates, deletes (§2.1).
Part vs sublanguage: formal specification vs informal grouping; all five sublanguages live in Foundation (§2.1).
Keyword vs identifier vs literal: defined by the database system vs named by the programmer vs an explicit value (§2.1).
CHAR(N) vs VARCHAR(N) vs TEXT: fixed N vs variable up to N vs variable up to 65,535 (§2.4).
DECIMAL vs FLOAT/DOUBLE: exact vs approximate (§2.4).
Signed vs unsigned: unsigned can't be negative but reaches a higher maximum with the same storage (§2.4).
10. Worked example (exam-style)
Scenario: A food truck needs a MenuItem table: item number (whole number up to 400, never negative), name (up to 40 characters), price (exact, up to 99.99), and a one-letter spice code defaulting to 'M'. Then add two items, raise a price, and clear the menu for a new season, keeping the table.
Step 1, types: item number → SMALLINT UNSIGNED (2 bytes; TINYINT tops out at 255 even unsigned). Name → VARCHAR(40). Price → DECIMAL(4,2) (exact; 4 significant digits, 2 after the point). Spice → CHAR(1) (§2.4).
Step 2, create: IF NOT EXISTS avoids an error if the table exists; DEFAULT follows the data type (§2.3, §2.6).
CREATE TABLE IF NOT EXISTS MenuItem (
ItemNum SMALLINT UNSIGNED,
ItemName VARCHAR(40),
Price DECIMAL(4,2),
Spice CHAR(1) DEFAULT 'M'
);Step 3, insert two rows, leaving out Spice: both get
'M'(with no default they'd get NULL) (§2.6).
INSERT INTO MenuItem (ItemNum, ItemName, Price)
VALUES (101, 'Elote Cup', 6.50),
(102, 'Brisket Taco', 4.75);Step 4, raise one price: without WHERE, every price would become 5.25 (§2.6).
UPDATE MenuItem
SET Price = 5.25
WHERE ItemNum = 102;Step 5, new season:
DELETE FROM MenuItem;orTRUNCATE TABLE MenuItem;leaves an empty table;DROP TABLE MenuItem;would delete the table itself (§2.3, §2.6).Step 6, classify: CREATE TABLE is DDL; INSERT, UPDATE, and DELETE are DML (§2.1).