topskill.dev
CoursesTracks
All courses/Introduction to SQLCreate tables with purposeful data types
Define tables and protect their rows
1 / 21
← Introduction to SQL
○Read rows with SELECT○Exercise: a lending-desk list○Name a result column with AS○Exercise: Name a result column with AS○Calculate a result with arithmetic○Exercise: Calculate a result with arithmetic○Remove duplicate result rows○Exercise: the category menu○Filter rows with WHERE○Exercise: Filter rows with WHERE○Require both conditions with AND○Exercise: Require both conditions with AND○Accept either condition with OR○Exercise: Accept either condition with OR○Reverse a known condition with NOT○Exercise: Reverse a known condition with NOT✦Module Quiz
○Recognize missing values with IS NULL○Exercise: gear without a note○Match an allowed list with IN○Exercise: Match an allowed list with IN○Select an inclusive range with BETWEEN○Exercise: Select an inclusive range with BETWEEN○Find text with LIKE○Exercise: names containing a space○Sort rows with an explicit tie-breaker○Exercise: Sort rows with an explicit tie-breaker○Take a bounded result with LIMIT○Exercise: Take a bounded result with LIMIT✦Module Quiz
○Count rows and known values with COUNT○Exercise: Count rows and known values with COUNT○Add known values with SUM○Exercise: Add known values with SUM○Calculate a mean with AVG○Exercise: Calculate a mean with AVG○Find a minimum with MIN○Exercise: Find a minimum with MIN○Find a maximum with MAX○Exercise: Find a maximum with MAX○Make one summary per group○Exercise: category totals○Filter groups with HAVING○Exercise: categories with enough stock✦Module Quiz
○Match related rows with INNER JOIN○Exercise: who booked each session○Keep unmatched rows with LEFT JOIN○Exercise: makers with no bookings○Reconcile two lists with FULL JOIN○Exercise: two attendance sheets○Read one table in two roles with a self join○Exercise: a mentor directory○Generate a small schedule with CROSS JOIN○Exercise: bench and shift combinations✦Module Quiz
●Create tables with purposeful data types○Exercise: a storage-bin table○Identify a row with PRIMARY KEY○Exercise: Identify a row with PRIMARY KEY○Require a value with NOT NULL○Exercise: Require a value with NOT NULL○Prevent repeated known values with UNIQUE○Exercise: Prevent repeated known values with UNIQUE○Validate a condition with CHECK○Exercise: Validate a condition with CHECK○Supply an omitted value with DEFAULT○Exercise: Supply an omitted value with DEFAULT○Require a matching parent with a foreign key○Exercise: Require a matching parent with a foreign key○Identify a relationship with a composite key○Exercise: Identify a relationship with a composite key○Insert rows with an explicit column list○Exercise: register two tool kits○Add a column with ALTER TABLE○Exercise: Add a column with ALTER TABLE✦Module Quiz
○Rename a column without replacing its values○Exercise: Rename a column without replacing its values○Remove one column with DROP COLUMN○Exercise: Remove one column with DROP COLUMN○Remove a table with DROP TABLE○Exercise: Remove a table with DROP TABLE○Avoid repeating groups in first normal form○Exercise: Avoid repeating groups in first normal form○Separate facts that depend on part of a key○Exercise: Separate facts that depend on part of a key○Separate indirectly dependent facts○Exercise: Separate indirectly dependent facts○Report a many-to-many relationship○Exercise: Report a many-to-many relationship○Project: build the people register○Project: add the workshop catalog○Project: connect people to workshops✦Module Quiz
○Update the rows you intend○Exercise: repair one fee○Delete selected rows, not the table○Exercise: retire one kit○Commit a unit of work or roll it back○Exercise: cancel a mistaken change○Undo a later part with SAVEPOINT○Exercise: keep the correction, undo the trial○Project: record an allocation atomically○Project: cancel the recorded allocation○Project: keep the revised plan, reject an add-on✦Module Quiz
○Use a scalar subquery as a value○Exercise: Use a scalar subquery as a value○Use a subquery as an IN list○Exercise: Use a subquery as an IN list○Read a subquery as a table○Exercise: Read a subquery as a table○Ask whether a related row exists○Exercise: makers who have bookings○Combine distinct rows with UNION○Exercise: Combine distinct rows with UNION○Keep every occurrence with UNION ALL○Exercise: Keep every occurrence with UNION ALL○Keep shared rows with INTERSECT○Exercise: Keep shared rows with INTERSECT○Subtract one result with EXCEPT○Exercise: Subtract one result with EXCEPT○Choose a value with CASE○Exercise: Choose a value with CASE○Display a fallback with COALESCE○Exercise: Display a fallback with COALESCE✦Module Quiz
○Trim surrounding spaces with TRIM○Exercise: Trim surrounding spaces with TRIM○Normalize letter case with LOWER○Exercise: Normalize letter case with LOWER○Make an uppercase label with UPPER○Exercise: Make an uppercase label with UPPER○Join text values with concatenation○Exercise: Join text values with concatenation○Count characters with CHAR_LENGTH○Exercise: Count characters with CHAR_LENGTH○Extract part of a value with SUBSTRING○Exercise: Extract part of a value with SUBSTRING○Round numeric output with ROUND○Exercise: Round numeric output with ROUND○Measure a magnitude with ABS○Exercise: Measure a magnitude with ABS○Round a packing count upward with CEIL○Exercise: Round a packing count upward with CEIL○Convert a value with CAST○Exercise: Convert a value with CAST✦Module Quiz
○Calculate calendar days between dates○Exercise: Calculate calendar days between dates○Filter a whole calendar period○Exercise: Filter a whole calendar period✦Module Quiz
○Name a reusable query with a view○Exercise: a ready gear view○Create an index without changing a result○Exercise: Create an index without changing a result○Read a query plan with EXPLAIN○Exercise: Read a query plan with EXPLAIN○Give a query stage a name with WITH○Exercise: summarize before filtering○Keep detail rows while calculating a rank○Exercise: rank gear within each category○Share a business rank across ties○Exercise: Share a business rank across ties○Count distinct ranked levels○Exercise: Count distinct ranked levels○Keep application input separate from SQL structure○Give a database account only the access it needs○Plan and test database recovery✦Module Quiz

