Exercises
Objectives
This lesson introduces no new concepts. It’s a chance to practice everything from this module: CREATE TABLE, data types, NULL/DEFAULT, PRIMARY KEY, NOT NULL, UNIQUE, SERIAL/IDENTITY, and DROP/TRUNCATE TABLE.
All exercises are runnable against a real PostgreSQL database.
Exercises
-
Write a
CREATE TABLEstatement for adepartmentstable: an auto-incrementingid(SERIAL PRIMARY KEY), a requiredname, and abudgetof typeNUMERIC(12,2). -
Write a
CREATE TABLEstatement for aproductstable: an auto-incrementingid, a requiredname, adescriptionthat can hold any amount of text, a requiredprice, and anin_stockboolean that defaults totrue. -
Insert a product without mentioning
in_stockat all, then confirm it defaulted totrue. -
Add a
UNIQUEconstraint to theproductstable’snamecolumn, then try inserting two products with the same name, and confirm the second one fails. -
Add a
NOT NULLconstraint todepartments.name, then try inserting a department withnameleft out entirely, and confirm it fails. -
Create a table using
GENERATED ALWAYS AS IDENTITYfor its primary key instead ofSERIAL, insert two rows, and confirm the ids were assigned automatically. -
TRUNCATEtheproductstable from exercise 2, confirm it’s empty, then insert a new product and check whether itsidcontinues from before or restarts. -
Write a
DROP TABLE IF EXISTSstatement for a table name that doesn’t exist, and confirm it doesn’t raise an error.
Recap
You can now create a real table with the right data types, control what’s required and what’s optional with NULL and DEFAULT, enforce uniqueness with PRIMARY KEY and UNIQUE, generate ids automatically with SERIAL or IDENTITY, and remove or empty a table safely. That’s everything needed to design and build a table from scratch.
Next module: CRUD Operations, where you’ll finally put real data into the tables you now know how to build, with INSERT, UPDATE, and DELETE.