r/SQL • u/AssistanceClean948 • Sep 15 '26
SQLite Good reason to use composite keys?
CREATE TABLE
IF NOT EXISTS CourseTag (
id INTEGER PRIMARY KEY,
courseId INTEGER NOT NULL,
tagId INTEGER NOT NULL,
UNIQUE(courseId, tagId),
FOREIGN KEY (courseId) REFERENCES Courses (id) ON DELETE CASCADE ON UPDATE RESTRICT,
FOREIGN KEY (tagId) REFERENCES Tags (id) ON DELETE CASCADE ON UPDATE RESTRICT
) STRICT;
17
Upvotes
15
u/thesqlguy Sep 15 '26
1
u/TemporaryDisastrous Sep 15 '26
Beyond uniqueness you'd use composite keys for performance, is that what you're asking?
1
u/Aggressive_Ad_5454 Sep 15 '26 edited Sep 15 '26
OK, let's run this down.
In SQLite v 3.8.2 and beyond, you can declare a table using the
WITHOUT ROWIDqualifier. In order to do that, your table must have a primary key. The effect of that kind of declaration is to structure the table on disk as having a so-called "clustered index." That is, the data of the table is stored within the structure of the primary key's index. If most of your queries to the table useWHERE primary_key_column = something, this table structure makes things a bit faster and saves a bit of tablespace, which is good. RAM, disk, and power all cost money.If you omit
WITHOUT ROWID, the DBMS throws in an extra ROWID column. Sometimes we need that, for example when a table doesn't have a unique primary key. It organizes the table so the data is stored with the ROWID, and indexed lookups grab the ROWID and search for it. That's an extra step.Your primary key can be just one column, or it can be a multi-column key.
Your particular table, OP, seems to be designed to support a many-to-many relationship between your
CourseandTagtables. So it's a perfect application for a multicolumn clustered index. So let's declare it like this:I left out the FKs; OP, you can put them back as needed.
This contains the primary key, which is ideal for looking things up by
courseId. It's a composite key so we can have multipletagIdvalues for eachcourseId. The other index is suitable for looking things up bytagId. Both these are so-called covering indexes.In SQLite, all INTEGER data items can hold values up to 8-byte signed binary numbers (BIGINT in some other DBMSs). But if the values fit in fewer bytes, SQLite uses fewer bytes.
In my experience, this is the most efficient way of handling many-to-many join tables like your
CourseTag.1
u/Organic_Profile1671 Sep 15 '26
To use a composite key, you'd drop id and have both courseId and tagId be your primary key.
You'd do this because the coursetag is always referred to by it's constitute parts, so having the clustered index is more performant than an additional artificial key.
For example, I'm searching all tags for course 1234, or all courses with tag 654. You'd never search for a particular CourseTag.Id so except for making deleting slightly more convenient it doesn't serve a purpose.
Also overlooked is overflowing PKs. Imagine a table with a composite key of Client_id/Date. Same table with an ID int value can hold 2 billion record. 1 million clients, 1 record a day, you store 2000 days worth (~6 years worth of data). With a combined key we never worry about max values.
2
u/Old-Biscotti3842 Sep 15 '26
There is one real con and it isn't the ORM. Anything that ever needs to point at a CourseTag row has to carry both columns, so the day this table becomes a parent, every child drags courseId and tagId along, and that's when people retrofit an id. For a pure join table nothing ever points at it, and honestly for CourseTag I can't think of what would, which is your answer.
On the ORM thing, since you got shot down for asking: the folklore is real but dated, and it mostly comes from Django, which had no composite primary keys at all until 5.2 and still won't let a ForeignKey point at one. Rails had the same limitation until 7.1. The funny part is that ORMs don't even agree with each other on this exact table. What you wrote, id plus UNIQUE(courseId, tagId), is literally what Django generates for its own many-to-many tables. Rails' create_join_table makes it with no primary key at all. Prisma's implicit relation table is also PK-less, just (A, B) with a unique on both and a plain index on B. So if an ORM is going to read this, copy that ORM's shape and you're fine.
If it's SQLite and hand-written SQL, u/Aggressive_Ad_5454's WITHOUT ROWID version is the one to take, and here's the part that makes it not a style choice. Your id version is three b-trees, the rowid table, the unique, and a (tagId, courseId) index you need anyway, where the composite one is two. And that reverse index isn't optional either way: you have ON DELETE CASCADE on Tags, and SQLite has to find the CourseTag rows by tagId to cascade, so without it every tag delete scans the whole table.
1
u/Hour-Measurement-835 Sep 15 '26
In SQLite the composite PK buys you less than people think. It's still a rowid table underneath with an autoindex on the pair, unless you add WITHOUT ROWID.
1
u/reditandfirgetit Sep 15 '26
The unique contraint isn't necessarily a composite key. It's enforcing that only one combination of tag/course is allowed in the table. That could just as well be student, course, quarter (student can only enroll in the course once per quarter)
1
u/aardw0lf11 Sep 15 '26
They can be useful in understanding the data while also providing an index. Sometimes having a unique ID for each record really serves no purpose other than a simple row number.
1
u/ArielCoding Sep 15 '26
SQLite doesn’t enforce those FOREIGN KEY rules including your CASCADE/RESTRICT unless you turn it on, run PRAGMA foreign_keys = ON; each time you connect or set it in your driver/ORM config.
1
u/888NRG_ Sep 16 '26
Many to many to relations that can't have duplicates
1
u/bermagot12 Sep 16 '26
Many reasons. You could have a table that reports restaurant profits per quarter for example, the composite key would be the restaurant ID + quarter.