SQL Database Schemas

Introduction

Databases are organized collections of data, and their structure determines how efficiently they store, retrieve, and manipulate information. A database schema defines the logical structure of a database, including its tables, columns, and constraints.

In this guide, you'll explore the fundamental components of SQL database schemas, including:

What is a Table?

A table is a logical structure within a database that organizes data into rows and columns. Each row represents an individual entity (e.g., a specific dog), and each column describes a property of that entity (e.g., its name, age, breed, etc.).

Think of a table as a spreadsheet where rows are records and columns are the attributes of those records. For example, a table for storing dog information might look like this:

name age_yrs breed weight_lbs microchipped
Callie 1 Corgi 16 no
Charley 1.5 Basset Hound 25 no
Jaxon 0.4 Beagle 19 yes

Column Types

Each column in a table is assigned a data type, defining the kind of data it can hold. Choosing the right column type ensures efficient storage and accurate data processing.

Numeric Types

String Types

Boolean Types

SQLite Column Types

SQLite simplifies column types into the following:

SQLite maps BOOLEAN values to NUMERIC, storing false as 0 and true as 1.

Column Constraints

Constraints enforce rules on the data within a column, ensuring accuracy and consistency. Here are common constraints:

Steps to Designing a Database

When designing a database schema, follow these steps:

  1. Identify the tables you need and their purpose.
  2. Define the columns for each table and choose appropriate data types.
  3. Add constraints like NOT NULL, DEFAULT, or PRIMARY KEY as necessary.

For example, a simple schema for a pet database might look like this:


CREATE TABLE pets (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  name VARCHAR(50) NOT NULL,
  age_yrs REAL,
  breed VARCHAR(50) DEFAULT 'Mixed',
  microchipped BOOLEAN
);

      

What You Learned

By understanding tables, columns, and constraints, you’re prepared to design and implement efficient database schemas that meet application needs.