Introduction
Table relationships help connect data in different tables so you can find related information easily.
Table relationships help connect data in different tables so you can find related information easily.
CREATE TABLE child_table ( id SERIAL PRIMARY KEY, parent_id INTEGER REFERENCES parent_table(id) );
CREATE TABLE authors ( id SERIAL PRIMARY KEY, name TEXT NOT NULL ); CREATE TABLE posts ( id SERIAL PRIMARY KEY, author_id INTEGER REFERENCES authors(id), title TEXT NOT NULL );
CREATE TABLE categories ( id SERIAL PRIMARY KEY, name TEXT NOT NULL ); CREATE TABLE products ( id SERIAL PRIMARY KEY, category_id INTEGER REFERENCES categories(id), product_name TEXT NOT NULL );
This creates two tables: customers and orders. Orders link to customers using customer_id. Then it inserts sample data and shows how to get orders with customer names.
CREATE TABLE customers ( id SERIAL PRIMARY KEY, name TEXT NOT NULL ); CREATE TABLE orders ( id SERIAL PRIMARY KEY, customer_id INTEGER REFERENCES customers(id), order_date DATE NOT NULL ); -- Insert sample data INSERT INTO customers (name) VALUES ('Alice'), ('Bob'); INSERT INTO orders (customer_id, order_date) VALUES (1, '2024-06-01'), (2, '2024-06-02'); -- Query orders with customer names SELECT orders.id, customers.name, orders.order_date FROM orders JOIN customers ON orders.customer_id = customers.id;
Always use primary keys in parent tables for reliable links.
Use JOIN queries to get related data from connected tables.
Relationships help keep data organized and avoid duplicates.
Table relationships connect data across tables using keys.
They make it easy to find related information with JOINs.
Use REFERENCES to create these links safely and clearly.
CREATE TABLE authors (id SERIAL PRIMARY KEY, name TEXT);CREATE TABLE books (id SERIAL PRIMARY KEY, title TEXT, author_id INT REFERENCES authors(id));SELECT books.title, authors.name FROM books JOIN authors ON books.author_id = authors.id;CREATE TABLE orders (id SERIAL PRIMARY KEY, customer_id INT, FOREIGN KEY customer_id REFERENCES customers(id));students and courses tables in Supabase. Which setup is best?Pass the test and this pattern moves unknown