Skip to content

建立 2026-09-14 更新 2026-09-14

SQL Editor

Table Editor 適合建表與點選編輯。複雜查詢、一次改很多列、函式與觸發器,請改用 SQL Editor。這裡跑的就是標準 PostgreSQL,學會的語法可以帶走。

跑一條查詢

開啟 SQL Editor,貼上後按 Run:

select id, task, is_complete
from todos
where is_complete = false
order by created_at desc
limit 20;

結果顯示在下方。常用查詢可以存成 snippet,下次不必重打。

Dashboard 的 AI 輔助(編輯器裡的 Command-K 一類功能)能幫你起草 SQL,但執行前一定要自己看過:尤其是 update / delete 沒有 where 的語句。

資料庫函式(RPC)

把一段 SQL 包成函式,前端用 .rpc('function_name') 呼叫。適合「不能只靠單表 CRUD」的邏輯,例如依條件回傳彙總、或必須在資料庫端完成的寫入。

create or replace function public.incomplete_count()
returns bigint
language sql
stable
as $$
  select count(*) from public.todos where is_complete = false;
$$;
const { data, error } = await supabase.rpc('incomplete_count')

函式預設也受權限與 RLS 影響。需要讓登入使用者呼叫時,記得 grant executeauthenticated,並在函式裡用 security invoker(預設)讓 RLS 仍生效。

觸發器

資料列一變就自動跑函式,例如「新增 post 時插入一則歡迎留言」、或把 updated_at 設成現在。

create or replace function public.set_updated_at()
returns trigger
language plpgsql
as $$
begin
  new.updated_at = now();
  return new;
end;
$$;

create trigger todos_set_updated_at
before update on public.todos
for each row
execute function public.set_updated_at();

觸發器在資料庫內執行,前端繞不開。適合完整性規則;不適合呼叫外部 HTTP(那是 Edge Functions 或 Database Webhooks 的工作)。

相關資料