smartyfy.mrindigi.com

Databases & SQL Master Course — 002. Tables and Schemas

Lesson 002 Tables and Schemas

A useful database starts with a clear structure. The bookstore now needs prices, genres, and author references as well as titles and stock. Before entering those facts, we will define exactly where each fact belongs. The result of this lesson is an empty but inspectable books table and a short data dictionary that explains its meaning.

Prerequisites and learning objectives

Complete Lesson 001 or be comfortable distinguishing rows, columns, and query results. Use a new empty SQLite practice database, separate from any real work. By the end, you will create a table, read its definition, inspect column metadata, name fields consistently, and explain why a declared column type does not express every business rule.

Step 1 Define the table before its columns

Write the row meaning first: one row represents one title in our fictional bookstore catalog. This is still a catalog model, not a record of each copy or each sale. A table name such as books helps people find the data, but its name alone cannot settle whether different editions count as different titles. For these beginner fixtures, each listed book number identifies the catalog entry we mean.

We need six attributes. book_id is the internal catalog number. title is the display name. author_id is the number of the associated author, whose separate record will be introduced in Lesson 004. genre is a broad classification. price_cents is the selling price measured in the fictional shop currency’s hundredths. stock is the currently recorded number of copies.

Names that include units prevent avoidable mistakes. A price of 1800 in price_cents means 18 whole currency units, not 1800 whole units. We deliberately use an integer count of hundredths in this simple single-currency exercise. Real systems need explicit currency and rounding rules, particularly when currencies or business calculations use different scales.

Step 2 Read a column definition

A column definition starts with its name and may include a declared type and constraints. In title TEXT NOT NULL, title is the name, TEXT describes the intended kind of value, and NOT NULL rejects a missing SQL NULL value. It does not reject an empty string or a string containing only spaces. Required presence and useful content are separate requirements.

Choose simple lowercase names with underscores for this course. That is a readability convention, not an engine requirement. Avoid names whose meaning depends on private abbreviations, and avoid names that collide with SQL keywords. A name such as current_inventory_quantity may be longer, but stock is sufficient when the data dictionary clearly defines it.

Step 3 Create the books table

Run this statement once in your empty practice database. The parentheses contain column definitions separated by commas. There is no comma after the final definition. The semicolon ends the statement.

CREATE TABLE books (
  book_id INTEGER,
  title TEXT NOT NULL,
  author_id INTEGER NOT NULL,
  genre TEXT NOT NULL,
  price_cents INTEGER NOT NULL,
  stock INTEGER NOT NULL
);

The table now exists with six columns and no rows. Creating the structure does not invent catalog entries. We have intentionally postponed primary and foreign key constraints until Lesson 004. At this stage book_id and author_id are descriptive integer columns; their names alone do not enforce uniqueness or valid references.

Take a moment to translate the statement back into English. Each row can contain a book number. Its title, author number, genre, price, and stock must be present as values rather than SQL NULL. The definition does not yet reject negative stock, duplicate book numbers, or an author number that has no matching author. Those rules need additional design and constraints.

Step 4 Inspect what was actually created

Do not rely solely on a remembered script. Ask SQLite for the current metadata. PRAGMA is a SQLite-specific command family; this example is an inspection operation.

PRAGMA table_info(books);

The result contains one row per ordinary column. In this example the names should be book_id, title, author_id, genre, price_cents, and stock. The type values should be INTEGER or TEXT as declared. The notnull flag is zero for book_id and one for the other five columns. The pk flag is zero for all six because we have not declared a primary key.

The cid values begin at zero and describe column positions in this metadata output. They are not your book identifiers. Similarly, a notnull flag is a property of the column definition, not a count of missing values in stored rows. Distinguish information about a schema from information inside the application data.

The books schema lists book_id INTEGER without NOT NULL, then title TEXT, author_id INTEGER, genre TEXT, price_cents INTEGER and stock INTEGER, each NOT NULL. A separate empty-table panel shows six columns, zero rows, and no keys declared yet.
CREATE TABLE defines six columns but inserts no books. In this introductory schema, all columns except book_id reject NULL; primary and foreign keys arrive in Lesson 004. Open full-size diagram

