Primary keys and foreign keys help keep data organized and connected in databases. They make sure each piece of data is unique and related to the right information.
Primary keys and foreign keys in Supabase
CREATE TABLE table_name ( column_name data_type PRIMARY KEY, other_column data_type, foreign_key_column data_type REFERENCES other_table(primary_key_column) );
The PRIMARY KEY ensures each row is unique.
The REFERENCES keyword creates a foreign key linking to another table's primary key.
CREATE TABLE users ( id SERIAL PRIMARY KEY, name TEXT );
CREATE TABLE orders ( order_id SERIAL PRIMARY KEY, user_id INTEGER REFERENCES users(id), amount NUMERIC );
CREATE TABLE comments ( comment_id SERIAL PRIMARY KEY, post_id INTEGER REFERENCES posts(id), content TEXT );
CREATE TABLE empty_table ( id SERIAL PRIMARY KEY );
This example creates two tables: customers and purchases. Each customer has a unique ID. Each purchase links to a customer using a foreign key. Then it inserts sample data and shows how to get purchase info with customer names.
CREATE TABLE customers ( customer_id SERIAL PRIMARY KEY, customer_name TEXT NOT NULL ); CREATE TABLE purchases ( purchase_id SERIAL PRIMARY KEY, customer_id INTEGER REFERENCES customers(customer_id), purchase_amount NUMERIC NOT NULL ); -- Insert sample data INSERT INTO customers (customer_name) VALUES ('Alice'), ('Bob'); INSERT INTO purchases (customer_id, purchase_amount) VALUES (1, 100.50), (2, 200.75); -- Query to show purchases with customer names SELECT purchases.purchase_id, customers.customer_name, purchases.purchase_amount FROM purchases JOIN customers ON purchases.customer_id = customers.customer_id;
Primary key lookup is very fast because it uniquely identifies rows.
Foreign keys help keep data consistent by preventing invalid links.
Common mistake: forgetting to add a primary key, which can cause duplicate rows.
Use primary keys to identify rows; use foreign keys to connect tables.
Primary keys make each row unique in a table.
Foreign keys link rows in one table to rows in another.
They help keep your data organized and connected.