ALTER, NULL, Constraints & UPDATE / DELETE
Changing a table without losing data, guarding it with constraints, and editing rows with a WHERE filter.
1. The Crux in 60 Seconds
ALTER keeps your data
ALTER TABLE (a DDL command) changes a column's type, adds a column or drops one, without the data loss of DROP + CREATE.
NULL means unknown
It is not a string and not comparable: neither less than nor greater than anything. 'null' in quotes is just text.
Constraints guard the data
NOT NULL, CHECK, UNIQUE, DEFAULT and PRIMARY KEY decide what may enter a column; violations make the statement fail.
Filter before you change
UPDATE and DELETE (both DML) hit every row unless you add a WHERE condition.
2. Foundational Concepts & Comparisons
DROP TABLE + CREATE TABLE
- Lets you redefine everything, even column position
- Loses all existing data in the table
- CREATE on an existing name fails ("already an object named..."), so drop first
- DROP always works, with or without data, and takes no WHERE
ALTER TABLE
- Changes the definition in place; rows stay
- Only compatible changes are allowed and nothing may be truncated
- New columns are always appended at the end
- Works the same on tables created by CREATE or imported from Excel: "a table is a table"
Recap of Day 1 (instructor's opening)
- DDL: CREATE TABLE, DROP TABLE; changes the definition
- DML: INSERT, DELETE; manipulates data
- DQL: SELECT; only queries data
- Also revisited: choosing columns, ORDER BY, schemas
- From here most classes focus on the SELECT statement (WHERE, aggregation, advanced topics start from the next class)
Warm-up Q&A
- Case: data is stored case-sensitively, but SQL Server compares case-insensitively by default when you query; the setting can be changed (instructor to confirm how). Most other databases are case-sensitive by default, he said.
- TOP vs LIMIT: same idea. SQL Server accepts
TOPonly; Redshift accepts both. - SELECT 1: returns the value 1 once per row (four rows give four 1s); not useful in place of *.
- Last N rows: done with ORDER BY, covered later.