Step 5 Create a small data dictionary

A data dictionary explains decisions that syntax cannot fully communicate. For this table, record that stock counts copies currently recorded, price_cents uses hundredths of one course currency, and author_id will refer to a separate author table. Also record the deliberate simplification that each book has one author. Real coauthorship would require a different relationship design.

Write an example and an excluded meaning for important fields. For stock, an example is 4 and an excluded meaning is total copies ever purchased. For price_cents, an example is 1800 and an excluded meaning is the number of cents paid across all sales. This habit exposes ambiguous requirements before they become incorrect reports.

Step 6 Recognize SQLite type behavior

Ordinary SQLite tables use type affinity rather than the strict type behavior beginners may expect from other systems. Declaring INTEGER alone is not a complete guarantee that every accepted value has the intended business meaning. Later lessons test that behavior and introduce SQLite STRICT tables. For now, insert values of the intended kind and treat validation as something to design and test, not infer from a familiar-looking type name.

If you run CREATE TABLE books again, SQLite normally reports that the table already exists. Do not add IF NOT EXISTS merely to hide uncertainty: that clause does not verify that the existing structure matches your new definition. Inspect the schema or open another empty practice database. This course avoids automatic deletion as a way to recover from setup mistakes.

Practice with worked solutions

Exercise 1

Create a shelves table with shelf_id as an integer, label as required text, and capacity as a required integer. What is its row meaning?

Worked solution
CREATE TABLE shelves (
  shelf_id INTEGER,
  label TEXT NOT NULL,
  capacity INTEGER NOT NULL
);

One row represents one named shelf. Define capacity as the maximum number of copies it can hold, not its current stock. The integer declarations alone do not enforce positive capacity or unique shelf identifiers.

Exercise 2

A statement ends with stock INTEGER NOT NULL, followed by a closing parenthesis. Why does it fail, and what changes?

Worked solution
CREATE TABLE stock_demo (stock INTEGER NOT NULL);

The trailing comma promises another column or constraint, but none follows. Remove that final comma. Commas separate definitions; they do not finish the list.

Exercise 3

A teammate proposes cost INTEGER for the selling price. Improve the name and supply a data-dictionary entry.

Worked solution

Use price_cents if the intended fact is a selling price in hundredths. Define it as the current listed selling price per copy in the course currency. Cost could mean acquisition cost, total expense, or sale price, so accepting it without clarification would hide a substantive business decision.

Exercise 4

Inspect shelves and explain the expected pk and notnull flags.

Worked solution
PRAGMA table_info(shelves);

All three pk flags are zero because no primary key was declared. shelf_id has notnull zero; label and capacity have notnull one. The metadata confirms constraints in the definition, not whether any data has been inserted.

Knowledge check

Question 1

What does CREATE TABLE do in this lesson?

  1. Adds four sample books
  2. Defines an empty table
  3. Deletes previous tables
  4. Automatically creates author records
Answer and explanation

B. The statement defines structure. INSERT will add records in the next lesson.

Question 2

What does NOT NULL on title reject?

  1. Every short title
  2. All repeated titles
  3. SQL NULL
  4. All blank-looking strings
Answer and explanation

C. It rejects SQL NULL, while empty strings need a separate validation rule.

Question 3

What does naming a column book_id guarantee?

  1. Uniqueness
  2. A foreign key
  3. Automatic numbering
  4. None of those by itself
Answer and explanation

D. Names communicate intent; constraints and engine features enforce specific behavior.

Question 4

Why use price_cents?

  1. It states the measurement unit
  2. It makes every currency identical
  3. It automatically rounds tax
  4. It creates an index
Answer and explanation

A. The name documents units. It does not supply currency conversion, tax rules, or indexes.

Question 5

What does PRAGMA table_info inspect?

  1. Only row values
  2. Column metadata
  3. The physical shelf
  4. Every future schema change
Answer and explanation

B. It reports the current ordinary column definitions for the specified table.

Pitfalls and summary

A plausible table name is not a complete model. Document grain and units, use consistent names, inspect actual metadata, and distinguish declared types from tested integrity rules. You have created an empty books structure. The next lesson will populate it while keeping column meanings and value order explicit.

Primary references