Developer Guides, Cheat Sheets & Tools
SQL course - Part 2: BUILDING BLOCKS
| Part index | Prerequisites | Previous | Next | Full course |
π§± PART 2 β BUILDING BLOCKS
6. Data types
| ποΈ Level | β±οΈ Time | π― After this chapter you canβ¦ |
|---|---|---|
| π’ Beginner | 25 min | Pick the right type for numbers, text, and dates Β· Store money safely Β· Avoid the phone-number and Unicode traps |
[!NOTE] π In plain words: A data type is a promise about what can go in a column. Choosing
INTfor an age means βonly whole numbers live here.β The database enforces that promise for you, forever.
π Analogy: Data types are the shaped holes in a toddlerβs shape-sorter toy. The star hole only accepts the star block. You cannot force a triangle in. That sounds restrictive β it is actually what keeps your data clean for the next ten years.
6.1 π’ Numeric types
| Purpose | π₯ MSSQL | π¦ MySQL | Range / notes |
|---|---|---|---|
| Tiny whole number | TINYINT (0 to 255) |
TINYINT (-128 to 127) |
β οΈ Different! MySQLβs version allows negative numbers by default |
| Small whole number | SMALLINT |
SMALLINT |
Β±32,767 |
| Normal whole number | INT |
INT / INTEGER |
Β±2.1 billion β your default choice |
| Huge whole number | BIGINT |
BIGINT |
Β±9.2 quintillion |
| Money / exact decimals | DECIMAL(p,s) / NUMERIC(p,s) |
DECIMAL(p,s) |
Exact. Use for all money |
| Approximate decimals | FLOAT, REAL |
FLOAT, DOUBLE |
Fast but inexact |
| Currency shortcut | MONEY, SMALLMONEY |
(none) | β οΈ Avoid: it can round in surprising ways |
| Boolean | BIT (0/1) |
BOOLEAN = alias for TINYINT(1) |
Write BOOLEAN: MySQL 8.4 warns that the (1) display width is deprecated |
Understanding DECIMAL(p, s):
DECIMAL(10, 2)
β βββ scale: digits AFTER the decimal point
βββββββ precision: TOTAL digits (before + after)
So DECIMAL(10,2) holds up to 99,999,999.99
[!WARNING] β οΈ The single most important rule about money: NEVER store money in
FLOATorDOUBLE.
-- β
Works in BOTH β see the danger for yourself
SELECT
CAST(0.1 AS FLOAT) + CAST(0.2 AS FLOAT) AS float_math,
CAST(0.1 AS DECIMAL(10,2)) + CAST(0.2 AS DECIMAL(10,2)) AS decimal_math;
FLOAT gives you 0.30000000000000004. Multiply that error across a million transactions and your accountant will find you. DECIMAL gives you exactly 0.30.
[!IMPORTANT] π― When to use what:
INTβ IDs, counts, quantities. Your default for whole numbers.BIGINTβ very large tables (website logs, sensor readings) that may pass 2 billion rows.DECIMAL(10,2)β prices, salaries, totals, anything with a currency symbol.DECIMAL(5,4)β rates and percentages that must be exact (interest, tax).FLOAT/DOUBLEβ scientific measurements, coordinates, sensor data, where tiny error is acceptable.
6.2 π€ String types
| Purpose | π₯ MSSQL | π¦ MySQL | Notes |
|---|---|---|---|
| Fixed length | CHAR(n) |
CHAR(n) |
Padded with spaces. Only for truly fixed values |
| Variable length | VARCHAR(n) |
VARCHAR(n) |
Your default choice |
| Unicode fixed | NCHAR(n) |
CHAR + utf8mb4 |
Β |
| Unicode variable | NVARCHAR(n) |
VARCHAR + utf8mb4 |
π MSSQL needs the N prefix |
| Very long text | VARCHAR(MAX), NVARCHAR(MAX) |
TEXT, MEDIUMTEXT, LONGTEXT |
Up to 2 GB / 4 GB |
| Binary | VARBINARY(MAX) |
BLOB, LONGBLOB |
Files, images |
π The Unicode difference, demonstrated. Unicode means text in any language β Sinhala, Japanese, Arabic, even emoji. A column that is not Unicode knows only one alphabet, and silently turns everything else into ?:
-- π₯ MSSQL: without N, non-Latin characters become question marks
CREATE TABLE demo_ascii (t VARCHAR(50));
INSERT INTO demo_ascii VALUES ('ζ₯ζ¬θͺ'); -- becomes ???
INSERT INTO demo_ascii VALUES (N'ζ₯ζ¬θͺ'); -- still ??? β the COLUMN is the problem
CREATE TABLE demo_unicode (t NVARCHAR(50));
INSERT INTO demo_unicode VALUES (N'ζ₯ζ¬θͺ'); -- β
stored correctly
-- π¦ MySQL: use utf8mb4 and plain VARCHAR works for everything, including emoji
CREATE TABLE demo_unicode (t VARCHAR(50)) CHARACTER SET utf8mb4;
INSERT INTO demo_unicode VALUES ('ζ₯ζ¬θͺ π'); -- β
stored correctly
[!WARNING] β οΈ MySQL trap: The old charset named
utf8in MySQL is not real UTF-8 β it uses at most 3 bytes per character, so it cannot store emoji or some Chinese, Japanese, and Korean characters. Always useutf8mb4. Themb4means βmaximum 4 bytesβ.
π The full story is Chapter 60 β character sets, collations, the silent
??data loss, and the collation conflict error that stops migrations dead.
[!IMPORTANT] π― CHAR vs VARCHAR β when to use each:
Use CHAR(n)whenUse VARCHAR(n)whenThe value is always exactly n characters Length varies (almost always) Country codes CHAR(2), currencyCHAR(3)Names, emails, addresses, descriptions Fixed-format codes, hashes CHAR(64)Anything a human types freely
[!TIP] π‘ Pro tip on sizing:
VARCHAR(50)andVARCHAR(255)use the same storage for the word βTomβ β you only pay for the characters actually stored. But the declared size still matters: it documents your intent, blocks junk data, and decides how much memory the database reserves when it sorts that column. Do not lazily declare everythingVARCHAR(4000)β every sort on that column would reserve far more memory than it needs.
6.3 π Date and time types
| Purpose | π₯ MSSQL | π¦ MySQL | Example value |
|---|---|---|---|
| Date only | DATE |
DATE |
2026-06-15 |
| Time only | TIME |
TIME |
14:30:00 |
| Date + time | DATETIME2(n) |
DATETIME(n) |
2026-06-15 14:30:00.000 |
| Older date + time | DATETIME β οΈ |
TIMESTAMP |
Β |
| With time zone | DATETIMEOFFSET |
(store UTC β world standard time β plus the offset) | 2026-06-15 14:30 +05:30 |
| Auto-updating stamp | (use a DEFAULT plus a trigger β code that runs on every change, Chapter 39) | TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP |
Β |
| Year only | (use SMALLINT) |
YEAR |
2026 |
[!WARNING] β οΈ MSSQL: Avoid the old
DATETIMEtype. It rounds to 3.33 ms increments (:59.997) and has a minimum year of 1753. UseDATETIME2for new work.
[!WARNING] β οΈ MySQL:
TIMESTAMPis stored as UTC and converted to the time zone of your connection (your session) when you read it, and it ends in the year 2038.DATETIMEstores exactly what you give it with no conversion. Pick deliberately:TIMESTAMPfor βwhen did this actually happen globallyβ,DATETIMEfor βthe local wall-clock time of an appointmentβ.
-- β
MySQL: an audit column that maintains itself
CREATE TABLE audit_demo (
id INT AUTO_INCREMENT PRIMARY KEY,
note VARCHAR(100),
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP
);
-- β
MSSQL: same idea; updated_at needs a trigger (see Chapter 39)
CREATE TABLE audit_demo (
id INT IDENTITY(1,1) PRIMARY KEY,
note VARCHAR(100),
created_at DATETIME2(0) NOT NULL DEFAULT SYSDATETIME(),
updated_at DATETIME2(0) NOT NULL DEFAULT SYSDATETIME()
);
[!TIP] π‘ The golden rule of time zones: Store UTC in the database. Convert it to the userβs local time only when you show it on screen, inside your application (the website or app). A database full of mixed local times is unrecoverable β you can never know afterwards which zone each row meant.
π Chapter 61 covers this properly β
AT TIME ZONE,CONVERT_TZ, DST (daylight saving time), and how to write a local-day filter that still uses an index.
6.4 π Special and modern types
| Type | π₯ MSSQL | π¦ MySQL | Use for |
|---|---|---|---|
| Globally unique ID | UNIQUEIDENTIFIER |
CHAR(36) or BINARY(16) |
IDs created on many computers at once; IDs shown in web addresses |
| JSON | NVARCHAR(MAX) + ISJSON() |
JSON (native) |
Flexible attributes, data exchanged with other programs |
| XML | XML (native) |
TEXT |
Exchanging data with older systems |
| Spatial | GEOGRAPHY, GEOMETRY |
GEOMETRY, POINT |
Maps, distances, areas |
| Enumerated list | (use CHECK constraint) |
ENUM('a','b','c') |
Small fixed lists |
| Set of values | (use a bridge table) | SET('a','b','c') |
β οΈ Rarely a good idea |
| Row versioning | ROWVERSION / TIMESTAMP |
(manual version column) | Detecting that someone else changed a row (Chapter 63) |
[!NOTE] π In plain words: a GUID / UUID is a long random ID (such as
3f2504e0-4f89-11d3-9a0c-0305e82c3301) that is unique across every computer in the world. JSON and XML are text formats for structured data β JSON looks like{"name": "Amara", "city": "Colombo"}. Spatial types store positions and shapes on a map.
[!WARNING] β οΈ Avoid MySQL
ENUMin serious designs. Adding a value requires anALTER TABLEon the whole table, the ordering rules surprise people, and other database engines do not have it. Use a small lookup table with a foreign key, or aCHECKconstraint. OurShopDBusesCHECKfor exactly this reason.
6.5 π§ The decision table: which type do I pick?
| I need to store⦠| Use this |
|---|---|
| A personβs name | VARCHAR(100) / NVARCHAR(100) |
| An email address | VARCHAR(150) + UNIQUE |
| A phone number | VARCHAR(30) β never a number type! |
| A price or salary | DECIMAL(10,2) |
| A tax rate like 0.0825 | DECIMAL(6,4) |
| A quantity | INT |
| Yes / no | BIT (MSSQL) / BOOLEAN (MySQL) |
| A birthday | DATE |
| When a row was created | DATETIME2(0) / DATETIME (in UTC) |
| A country code | CHAR(2) |
| A blog post body | NVARCHAR(MAX) / TEXT |
| A product image | Store the file path or URL, not the file |
| A status like Pending/Paid | VARCHAR(20) + CHECK, or a lookup table |
[!CAUTION] π Common mistake: Storing a phone number as
BIGINT. You immediately lose the leading+, the leading zeros, spaces, dashes, and extensions. Phone numbers are identifiers, not quantities β you never do arithmetic on them. The same applies to postal codes, invoice numbers with letters, and national ID numbers.
6.6 π§ͺ Try it yourself
- Create a table
type_labwith one column of every numeric type. Insert12345.678into each and observe how each one stores it. - Try inserting
'abc'into anINTcolumn. Read the exact error message β you will see it again. - In MySQL, create one table with
CHARACTER SET utf8and one withutf8mb4. Insert'CafΓ© π'into both. Compare. - Create a
DECIMAL(5,2)column and try to insert1234.56. Explain the error in your own words.
π§ In practice β data types
How to use it. Choose the narrowest type that can hold every legal value: an exact type for money, a proper date type for dates, and a length limit on text that reflects the real world. Expected result: the column itself rejects impossible data, so no application code has to remember to check.
When to use it. When creating any table, and when reviewing one you inherited. The cost of a wrong type is paid at every read and every write, forever.
Where to use it. Schema design. Scenario: ShopDB stores prices as
DECIMAL(10,2). Store them asFLOATinstead and0.1 + 0.2is not0.3; totals drift by fractions of a cent, and a month later finance cannot reconcile the ledger. This is the single most consequential type decision in a commercial system.When not to use it. Never use a floating-point type (
FLOAT,REAL,DOUBLE) for money or anything else that must add up exactly. Do not store dates, numbers, or booleans in text columns β it kills index usage, permits nonsense values, and pushes conversion into every query. And do not reflexively use the maximum length:VARCHAR(MAX)/TEXTcolumns are stored and handled differently, and often cannot be indexed normally.Best practices. Prefer
DECIMAL(p,s)for money, a real date/time type for time, and integers for counts. Be deliberate about text: in MySQL useutf8mb4(the olderutf8cannot store emoji or many characters); in SQL Server preferNVARCHARwhen the data may be non-English. Changing a columnβs type on a large populated table later is an expensive, locking operation β which is why getting this right now is worth ten minutes.
7. Creating databases and schemas
| ποΈ Level | β±οΈ Time | π― After this chapter you canβ¦ |
|---|---|---|
| π’ Beginner | 15 min | Create, list, and delete databases Β· Organize tables into schemas |
[!NOTE] π In plain words: A database is the outer container. A schema is a folder inside it that groups related tables so a large system stays organized.
7.1 ποΈ Creating a database
-- β
MSSQL
-- (ShopDB already exists from Chapter 4, so these examples use practice names)
CREATE DATABASE DemoDB;
GO
-- With explicit file locations and sizes (the way real servers are set up)
-- β οΈ The folders must already exist on the server, or the CREATE fails
CREATE DATABASE DemoDB_Files
ON PRIMARY (
NAME = DemoDB_Files_data,
FILENAME = 'C:\SQLData\DemoDB_Files.mdf',
SIZE = 500MB,
FILEGROWTH = 100MB
)
LOG ON (
NAME = DemoDB_Files_log,
FILENAME = 'C:\SQLLogs\DemoDB_Files.ldf',
SIZE = 100MB,
FILEGROWTH = 50MB
);
GO
-- β
MySQL
-- (ShopDB already exists from Chapter 4, so these examples use practice names)
CREATE DATABASE DemoDB;
-- Recommended: always state the character set explicitly
CREATE DATABASE DemoDB_Utf8
CHARACTER SET utf8mb4
COLLATE utf8mb4_0900_ai_ci;
[!NOTE] π In plain words: SQL Server keeps every database in (at least) two files: an
.mdffile holding the data, and an.ldffile holding the transaction log β a diary of every change, used to recover after a crash.
Safe versions that do not error if it already exists:
-- β
MSSQL
IF DB_ID('ShopDB') IS NULL
CREATE DATABASE ShopDB;
-- β
MySQL
CREATE DATABASE IF NOT EXISTS ShopDB;
Switching to a database:
-- β
MSSQL
USE ShopDB;
GO
-- β
MySQL
USE ShopDB;
Listing and dropping:
-- β
MSSQL
SELECT name, create_date, state_desc FROM sys.databases;
DROP DATABASE DemoDB; -- fails while any connection (session) is still using it
-- β
MySQL
SHOW DATABASES;
DROP DATABASE IF EXISTS DemoDB;
[!WARNING] β οΈ
DROP DATABASEis instant and permanent. There is no recycle bin, no confirmation, no undo. On a real, live (production) server, ordinary accounts should not even be allowed to run it. See Chapter 56 before you ever type it on a real server.
7.2 π Schemas β the folder system
π Analogy: A database is a filing cabinet. Schemas are the labelled drawers: Sales, HR, Finance. Without drawers, 400 tables sit in one pile.
-- β
MSSQL: schemas are real, named containers
CREATE SCHEMA sales;
GO
CREATE SCHEMA hr;
GO
CREATE TABLE sales.orders (order_id INT PRIMARY KEY);
CREATE TABLE hr.employees (employee_id INT PRIMARY KEY);
-- Always reference with schema.table
SELECT * FROM sales.orders;
π The big structural difference:
- In MSSQL, a database contains schemas, and schemas contain tables. The default schema is
dbo(database owner).dbo.customersandcustomersmean the same thing for most users.- In MySQL, schema and database are the same thing.
CREATE SCHEMAis literally a synonym forCREATE DATABASE. To group things, you either use separate databases or a naming convention likesales_orders.
-- π¦ MySQL: these two statements are identical
CREATE SCHEMA IF NOT EXISTS shop_analytics;
CREATE DATABASE IF NOT EXISTS shop_analytics; -- does nothing: the schema above IS this database
-- Cross-database queries work naturally
CREATE TABLE IF NOT EXISTS shop_analytics.customer_scores (
customer_id INT PRIMARY KEY,
score INT NOT NULL
);
SELECT * FROM ShopDB.customers c
JOIN shop_analytics.customer_scores s ON s.customer_id = c.customer_id;
[!IMPORTANT] π― When to use schemas (MSSQL):
- Grouping by business area:
sales,inventory,hr,reporting- Applying permissions in bulk: βthe reporting team can read everything in the
reportingschemaβ β oneGRANTinstead of 200- Keeping raw imported data (a staging area) apart from clean data:
staging.raw_ordersβdbo.orders
[!TIP] π‘ Pro tip (MSSQL): Always write
dbo.customers, never barecustomers. Leaving the schema out makes SQL Server look the name up every time the query runs, can fill its memory with duplicate query plans, and breaks as soon as two schemas contain a table with the same name.
7.3 π§ͺ Try it yourself
- Create a database called
PracticeDBwithutf8mb4(MySQL) or default settings (MSSQL). - In MSSQL, create schemas
salesandarchive, and put one table in each. - List all databases on your server. Find the system databases (
master,mysql,information_schema) and read one sentence about what each does.
π§ In practice β databases and schemas
How to use it. Create the database, then group related tables into schemas β
sales.orders,hr.employees. In SQL Server a schema is a named container inside a database; in MySQL the word schema is a synonym for database, which is the main thing to keep straight when moving between them. Expected result: related tables are grouped, and you can grant permissions to a whole group at once.When to use it. Once a database exceeds a couple of dozen tables, or when different teams or modules own different parts of it.
Where to use it. Multi-module systems. Scenario: a company system holds sales, HR, and reporting tables in one SQL Server database. Putting them in three schemas lets you give the HR application access to
hr.*and nothing else β one grant, not one per table, and new HR tables are covered automatically.When not to use it. For a small application with fifteen tables, schemas add naming friction and buy little. And remember the terminology gap: MySQL has no SQL Server-style schema-inside-a-database, so a design that leans on them does not port directly.
Best practices. In SQL Server, always qualify objects with their schema (
dbo.customers, notcustomers) β unqualified names force a per-user name resolution that is both slower and a source of genuinely confusing bugs when two users have different default schemas. Grant permissions at the schema level rather than table by table; it is less work and it does not silently leave the next new table unprotected.
8. Creating tables
| ποΈ Level | β±οΈ Time | π― After this chapter you canβ¦ |
|---|---|---|
| π’ Beginner | 20 min | Write a CREATE TABLE statement Β· Decide which columns are required Β· Give columns sensible default values Β· Copy a table |
[!NOTE] π In plain words:
CREATE TABLEis where you draw the blueprint: the columns, their types, and the rules that keep bad data out.
π Analogy: Designing a paper form before you print a thousand copies. You decide which boxes exist, what may be written in each (a date, a number, a name), and which boxes are compulsory. Every row is one filled-in copy of that form.
8.1 π§± The anatomy of CREATE TABLE
CREATE TABLE table_name (
column_name DATA_TYPE [NULL | NOT NULL] [DEFAULT value] [constraints],
...
[table-level constraints]
);
Anything in [square brackets] is optional.
A fully annotated real example:
-- β
MSSQL
CREATE TABLE product_reviews (
review_id INT IDENTITY(1,1), -- auto-numbered
product_id INT NOT NULL, -- required
customer_id INT NOT NULL, -- required
rating TINYINT NOT NULL, -- 1 to 5
title NVARCHAR(120) NULL, -- optional
body NVARCHAR(MAX) NULL, -- optional, long
is_verified BIT NOT NULL DEFAULT 0, -- default value
created_at DATETIME2(0) NOT NULL DEFAULT SYSDATETIME(),
CONSTRAINT pk_product_reviews PRIMARY KEY (review_id),
CONSTRAINT fk_reviews_product FOREIGN KEY (product_id) REFERENCES products(product_id),
CONSTRAINT fk_reviews_customer FOREIGN KEY (customer_id) REFERENCES customers(customer_id),
CONSTRAINT ck_reviews_rating CHECK (rating BETWEEN 1 AND 5),
CONSTRAINT uq_reviews_one_per_customer UNIQUE (product_id, customer_id)
);
-- β
MySQL
CREATE TABLE product_reviews (
review_id INT AUTO_INCREMENT,
product_id INT NOT NULL,
customer_id INT NOT NULL,
rating TINYINT NOT NULL,
title VARCHAR(120) NULL,
body TEXT NULL,
is_verified BOOLEAN NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT pk_product_reviews PRIMARY KEY (review_id),
CONSTRAINT fk_reviews_product FOREIGN KEY (product_id) REFERENCES products(product_id),
CONSTRAINT fk_reviews_customer FOREIGN KEY (customer_id) REFERENCES customers(customer_id),
CONSTRAINT ck_reviews_rating CHECK (rating BETWEEN 1 AND 5),
CONSTRAINT uq_reviews_one_per_customer UNIQUE (product_id, customer_id)
) ENGINE=InnoDB;
The CONSTRAINT lines at the bottom are the tableβs rules: the PRIMARY KEY is the rowβs unique ID, each FOREIGN KEY must point at a real product or customer, the CHECK keeps the rating between 1 and 5, and UNIQUE blocks duplicates. Chapter 9 explains each one.
[!NOTE] π Read that last constraint again.
UNIQUE (product_id, customer_id)encodes a business rule in the database itself: one review per customer per product. No amount of buggy application code can ever violate it. This is the superpower of a relational database β rules that cannot be bypassed.
8.2 π³οΈ NULL vs NOT NULL β decide for every column
NULL means βno value β unknown or not applicableβ. It is not zero, and it is not empty text.
| Β | NOT NULL |
NULL (the default) |
|---|---|---|
| Meaning | βThis fact is requiredβ | βThis fact may be unknown or not applicableβ |
| Example | customers.email |
orders.ship_date (not shipped yet) |
| Effect | Insert fails without a value | Missing value is allowed |
[!TIP] π‘ Pro tip: Make every column
NOT NULLunless you have a real reason to allow empty values. Columns that allowNULLmake every query that touches them harder to get right (see Chapter 15). Ask: βCan this genuinely be unknown in the real world?β A ship date genuinely can be. An email address on a signup form cannot.
8.3 π DEFAULT values
-- β
MSSQL
CREATE TABLE support_tickets (
ticket_id INT IDENTITY(1,1) PRIMARY KEY,
subject NVARCHAR(200) NOT NULL,
priority VARCHAR(10) NOT NULL DEFAULT 'Normal',
status VARCHAR(20) NOT NULL DEFAULT 'Open',
opened_at DATETIME2(0) NOT NULL DEFAULT SYSDATETIME(),
opened_by NVARCHAR(100) NOT NULL DEFAULT SUSER_SNAME() -- the login name of whoever added the row
);
-- β
MySQL
CREATE TABLE support_tickets (
ticket_id INT AUTO_INCREMENT PRIMARY KEY,
subject VARCHAR(200) NOT NULL,
priority VARCHAR(10) NOT NULL DEFAULT 'Normal',
status VARCHAR(20) NOT NULL DEFAULT 'Open',
opened_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
opened_by VARCHAR(100) NOT NULL DEFAULT (CURRENT_USER())
);
Now this insert works even though we supplied only one column:
INSERT INTO support_tickets (subject) VALUES ('Laptop will not power on');
[!IMPORTANT] π― When to use DEFAULT: status columns, created-at timestamps, counters starting at 0, yes/no flags, and βcreated byβ columns that record who did what. Anywhere the sensible value is obvious and you do not want every insert statement to repeat it.
8.4 π Creating a table from a query
Useful for a temporary recovery copy before a small practice change, and for building report tables. A table copy is not a database backup.
-- β
MSSQL: SELECT ... INTO creates the table and copies rows
SELECT *
INTO products_backup_2026_09
FROM products;
-- Structure only, zero rows (a false condition copies nothing)
SELECT *
INTO products_empty_copy
FROM products
WHERE 1 = 0;
-- β
MySQL: CREATE TABLE ... AS SELECT (often called CTAS)
CREATE TABLE products_backup_2026_09 AS
SELECT * FROM products;
-- Structure only, zero rows
CREATE TABLE products_empty_copy AS
SELECT * FROM products WHERE 1 = 0;
-- Copies columns and indexes, but not foreign keys
CREATE TABLE products_clone LIKE products;
[!WARNING] β οΈ Important limitation:
SELECT INTOandCREATE TABLE AS SELECTcopy the data and column types only. They do not copy primary keys, foreign keys, indexes, defaults, or check constraints. The copy is a bag of rows, not a properly protected table. MySQLβsCREATE TABLE ... LIKEpreserves columns and indexes but omits foreign keys; recreate and verify those separately.
[!TIP] π‘ Pro tip β the 30-second safety net. Before any risky
UPDATEorDELETEon production, take a copy first:-- π₯ MSSQL (MySQL: CREATE TABLE orders_before_fix AS SELECT * FROM orders WHERE ...) SELECT * INTO orders_before_fix FROM orders WHERE order_date >= '2026-01-01';It costs seconds. It has saved thousands of careers.
8.5 π§ͺ Try it yourself
- Create a
wishliststable linkingcustomersandproducts, with acreated_atdefault and a unique constraint preventing the same product twice per customer. - Create it with the composite primary key
(customer_id, product_id)instead of a surrogate ID (a made-up ID number β explained in 9.2). Which do you prefer, and why? - Make a backup copy of
products, then confirm with the constraint-listing query from 9.6 that the copy has no primary key.
π§ In practice β creating tables
How to use it. Write
CREATE TABLE, naming each column with its type, its nullability, and its default. Declare the primary key in the same statement, and add foreign keys as soon as the table it points at exists. Expected result: running your script on an empty server reproduces the structure exactly β which is what makes it a reliable thing to commit to version control.When to use it. Whenever a new kind of thing enters the system. βA new kind of thingβ means a new noun, not a new attribute β a new attribute is a column on an existing table.
Where to use it. Schema design and migrations. Scenario: adding wishlists to the shop means a
wishliststable and awishlist_itemsbridge table, because a customer has many wishlists and a wishlist holds many products β the same many-to-many shape asorder_items.When not to use it. Do not create a table for something that is really a column, and do not create the βone table with a
typecolumn and forty mostly-NULLcolumnsβ design β that is an anti-pattern covered in Β§66.1. AvoidSELECT * INTO/CREATE TABLE AS SELECTfor anything permanent: it copies the data and the column types but not the keys, constraints, indexes, or defaults, so the copy has none of the protection the original had.Best practices. Decide nullability deliberately for every column β
NULLshould mean βgenuinely unknown or not applicableβ, never βwe could not be botheredβ, because every nullable column becomes a special case in every later query. Keep theCREATE TABLEscripts in source control and change them only through migrations (Chapter 64); a schema that exists only inside a running server is a schema nobody can review or rebuild.
9. Constraints, the rules that protect your data
| ποΈ Level | β±οΈ Time | π― After this chapter you canβ¦ |
|---|---|---|
| π’ Beginner | 30 min | Use the six kinds of rules (constraints) Β· Link tables with foreign keys Β· Choose what happens when a linked row is deleted |
[!NOTE] π In plain words: Constraints are rules the database refuses to break. They are your last line of defence β the one that still works when the app has a bug, when someone runs SQL by hand, or when a new developer joins.
π Analogy: Constraints are the bouncers at the club door. The app might be careless about who it invites, but the bouncer checks every single person, every single time, with no exceptions and no bad days.
9.1 ποΈ The six constraint types
| Constraint | Guarantees | Real-world meaning in ShopDB |
|---|---|---|
NOT NULL |
A value must be present | Every customer must have an email |
UNIQUE |
No two rows share the value | No two customers share an email |
PRIMARY KEY |
Unique and not null | Each customer has exactly one ID |
FOREIGN KEY |
The value exists in another table | An order cannot reference customer #999 if there is no #999 |
CHECK |
The value passes a test you write | A rating is between 1 and 5 |
DEFAULT |
A value is supplied when omitted | New orders start as βPendingβ |
9.2 π PRIMARY KEY
-- Single-column, inline
CREATE TABLE brands (
brand_id INT PRIMARY KEY,
brand_name VARCHAR(80) NOT NULL
);
-- Named constraint (preferred: you can drop and reference it later)
CREATE TABLE brands2 (
brand_id INT NOT NULL,
brand_name VARCHAR(80) NOT NULL,
CONSTRAINT pk_brands2 PRIMARY KEY (brand_id)
);
-- Composite key: two columns TOGETHER form the ID; uniqueness comes from the COMBINATION
CREATE TABLE order_items_demo (
order_id INT NOT NULL,
product_id INT NOT NULL,
quantity INT NOT NULL,
CONSTRAINT pk_order_items_demo PRIMARY KEY (order_id, product_id)
);
The rules of a primary key:
- It is unique β no duplicates, ever.
- It is never NULL.
- There is exactly one per table.
- It should be stable β never updated after insert.
- It automatically gets an index (a clustered one by default in MSSQL and in MySQLβs InnoDB engine β explained just below).
π A hidden but important difference: In MSSQL, the primary key becomes a clustered index by default β the rows are physically stored in primary-key order, like words in a dictionary. In MySQL/InnoDB this is always true, and every other index on the table also stores a copy of the primary key. So a long primary key (such as a 200-character email) makes every index on that table bigger and slower in MySQL.
π Natural key vs surrogate key β a decision you will make on every table. A natural key is real-world data that is already unique, such as an email address or an ISBN. A surrogate key is a number the database invents purely to be the ID:
| Β | Natural key (real data) | Surrogate key (meaningless ID) |
|---|---|---|
| Example | email, isbn, country_code |
customer_id INT IDENTITY |
| β Pros | No extra column, meaningful, no join needed for the value | Small, fast, never changes, private |
| β Cons | Can change (people change email!), often wide, exposes data | Extra column, needs a UNIQUE on the natural key too |
| π― Verdict | Fine for tiny fixed lookups (country_code CHAR(2)) |
Default choice for almost every business table |
[!TIP] π‘ Pro tip: Use a surrogate key as the primary key and put a
UNIQUEconstraint on the natural key. You get fast stable joins and the real-world uniqueness rule.ShopDB.customersdoes exactly this:customer_idis the PK,UNIQUE.
9.3 π FOREIGN KEY and referential integrity
A foreign key links a row to a row in another table. Referential integrity means every link points at something that really exists β an order can never belong to a customer who does not exist.
-- β
Works in BOTH
CREATE TABLE order_notes (
note_id INT NOT NULL,
order_id INT NOT NULL,
note_text VARCHAR(500) NOT NULL,
CONSTRAINT pk_order_notes PRIMARY KEY (note_id),
CONSTRAINT fk_notes_order FOREIGN KEY (order_id)
REFERENCES orders(order_id)
ON DELETE CASCADE
ON UPDATE NO ACTION
);
Watch it protect you:
-- β This FAILS: customer 9999 does not exist
INSERT INTO orders (customer_id, order_date) VALUES (9999, '2026-09-01');
-- MSSQL: The INSERT statement conflicted with the FOREIGN KEY constraint...
-- MySQL: Cannot add or update a child row: a foreign key constraint fails...
What happens to linked rows when a row is deleted? The row being pointed at is the parent (an order); the rows pointing at it are its children (that orderβs notes). You choose the behaviour:
| Action | What it does | π― Use when |
|---|---|---|
NO ACTION / RESTRICT |
Blocks the delete (the default) | The child rows are important records. Safest default. |
CASCADE |
Deletes the children too | Children are meaningless alone: order items, cart lines, note attachments |
SET NULL |
Sets the childβs FK to NULL (column must be nullable) | The link is optional: an order keeps existing when its sales rep leaves |
SET DEFAULT |
Sets the childβs FK to its default | Rare; a βUnassignedβ placeholder row exists |
-- β
Works in BOTH. Shown as ALTER statements so each one runs on its own;
-- inside CREATE TABLE you would write the same CONSTRAINT ... line.
-- π― CASCADE: deleting an order should delete its attachments
-- (a new child table, because order_items already cascades from orders and
-- MSSQL refuses a second cascade path to the same table β see the note below)
CREATE TABLE order_attachments (
attachment_id INT PRIMARY KEY,
order_id INT NOT NULL,
file_name VARCHAR(200) NOT NULL
);
ALTER TABLE order_attachments
ADD CONSTRAINT fk_attachments_order FOREIGN KEY (order_id)
REFERENCES orders(order_id) ON DELETE CASCADE;
-- π― SET NULL: REPLACE the existing Chapter 4 employee FK; do not add a second FK.
The original fk_orders_employee uses the default delete action. Keeping it alongside a new SET NULL constraint does not replace that rule. Run only your engineβs replacement below; employee_id is already nullable in ShopDB.
-- π₯ SQL Server
ALTER TABLE orders DROP CONSTRAINT fk_orders_employee;
ALTER TABLE orders ADD CONSTRAINT fk_orders_employee FOREIGN KEY (employee_id)
REFERENCES employees(employee_id) ON DELETE SET NULL;
-- π¦ MySQL
ALTER TABLE orders DROP FOREIGN KEY fk_orders_employee;
ALTER TABLE orders ADD CONSTRAINT fk_orders_employee FOREIGN KEY (employee_id)
REFERENCES employees(employee_id) ON DELETE SET NULL;
-- β
Works in BOTH: the independent product example follows.
-- π― RESTRICT: never delete a product that has been sold
ALTER TABLE order_items
ADD CONSTRAINT fk_items_product_demo FOREIGN KEY (product_id)
REFERENCES products(product_id) ON DELETE NO ACTION;
[!WARNING] β οΈ
ON DELETE CASCADEis a loaded gun. Deleting one customer can silently erase their orders, those ordersβ items, and those ordersβ payments β thousands of rows, no warning. Use it only where the child truly cannot exist alone. For customers, prefer a soft delete β marking the row as inactive (is_active = 0) instead of really deleting it (Chapter 19). That is what real online shops do.
π MSSQL restriction: MSSQL refuses any set-up where one delete could cascade into the same table along two different routes (the error says βmay cause cycles or multiple cascade pathsβ). MySQL allows more, but has its own limit on how deep a chain of cascades can go. If you meet this error, the fix is usually to handle the delete in a stored procedure (a saved SQL program, Chapter 37) or a trigger (Chapter 39) instead.
[!CAUTION] π Common mistake (MySQL): Foreign keys are silently ignored by the
MyISAMstorage engine. If your FKs seem to do nothing, runSHOW CREATE TABLE your_table;and confirm it saysENGINE=InnoDB.
9.4 βοΈ UNIQUE
-- (customers.email already got its UNIQUE in Chapter 4; a second identical
-- constraint would only build a redundant index β so these use new rules)
-- Single column: no two suppliers with the same company name
ALTER TABLE suppliers ADD CONSTRAINT uq_suppliers_company UNIQUE (company_name);
-- Composite: the COMBINATION must be unique
ALTER TABLE employees
ADD CONSTRAINT uq_employees_full_name UNIQUE (first_name, last_name);
| Β | PRIMARY KEY |
UNIQUE |
|---|---|---|
| How many per table | Exactly 1 | As many as you like |
| Allows NULL | β Never | β Yes |
| NULL behaviour | n/a | π MSSQL: only ONE NULL allowed. MySQL: many NULLs allowed |
| Creates an index | β Clustered by default | β Non-clustered |
π That NULL difference matters in practice. A nullable
tax_id UNIQUEcolumn: MySQL happily stores 500 customers with no tax ID; MSSQL rejects the second one. The MSSQL fix is a filtered unique index β a uniqueness rule that only covers the rows you choose:-- π₯ MSSQL: unique only among rows that actually have a value ALTER TABLE customers ADD tax_id VARCHAR(30) NULL; GO CREATE UNIQUE INDEX uq_customers_taxid ON customers(tax_id) WHERE tax_id IS NOT NULL;
9.5 π CHECK constraints
βΉοΈ Note:
ShopDBalready createdck_products_price,ck_items_discount, and the tier check in Chapter 4. Re-adding a constraint name that already exists fails with βThere is already an object named βck_products_priceβ in the databaseβ β so the examples below use_demosuffixes to stay runnable on your existing database.
-- β
Works in BOTH (MySQL enforces CHECK from version 8.0.16 onward)
ALTER TABLE products
ADD CONSTRAINT ck_products_price_demo CHECK (unit_price >= 0);
ALTER TABLE order_items
ADD CONSTRAINT ck_items_discount_demo CHECK (discount >= 0 AND discount <= 0.9);
ALTER TABLE orders
ADD CONSTRAINT ck_orders_dates CHECK (ship_date IS NULL OR ship_date >= order_date);
ALTER TABLE customers
ADD CONSTRAINT ck_customers_email_shape CHECK (email LIKE '%_@_%._%');
[!NOTE] π Read
ck_orders_datescarefully. It says: βeither the order has not shipped, or it shipped on or after the order date.β You have just made time travel impossible in your database. No application bug can ever create an order shipped before it was placed.
[!WARNING] β οΈ MySQL versions before 8.0.16 parsed
CHECKand then silently ignored it. If you are on an older MySQL, your check constraints are decoration, not enforcement. Verify withSELECT VERSION();.
[!TIP] π‘ Pro tip: A
CHECKconstraint can reference multiple columns in the same row, but not other tables and not subqueries. For cross-table rules, use a trigger (Chapter 39) or handle it in a stored procedure.
9.6 π§ Adding, dropping, and inspecting constraints
-- β
Works in BOTH: add
ALTER TABLE products ADD CONSTRAINT ck_products_reorder CHECK (reorder_level >= 0);
-- β
Works in BOTH: drop
ALTER TABLE products DROP CONSTRAINT ck_products_reorder;
-- π¦ MySQL also has type-specific drop syntax
ALTER TABLE products DROP FOREIGN KEY fk_products_supplier;
ALTER TABLE suppliers DROP INDEX uq_suppliers_company; -- the UNIQUE added in 9.4
ALTER TABLE brands2 DROP PRIMARY KEY; -- from 9.2 (allowed because brands2 has no AUTO_INCREMENT column)
Inspecting what constraints exist:
-- π₯ MSSQL
SELECT
t.name AS table_name,
c.name AS constraint_name,
c.type_desc AS constraint_type
FROM sys.objects c
JOIN sys.tables t ON t.object_id = c.parent_object_id
WHERE c.type IN ('PK','UQ','F','C','D')
ORDER BY t.name, c.type_desc;
-- π¦ MySQL
SELECT table_name, constraint_name, constraint_type
FROM information_schema.table_constraints
WHERE table_schema = 'ShopDB'
ORDER BY table_name, constraint_type;
[!TIP] π‘ Pro tip β name every constraint. An automatically generated name like
CK__products__unit___3B75D760is impossible to use in a change script, and it is different on every server. Adopt a convention and never break it:
Prefix Meaning Example pk_Primary key pk_ordersfk_Foreign key fk_orders_customeruq_Unique uq_customers_emailck_Check ck_products_pricedf_Default df_orders_statusix_Index ix_orders_order_date
9.7 π§ͺ Try it yourself
- Try to insert a customer with a duplicate email. Read the error. Now try a
loyalty_tierof'Diamond'. Read that error too. - Try to delete customer #1 (who has orders). Which constraint stops you, and what exactly does the message say?
- π₯ SQL Server: test a
CHECKrejecting futurehire_datevalues. π¦ MySQL: first demonstrate thatCHECK (hire_date <= CURRENT_DATE)is rejected because nondeterministic functions are forbidden. For a deterministic constraint exercise use an explicit fixed cutoff date; for a rolling βtodayβ rule validate on each write in a trigger or application. A fixed cutoff is not the same business rule. See MySQL CHECK restrictions. - Delete order 1000 and observe what happens to its rows in
order_itemsandpayments. Explain why.
π§ In practice β constraints
How to use it. Attach the rule to the column or table:
NOT NULL,UNIQUE,CHECK (unit_price >= 0),PRIMARY KEY,FOREIGN KEY ... REFERENCES, andDEFAULT. Expected result: anINSERTthat breaks the rule is rejected by the database with a named error, no matter which application, script, or person attempted it.When to use it. For every rule that must hold for all data, always. If you find yourself writing the same validation in two applications, that rule belongs in the database instead of β or as well as β the code.
Where to use it. Any table holding data that matters. Scenario: a
CHECK (quantity > 0)onorder_itemsmeans a bug in a new mobile app cannot create a line with a negative quantity. The application should still validate for a friendly error message, but the constraint is what makes the bad row impossible rather than merely unlikely.When not to use it. Constraints are the wrong place for rules that change often (promotional pricing logic), rules that need data from elsewhere, or rules that are advisory rather than absolute β those belong in application code. A
CHECKthat has to be altered every quarter is a maintenance burden and a source of failed deployments.Best practices. Name your constraints explicitly (
CK_order_items_quantity_positive) instead of letting the engine generate a name β auto-generated names differ between environments, which makes migration scripts non-portable and error messages useless. Choose foreign-key behaviour deliberately:ON DELETE CASCADEis convenient and genuinely dangerous, because deleting one row can silently remove thousands.ON DELETE RESTRICT(refuse) is the safer default for anything financial.
10. Auto-numbering: IDENTITY vs AUTO_INCREMENT
| ποΈ Level | β±οΈ Time | π― After this chapter you canβ¦ |
|---|---|---|
| π’ Beginner | 20 min | Let the database number rows for you Β· Get the ID of the row you just added Β· Know when a GUID is the better ID |
[!NOTE] π In plain words: You should not have to invent a new ID number for every row you insert. Auto-numbering lets the database hand out
1, 2, 3, 4β¦automatically and guarantees no two rows get the same one.
π Analogy: The ticket dispenser at a bakery counter. You do not choose your number; you pull the next one. Two customers can never get the same ticket, even if they pull at the same instant.
10.1 π₯ MSSQL: IDENTITY
CREATE TABLE invoices (
invoice_id INT IDENTITY(1,1) PRIMARY KEY, -- start at 1, step by 1
amount DECIMAL(10,2) NOT NULL
);
-- IDENTITY(seed, increment): seed = the first number, increment = the step
-- IDENTITY(1000, 1) β 1000, 1001, 1002 ...
-- IDENTITY(1, 10) β 1, 11, 21, 31 ...
-- Insert WITHOUT the identity column β the engine fills it
INSERT INTO invoices (amount) VALUES (250.00);
-- Get the ID that was just generated (3 ways, use SCOPE_IDENTITY)
SELECT SCOPE_IDENTITY() AS best_choice; -- β
the ID from YOUR last insert, in THIS piece of code
SELECT @@IDENTITY AS risky; -- β οΈ can return an ID created by a TRIGGER instead!
SELECT IDENT_CURRENT('invoices') AS also_risky; -- β οΈ the latest ID from ANYONE's insert
[!WARNING] β οΈ Use
SCOPE_IDENTITY(), not@@IDENTITY. If a trigger oninvoicesinserts a row into an audit table,@@IDENTITYreturns the audit tableβs ID, silently corrupting your logic. This is a genuine production bug that has cost companies real money.
The modern, best way β OUTPUT. It hands the new rows straight back to you as a result grid, including their new IDs:
-- β
MSSQL: works correctly even for multi-row inserts
INSERT INTO invoices (amount)
OUTPUT inserted.invoice_id, inserted.amount
VALUES (100.00), (200.00), (300.00);
Inserting your own ID number. Normally SQL Server refuses to let you choose the ID. IDENTITY_INSERT switches that protection off for one table, for a moment:
SET IDENTITY_INSERT invoices ON;
INSERT INTO invoices (invoice_id, amount) VALUES (5000, 999.00);
SET IDENTITY_INSERT invoices OFF; -- always turn it back off!
Resetting the counter (DBCC = SQL Serverβs Database Console Commands, its maintenance toolbox):
DBCC CHECKIDENT ('invoices', RESEED, 6000); -- next insert gets 6001
DBCC CHECKIDENT ('invoices', NORESEED); -- just report the current value
-- β οΈ Never reseed BELOW the highest existing value: the next insert collides with a key that already exists
10.2 π¦ MySQL: AUTO_INCREMENT
CREATE TABLE invoices (
invoice_id INT AUTO_INCREMENT PRIMARY KEY,
amount DECIMAL(10,2) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=1000; -- optional starting value
INSERT INTO invoices (amount) VALUES (250.00);
-- Get the generated ID
SELECT LAST_INSERT_ID(); -- β
per-connection, safe from other users
[!TIP] π‘
LAST_INSERT_ID()belongs to your connection only. Another user inserting at the same moment cannot change your value. For a multi-row insert it returns the ID of the first generated row. Do not infer all later IDs by adding one without controlling increment/offset settings, statement mode and ignored/conflicting rows; retrieve rows through an explicit unique correlation key.
Inserting explicit values and resetting:
-- No special switch needed; just supply the value
INSERT INTO invoices (invoice_id, amount) VALUES (5000, 999.00);
-- Reset the counter. Ask for a number lower than an existing ID and MySQL quietly uses (highest ID + 1)
ALTER TABLE invoices AUTO_INCREMENT = 1;
10.3 π Side-by-side comparison
| Task | π₯ MSSQL | π¦ MySQL |
|---|---|---|
| Declare | INT IDENTITY(1,1) |
INT AUTO_INCREMENT |
| Custom start | IDENTITY(1000,1) |
AUTO_INCREMENT=1000 on the table |
| Custom step | IDENTITY(1,10) |
Server variable auto_increment_increment |
| Get last ID | SCOPE_IDENTITY() |
LAST_INSERT_ID() |
| Insert explicit value | SET IDENTITY_INSERT t ON |
Just insert it |
| Reset | DBCC CHECKIDENT(...) |
ALTER TABLE t AUTO_INCREMENT = n |
| Per table limit | One identity column | One auto_increment column (must be indexed) |
| Gaps after rollback | β Yes, gaps happen | β Yes, gaps happen |
10.4 π³οΈ Gaps are normal β stop trying to fix them
-- π₯ MSSQL
BEGIN TRANSACTION;
INSERT INTO invoices (amount) VALUES (10.00); -- takes ID 7
ROLLBACK; -- row is gone... but 7 is used up
INSERT INTO invoices (amount) VALUES (20.00); -- gets ID 8, not 7
-- π¦ MySQL: identical, except a transaction starts with START TRANSACTION
START TRANSACTION;
INSERT INTO invoices (amount) VALUES (10.00);
ROLLBACK;
INSERT INTO invoices (amount) VALUES (20.00); -- the rolled-back ID is skipped
[!NOTE] π In plain words: Auto-numbers promise that no two rows share a number β they do not promise that the numbers have no gaps. A cancelled (rolled-back) insert, a failed insert, or a deleted row leaves a permanent hole. This is deliberate: to avoid holes, every user would have to wait in one single queue to insert, and a busy database would crawl.
[!WARNING] β οΈ Never use an auto-number as an invoice number, receipt number, or anything legally sequential. Auditors require numbers with no gaps. Generate those yourself in a small counter table (slower, but gap-free), or use a numbering scheme with a date prefix.
10.5 π The alternative: GUIDs / UUIDs
[!NOTE] π In plain words: a GUID (Microsoftβs name) or UUID (everyone elseβs name) is a 36-character random ID such as
3f2504e0-4f89-11d3-9a0c-0305e82c3301. It is so random that thousands of computers can create IDs at the same moment without ever producing the same one.
-- π₯ MSSQL
CREATE TABLE sessions (
session_id UNIQUEIDENTIFIER NOT NULL DEFAULT NEWID() PRIMARY KEY,
user_id INT NOT NULL
);
-- NEWSEQUENTIALID() generates GUIDs that always increase, which keeps the index tidy
-- π¦ MySQL
CREATE TABLE sessions (
session_id CHAR(36) NOT NULL DEFAULT (UUID()) PRIMARY KEY,
user_id INT NOT NULL
);
-- Better for storage/indexing: BINARY(16) with UUID_TO_BIN(UUID(), 1)
| Β | Auto-number (INT) | GUID / UUID |
|---|---|---|
| Size | 4 bytes | 16 bytes (36 as text!) |
| Index performance | β Excellent β new rows always go at the end | β οΈ Random values scatter new rows all over the index, slowing inserts |
| Guessable by outsiders | β οΈ Yes (/orders/1001 β try 1002) |
β No |
| Generated by the app before insert | β No | β Yes β useful for apps that work offline or run on many servers |
| Merging data from multiple servers | β Collisions | β No collisions |
[!TIP] π‘ The professional compromise used by many real systems: keep an
INT IDENTITYas the internal primary key (fast joins, small indexes) and add aUNIQUEGUID column as the ID shown to the outside world (in web addresses and apps). Best of both.
10.6 π― When to use which key strategy
| Your situation | Use |
|---|---|
| A normal business table (customers, orders, products) | INT IDENTITY / AUTO_INCREMENT |
| More than ~2 billion rows expected (events, logs, sensor data) | BIGINT auto-number |
| IDs must not be guessable in a public URL | INT internally + a UNIQUE GUID for the outside world |
| Rows are created offline, or merged from several servers | GUID / UUID |
| The application needs the ID before inserting | A sequence (Ch 41) or a GUID |
| Legally gapless numbering (invoices, receipts) | β Not an auto-number β a controlled counter table |
A pure link/bridge table (order_items) |
β No surrogate at all β use the composite key |
[!CAUTION] π Common mistake: adding an
id INT IDENTITYprimary key to a bridge table that already has a perfectly good natural key of(order_id, product_id). It adds a column, adds an index, and β worst of all β stops the database preventing duplicates, because now two rows with the same order and product are βdifferentβ rows.
10.7 π§ͺ Try it yourself
- Insert a product without specifying
product_id. Retrieve the generated ID immediately, using the correct function for your engine. - Start a transaction, insert a row, roll it back, then insert again. Prove to yourself the gap is permanent.
- Insert three rows in one statement and capture all three generated IDs (
OUTPUTin MSSQL; a unique per-row correlation key followed by a query in MySQL; do not assume consecutive IDs).
π§ In practice β auto-numbering
How to use it. Declare the key column as
INT IDENTITY(1,1)in SQL Server orINT AUTO_INCREMENTin MySQL, then simply omit it from yourINSERTβ the engine assigns the next value. Retrieve what it assigned withSCOPE_IDENTITY()(MSSQL) orLAST_INSERT_ID()(MySQL). Expected result: the engine generates identifiers; aPRIMARY KEYorUNIQUEconstraint enforces uniqueness.IDENTITYby itself is not a uniqueness constraint.When to use it. For the surrogate primary key of nearly every table β a meaningless number whose only job is to identify the row, so that no real-world value has to stay unique forever.
Where to use it. Almost every table in a typical system. Scenario: ShopDBβs
customers.customer_id. Email would seem like a natural key, but people change email addresses, and a key that changes has to be updated in every table that references it. A number that means nothing never has to change.When not to use it. Do not rely on auto-numbers being gapless. A rolled-back transaction consumes the value permanently, so
1, 2, 5, 6is normal and correct. If a regulator requires unbroken invoice numbering, that is a separate, deliberately serialised counter β not the primary key. Do not use auto-increment integers as public identifiers in URLs either: they let anyone count your customers and guess neighbouring records. Use a UUID or a separate public token for that.Best practices. Use
SCOPE_IDENTITY()rather than@@IDENTITYin SQL Server β@@IDENTITYreturns the last identity generated in the session, so a trigger that inserts into an audit table will hand you the audit rowβs id instead of your own. That bug is subtle, intermittent, and appears only once a trigger is added months later.
11. ALTER and DROP
| ποΈ Level | β±οΈ Time | π― After this chapter you canβ¦ |
|---|---|---|
| π’ Beginner | 20 min | Add, change, rename, and remove columns Β· Tell DELETE, TRUNCATE, and DROP apart Β· Change live tables safely |
[!NOTE] π In plain words:
ALTERchanges an existing tableβs design without losing its data.DROPdestroys objects completely. One is a renovation; the other is a demolition.
π Analogy:
ALTERis adding a new room to a house while the family still lives in it.DROPis knocking the whole house down β and everything inside goes with it.
11.1 β Adding columns
-- β
Works in BOTH
ALTER TABLE customers ADD date_of_birth DATE NULL;
-- π₯ MSSQL: multiple columns in one statement
ALTER TABLE customers ADD
marketing_opt_in BIT NOT NULL CONSTRAINT df_customers_marketing_opt_in DEFAULT 0,
referral_code VARCHAR(20) NULL;
-- π¦ MySQL: needs ADD COLUMN for each, and supports positioning
ALTER TABLE customers
ADD COLUMN marketing_opt_in BOOLEAN NOT NULL DEFAULT 0,
ADD COLUMN referral_code VARCHAR(20) NULL AFTER email;
[!WARNING] β οΈ Adding a
NOT NULLcolumn to a table that already has rows requires aDEFAULT, otherwise the existing rows would have no value and the statement fails. On very large tables, adding aNOT NULLcolumn with a default can rewrite the entire table β check your engine version and plan it for a quiet, pre-announced time (a maintenance window).
11.2 βοΈ Changing a column
π This is one of the biggest syntax differences between the two engines.
-- π₯ MSSQL: ALTER COLUMN, and you restate only the type/nullability
ALTER TABLE customers ALTER COLUMN phone VARCHAR(40);
ALTER TABLE customers ALTER COLUMN city NVARCHAR(60) NOT NULL;
-- π¦ MySQL: MODIFY changes the definition; CHANGE also renames
ALTER TABLE customers MODIFY COLUMN phone VARCHAR(40);
ALTER TABLE customers MODIFY COLUMN city VARCHAR(60) NOT NULL;
-- CHANGE = rename + redefine (you must restate the full definition)
ALTER TABLE customers CHANGE COLUMN phone phone_number VARCHAR(40) NULL;
ALTER TABLE customers CHANGE COLUMN phone_number phone VARCHAR(40) NULL; -- and back again
[!WARNING] β οΈ MySQL
MODIFYreplaces the ENTIRE definition. If the column wasNOT NULL DEFAULT 'x'and you writeMODIFY COLUMN phone VARCHAR(40), you have just silently dropped both theNOT NULLand theDEFAULT. Always restate everything you want to keep.
Safe type changes vs dangerous ones:
| Change | Risk |
|---|---|
VARCHAR(50) β VARCHAR(100) |
β Safe, widening |
INT β BIGINT |
β Safe, widening |
VARCHAR(100) β VARCHAR(50) |
β οΈ Fails, or cuts off (truncates) any longer text |
VARCHAR β INT |
β οΈ Fails on any non-numeric row |
NULL β NOT NULL |
β οΈ Fails if any row is NULL β clean the data first |
DECIMAL(10,2) β DECIMAL(10,4) |
β οΈ Integer capacity shrinks from 8 digits to 6; existing values can overflow |
DECIMAL(10,2) β DECIMAL(12,4) |
β Preserves 8 integer digits while adding 2 fractional digits |
DECIMAL(10,4) β DECIMAL(10,2) |
β οΈ Silent rounding, data loss |
[!TIP] π‘ Pro tip β always check before you shrink:
-- π₯ MSSQL SELECT MAX(LEN(phone)) FROM customers;-- π¦ MySQL SELECT MAX(CHAR_LENGTH(phone)) FROM customers;
11.3 π·οΈ Renaming
-- π₯ MSSQL: a built-in stored procedure (a saved program), not a normal SQL statement
EXEC sp_rename 'customers.phone', 'phone_number', 'COLUMN';
EXEC sp_rename 'customers', 'clients';
-- Put both names back, so the rest of this guide still works
EXEC sp_rename 'clients', 'customers';
EXEC sp_rename 'customers.phone_number', 'phone', 'COLUMN';
-- π¦ MySQL
ALTER TABLE customers RENAME COLUMN phone TO phone_number; -- MySQL 8.0+
ALTER TABLE customers RENAME TO clients;
RENAME TABLE clients TO customers; -- alternative syntax (and puts the name back)
ALTER TABLE customers RENAME COLUMN phone_number TO phone; -- restore the column name too
[!WARNING] β οΈ Renaming does not update anything that references the old name. Views, stored procedures, functions, and application code all break silently. In MSSQL,
sp_renameeven prints a warning about this. Search all of your code before renaming anything on a live server.
11.4 β Dropping columns
-- β
Works in BOTH
ALTER TABLE customers DROP COLUMN date_of_birth;
-- β
MySQL: several at once
ALTER TABLE customers DROP COLUMN referral_code, DROP COLUMN marketing_opt_in;
-- β
MSSQL: several at once (comma-separated column list, one DROP COLUMN)
-- A column with a DEFAULT cannot be dropped until its default constraint is dropped
ALTER TABLE customers DROP CONSTRAINT df_customers_marketing_opt_in;
ALTER TABLE customers DROP COLUMN referral_code, marketing_opt_in;
[!WARNING] β οΈ You usually cannot drop a column that is part of a primary key, referenced by a foreign key, used by an index, or referenced by a check constraint or computed column. Drop the dependent object first.
11.5 π£ DROP vs TRUNCATE vs DELETE
This is one of the most common interview questions in existence. Learn this table cold.
| Β | DELETE |
TRUNCATE |
DROP |
|---|---|---|---|
| What it removes | Chosen rows | All rows | Rows and the table itself |
| Command family | DML | DDL | DDL |
WHERE clause |
β Yes | β No | β No |
| Speed on big tables | π’ Slow (row by row) | π Very fast (frees whole blocks of storage at once) | π Very fast |
| Recorded in the log | Every row | Very little | Very little |
| Fires triggers | β Yes | β No | β No |
| Resets auto-number | β No | β Yes | n/a |
| Can be undone (rolled back) | β Yes | β MSSQL yes (inside a transaction). β οΈ MySQL no β it saves automatically | β οΈ MSSQL yes. MySQL no |
| Blocked by a foreign key | Yes, if children exist | Yes, always if any FK points at it | Yes, until the FK is dropped |
| Table structure survives | β Yes | β Yes | β No |
-- β
Works in BOTH
-- A throwaway table to demonstrate on (Chapter 12 builds the real staging tables)
CREATE TABLE staging_orders (order_id INT, status VARCHAR(20));
INSERT INTO staging_orders VALUES (1, 'Pending'), (2, 'Paid');
-- DELETE: surgical
DELETE FROM order_items WHERE order_id = 1004;
-- TRUNCATE: empty the table, keep the structure
TRUNCATE TABLE staging_orders;
-- DROP: the table is gone
DROP TABLE staging_orders;
[!TIP] π‘ How to remember it:
DELETEerases some words.TRUNCATEerases the whole page.DROPthrows away the whole notebook.
11.6 π‘οΈ Safe DDL habits for production
-- β
Works in BOTH: guard against "does not exist" errors
DROP TABLE IF EXISTS staging_orders;
-- π₯ MSSQL: check before you act
IF OBJECT_ID('dbo.staging_orders', 'U') IS NOT NULL
DROP TABLE dbo.staging_orders;
IF NOT EXISTS (SELECT 1 FROM sys.columns
WHERE object_id = OBJECT_ID('dbo.customers') AND name = 'referral_code')
ALTER TABLE dbo.customers ADD referral_code VARCHAR(20) NULL;
[!TIP] π‘ The five rules of production DDL:
- Have a recoverable backup first. A
SELECT ... INTOtable copy can help undo a small change, but runtime depends on data size and it does not replace backups, constraints or a tested restore path.- Run it on a copy first. A development copy, then a test (staging) copy, then the real server. Never the reverse.
- Wrap it in a transaction where the engine supports it, and verify before committing.
- Know how long it will block users.
ALTER TABLEon a 200-million-row table can lock everyone out of it for hours. Check whether your version can make the change online (without blocking).- Write the script that undoes the change before you run the change. If you cannot describe how to undo it, you are not ready to run it.
-- π¦ MySQL 8.0: control how the ALTER is performed
ALTER TABLE customers ADD COLUMN nickname VARCHAR(50), ALGORITHM=INSTANT;
-- ALGORITHM = INSTANT (fastest: changes only the table's description, not its rows) | INPLACE | COPY
-- LOCK = NONE (reads and writes continue) | SHARED | EXCLUSIVE
π Doing this repeatedly, on many servers, without a human at a keyboard is Chapter 64 β versioned migrations, idempotent scripts (safe to run twice), and the expandβcontract pattern for changes that cannot break a running application.
11.7 π§ͺ Try it yourself
- Add a
notes VARCHAR(500)column toorders, populate it for one row, then drop it. - Try to change
customers.emailtoVARCHAR(10). Read the error and explain it. - Create a copy of
products,TRUNCATEit, and check whether the auto-number restarted at 1. - Try to
DROP TABLE customers. Which constraint blocks you? What would you have to drop first?
π§ In practice β ALTER and DROP
How to use it. Use
ALTER TABLE ... ADD COLUMNto extend a table,ALTER TABLE ... ALTER/MODIFY COLUMNto change a type, andDROPto remove an object entirely. Always check what depends on the object first. Expected result: the change applies, and nothing that referenced the old shape silently breaks.When to use it. Whenever requirements change β which is constantly. Schemas are not written once; they evolve, and the skill is evolving them without downtime or data loss.
Where to use it. Migrations and deployments. Scenario: adding a
loyalty_tiercolumn tocustomers. Adding it asNULL-able with a default is near-instant; adding it asNOT NULLwith no default on a large table rewrites every row and holds a lock while it does, which on a busy shop means an outage.When not to use it. Never run
ALTERorDROPagainst production by hand.DROP TABLEhas no undo, andDROP DATABASEhas no undo β recovery means restoring a backup and losing everything since. Avoid schema changes during peak traffic, and be aware that on large tables some βsimpleβ type changes are full rewrites.Best practices. Make every schema change through a reviewed, version-controlled migration script (Chapter 64), and write the rollback at the same time as the change. Take a backup before any destructive operation. Prefer additive changes β add a new column, backfill it, switch the application over, and drop the old one in a later release β because that sequence can be stopped safely at any point, while a single rename cannot.
| Part index | Prerequisites | Previous | Next | Full course |