Create tables with purposeful data types

Until now, each lesson has supplied its tables. CREATE TABLE defines one yourself. Between parentheses, each column needs a name and a type; commas separate definitions. This is data definition language, often shortened to DDL.

Data model

Example data

This example starts without tables. The following dictionaries describe the tables to create, not preloaded tables.

parcel_labels

One row represents one parcel label to be created.

Field / SQL typeMeaningRules
label_id · integerIntended identifier of the parcel label.Nullable; NULL means the identifier is unrecorded.
destination · textDestination text for the parcel.Nullable; NULL means no destination value is recorded.
weight · numeric(8,2)Parcel mass in kilograms, stored to two decimal places.Nullable; NULL means the weight is unrecorded, not zero.
fragile · booleanFragility flag: true for fragile, false otherwise.Nullable; NULL means fragility is unrecorded.
ship_date · dateShipping calendar date, without time of day or time zone.Nullable; NULL means no ship date value is recorded.

This first design declares no primary key or positivity checks. A missing fragile flag means the flag is unknown, not false.

This table has no declared primary or unique key; distinct sample values are not a uniqueness guarantee.

For the parcel-label example, one future row will describe one parcel: its identifier, destination, weight in kilograms, fragile flag, and shipping date. Defining those fields decides which kinds of facts the table can hold. It does not yet require an identifier to be unique or a weight to be positive; the next lessons add those rules.

Choose types by meaning. integer stores whole numbers; numeric(8,2) stores exact decimal values with up to eight total digits, two after the decimal point. text stores variable-length text. boolean stores true or false, while date stores a calendar date without a time of day. A telephone number belongs in text because arithmetic on it makes no sense and leading zeroes may matter.

Run the demo. Its final SELECT returns an empty result with the new column headings. Creating a table does not create data rows. A later INSERT lesson adds records. IF NOT EXISTS makes this particular demo safe to run twice; it does not check that an existing table has the desired structure.

These lessons use PostgreSQL syntax. Type names and size rules vary across products. Avoid guessing that every database treats text, boolean, or auto-generated identifiers the same way.

sql
CREATE TABLE IF NOT EXISTS parcel_labels (
  label_id integer,
  destination text,
  weight numeric(8,2),
  fragile boolean,
  ship_date date
);
SELECT label_id, destination, weight, fragile, ship_date
FROM parcel_labels;