Foreign Key Joins & Resource Embedding

Foreign Key Joins & Resource Embedding in Supabase: In traditional web frameworks, fetching a blog post along with its author, category, and comments requires…

In traditional web frameworks, fetching a blog post along with its author, category, and comments requires writing manual SQL JOIN statements or running multiple database queries. PostgREST inspects foreign key relationships in PostgreSQL and enables automatic resource embedding through nested select syntax.


One-to-Many & Many-to-One Joins

If posts.author_id references profiles.id, Supabase joins them automatically:

const { data: posts, error } = await supabase
  .from('posts')
  .select(`
    id,
    title,
    content,
    created_at,
    author:profiles (
      id,
      username,
      avatar_url
    ),
    category:categories (
      name,
      slug
    )
  `)
  .eq('status', 'PUBLISHED')
  .limit(10);

The response is returned formatted directly as nested JSON:

[
  {
    "id": "e4b2d6a1...",
    "title": "Mastering Supabase Architecture",
    "content": "...",
    "created_at": "2024-04-15T...",
    "author": {
      "id": "99f8...",
      "username": "alex_dev",
      "avatar_url": "https://..."
    },
    "category": {
      "name": "Engineering",
      "slug": "engineering"
    }
  }
]

Disambiguating Multiple Foreign Keys

If a table contains multiple foreign keys pointing to the same target table (e.g., sender_id and recipient_id both pointing to profiles), specify the relationship explicitly using the foreign key column name:

const { data: messages, error } = await supabase
  .from('direct_messages')
  .select(`
    id,
    body,
    sent_at,
    sender:profiles!direct_messages_sender_id_fkey(username, avatar_url),
    recipient:profiles!direct_messages_recipient_id_fkey(username, avatar_url)
  `)
  .eq('thread_id', activeThreadId);

Filtering on Nested Relations (!inner Joins)

By default, embedded relations perform a LEFT OUTER JOIN: if a post has no comments, the post is still returned with comments: [].

To convert this into an INNER JOIN where the parent is only returned if the child satisfies a condition, append !inner:

// Retrieve ONLY authors who have written at least one article about 'Postgres'
const { data: authors, error } = await supabase
  .from('profiles')
  .select(`
    username,
    posts!inner(title, status, tags)
  `)
  .eq('posts.status', 'PUBLISHED')
  .contains('posts.tags', ['postgres']);

Remote Procedure Calls (RPC) for Complex SQL

When queries require recursive CTEs, full-text ranking, or multi-step database transactions, write a PL/pgSQL function and call it via .rpc():

-- SQL definition in Supabase SQL editor:
CREATE OR REPLACE FUNCTION get_trending_posts(p_min_likes INT, p_days INT)
RETURNS TABLE (
    post_id UUID,
    title TEXT,
    like_count BIGINT
) LANGUAGE sql STABLE AS $$
    SELECT p.id, p.title, COUNT(l.id) AS like_count
    FROM posts p
    JOIN likes l ON p.id = l.post_id
    WHERE l.created_at >= NOW() - (p_days || ' days')::interval
    GROUP BY p.id, p.title
    HAVING COUNT(l.id) >= p_min_likes
    ORDER BY like_count DESC;
$$;

Invoke the function directly from your client:

const { data: trending, error } = await supabase.rpc('get_trending_posts', {
  p_min_likes: 25,
  p_days: 7
});

Exercises

  1. Write a nested query fetching a project, its assigned team members, and the latest 5 task items for each project.
  2. Explain how the !inner modifier transforms PostgREST join semantics from LEFT JOIN to INNER JOIN.
  3. Create an RPC function calculating total monthly revenue for an organization and call it via the SDK.