Suppose I have a Citizen
table (columns: rowid
, name
) and a Race
table (columns: rowid
, name
). These are citizens of the world and the races are "Caucasian", "African American", etc. The rowid
s are the default columns provided by SQLite.
There are billions of citizens. There are very few races, say 50.
What is the SQLite way of connecting each citizen to his or her race?
In a standard programming language, I would simply attach to each race a set containing all the corresponding citizen rowid
s. This would allow me to do various things:
rowid
into his or her race's set.How can I do this in SQLite? Could this be tricky given that SQLite only has B-tree indexes? Maybe this kind of data doesn't belong in a SQLite database to begin with?
SQLite is an Relational Database Management System which is written in ANSI-C.
SQLite only has four primitive data types: INTEGER, REAL, TEXT, and BLOB.
The relational model (RM) is an approach to managing data using a structure and language consistent with first-order predicate logic, first described in 1969 by English computer scientist Edgar F. Codd, where all data is represented in terms of tuples, grouped into relations.
SQLite has support for FOREIGN KEYS, so you should model your tables as follows.
RaceId from the Race table is a FOREIGN KEY in Citizen table, if 1 Citizen can have only 1 Major Race in your application use case.
CREATE TABLE Race
(
RowId INTEGER AUTO_INCREMENT PRIMARY KEY,
RaceName TEXT
);
CREATE TABLE Citizen
(
RowId BIGINT AUTO_INCREMENT PRIMARY KEY,
CitizenName TEXT,
RaceId INTEGER,
FOREIGN KEY(RaceId) REFERENCES Race(RowId)
);
If you want to support Multiple Races (which is very possible these days), then remove the FOREIGN KEY from the Citizen table and create a new MANY-2-MANY table called CitizenRace, that will have CitizenIds and RaceIds like below.
CREATE TABLE Race
(
RowId INTEGER AUTO_INCREMENT PRIMARY KEY,
RaceName TEXT
);
CREATE TABLE Citizen
(
RowId BIGINT AUTO_INCREMENT PRIMARY KEY,
CitizenName TEXT
);
CREATE TABLE CitizenRace
(
CitizenId BIGINT,
RaceId INTEGER,
FOREIGN KEY(CitizenId) REFERENCES Citizen(RowId),
FOREIGN KEY(RaceId) REFERENCES Race(RowId)
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With