Web Development courseLesson 9 of 20 · tap to see all lessons
Web Development · Beginner
SQL with Supabase and PostgreSQL: Tables, Keys, Queries, CRUD, and Project Setup
Write SQL for tables, keys, and relationships, query and change data with SELECT, INSERT, UPDATE, and DELETE, and set up a Supabase PostgreSQL project.
- Qyubie Learn Editorial Team
- Published
- 14 min read
Includes 2 exercises and 2 quick checks you can do right here.
In lesson 8 you sent SQL from PHP to MySQL. This lesson focuses on SQL itself, the language every relational database speaks, and introduces PostgreSQL, the database behind Supabase. Supabase gives you a PostgreSQL database in the cloud with a web dashboard and a ready-made API, and it's what your Next.js project will use from lesson 15 on.
By the end of this lesson you will be able to:
- design tables with primary keys and relationships,
- read data with
SELECT,WHERE,ORDER BY, andJOIN, - change data with
INSERT,UPDATE, andDELETE, - create a Supabase project and tables, and
- explain how an app reaches a Supabase database, and why keys and row level security matter.
The examples marked Run execute in your browser on SQLite, a small database engine. They use standard SQL that works the same way in PostgreSQL. PostgreSQL-only lines appear in plain code blocks, to run in Supabase's SQL Editor.
Tables, rows, columns, and keys
A table holds one kind of thing: students, subjects, orders. Each column has a type, and each row is one record.
| Concept | Meaning | Example |
|---|---|---|
| primary key | a column whose value is unique and never empty, identifying each row | students.id |
| foreign key | a column that holds another table's primary key, linking the rows | enrollments.student_id → students.id |
| one-to-many | one row on one side, many on the other; the foreign key goes on the "many" side | one student, many enrollments |
| many-to-many | many on both sides; modeled with a linking table | students and subjects, linked by enrollments |
Common PostgreSQL types: integer and bigint (whole numbers), numeric(10,2) (exact decimals, for money), text (any length of text), varchar(n), boolean, date, timestamptz (a date and time with time zone), and uuid (a long random ID).
In PostgreSQL (and Supabase), a table with an auto-numbered key and a creation time looks like this:
create table students (
id bigint generated by default as identity primary key,
student_no text not null unique,
full_name text not null,
course text not null,
year_level integer default 1,
created_at timestamptz default now()
);
create table enrollments (
id bigint generated by default as identity primary key,
student_id bigint not null references students (id) on delete cascade,
subject_code text not null,
grade numeric(3, 2)
);generated by default as identitynumbers new rows automatically: PostgreSQL's version of MySQL'sAUTO_INCREMENT. (Older tutorials useserial, which does the same.)references students (id)makesstudent_ida foreign key. The database refuses an enrollment for a student who doesn't exist.on delete cascadedeletes a student's enrollments automatically when the student is deleted.- SQL keywords aren't case-sensitive. PostgreSQL code is often written in lowercase; either way is fine.
SELECT, WHERE, and sorting
Everything starts with reading data. Press Run, then change the query and run it again:
Try it · SQL
The pieces, always in this order:
SELECT columns -- which columns (* for all)
FROM table -- which table
WHERE condition -- which rows
ORDER BY column DESC -- sorting (ASC is the default)
LIMIT 10; -- how many rows at mostUseful conditions: =, <>, <, >=, AND, OR, NOT, IN ('BSCS', 'BSIT'), BETWEEN 1 AND 2, LIKE 'A%' (starts with A), and IS NULL. PostgreSQL also has ILIKE, a LIKE that ignores upper- and lowercase.
Exercise · SQL
Third-year honor roll
List the full_name and gwa of 3rd-year students whose gwa is 2.00 or better (2.00 or lower), best GWA first.
Hint
WHERE year_level = 3 AND gwa <= 2.00, then ORDER BY gwa (ascending: lower is better).
Show a solution
Try it yourself first — you learn more from a wrong attempt than from reading an answer.
SELECT full_name, gwa FROM students WHERE year_level = 3 AND gwa <= 2.00 ORDER BY gwa;
Relationships and JOIN
Data split across tables comes back together with a JOIN, matching the foreign key to the primary key:
Try it · SQL
enrollments e and students s are aliases, and ON s.id = e.student_id says which rows belong together. GROUP BY then summarizes per group: try replacing the last query with this one.
SELECT s.full_name, COUNT(*) AS subjects, AVG(e.grade) AS average
FROM enrollments e
JOIN students s ON s.id = e.student_id
GROUP BY s.full_name;INSERT, UPDATE, and DELETE
Try it · SQL
INSERT INTO table (columns) VALUES (...)adds rows; name the columns, and leave out the auto-numberedid.UPDATE table SET column = value WHERE ...changes rows.DELETE FROM table WHERE ...removes rows.- Always write the
WHERE. Without it,UPDATEandDELETEchange every row in the table.
PostgreSQL can also hand back the row it just changed, using RETURNING. It's how an app learns the new id right after an insert:
insert into students (student_no, full_name, course)
values ('2026-0003', 'Gia Sy', 'BSIT')
returning id, created_at;Exercise · SQL
Fix the subject list
Change the units of PE 4 to 2, delete the subject GE 0, then show all code and units, sorted by code.
Hint
UPDATE subjects SET units = 2 WHERE code = 'PE 4'; then DELETE FROM subjects WHERE code = 'GE 0';
Show a solution
Try it yourself first — you learn more from a wrong attempt than from reading an answer.
UPDATE subjects SET units = 2 WHERE code = 'PE 4'; DELETE FROM subjects WHERE code = 'GE 0'; SELECT code, units FROM subjects ORDER BY code;
Quick check
Setting up a Supabase project
Supabase is a hosted PostgreSQL database with extras: a dashboard, user authentication (lesson 17), file storage, and an automatic Data API that lets apps read and write tables over HTTP. The free plan is enough for this course.
- Create a project. Sign in at supabase.com (with GitHub is easiest) and click New project. Give it a name, choose a region near you (Singapore, for the Philippines), and set a strong database password. Save it in a password manager.
- Create a table with the Table Editor. Open Table Editor, click New table, name it
students, and add columns:student_no(text),full_name(text),course(text),year_level(int4). Anidprimary key andcreated_atare added for you. Click Save. - Or create it with SQL. Open the SQL Editor, paste a
create tablestatement like the one at the top of this lesson, and click Run. Everything you learned above works here, because it's real PostgreSQL. - Add rows. Use Insert row in the Table Editor, or run
insertstatements in the SQL Editor.
How an app reaches the database
There are two ways to connect to a Supabase database:
- The Data API (the usual way for web apps). Your app sends HTTP requests to your project's URL, and Supabase runs the matching SQL. The JavaScript library
@supabase/supabase-jsmakes these requests for you (lesson 16):
import { createClient } from "@supabase/supabase-js";
const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL,
process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY,
);
const { data, error } = await supabase
.from("students")
.select("student_no, full_name")
.eq("course", "BSCS")
.order("full_name");This reads exactly like SELECT student_no, full_name FROM students WHERE course = 'BSCS' ORDER BY full_name. Every call returns { data, error }.
- A direct PostgreSQL connection, like PHP's PDO in lesson 8 (
pgsql:host=...). The connection details are under Connect in the dashboard. Use this from server code and tools, not from the browser.
API keys
The project URL and keys are under Project Settings → API Keys. There are two kinds:
| Key | Looks like | Where it can go |
|---|---|---|
| Publishable key | sb_publishable_... | safe in browser code and public repositories; what it can do is limited by row level security |
| Secret key | sb_secret_... | server only. It bypasses all security rules. Never put it in browser code or commit it to Git. |
Older projects show the same two keys under their legacy names, anon (publishable) and service_role (secret).
Row level security
Because the publishable key is public, anyone can use it to call your Data API. Row level security (RLS) decides which rows each request may read or change. RLS is switched on for tables made in the dashboard's Table Editor; for tables made with SQL, turn it on yourself. With RLS on and no policies, the Data API returns no rows: everything is locked until you allow it.
A policy is a rule written in SQL. This one lets anyone read the subjects table, which suits public data like a course catalog:
alter table subjects enable row level security;
grant select on table subjects to anon, authenticated;
create policy "Anyone can read subjects"
on subjects for select
to anon, authenticated
using ( true );using ( true ) means "every row". The grant line gives the Data API's roles access to the table at all; RLS then decides which rows. Older projects grant this automatically for new tables, but Supabase is changing new projects so that tables are exposed only when you grant access. Writing the grant yourself works on both (without it, a newer project answers with error 42501, "permission denied"). Never use it for private data like grades; lesson 17 shows policies that let users see only their own rows.
Quick check
Basic CRUD and database access, in summary
| Action | SQL | supabase-js (lesson 16) | Who should be allowed |
|---|---|---|---|
| Create | insert into ... | .insert({...}) | usually signed-in users |
| Read | select ... where ... | .select().eq(...) | depends: public catalog vs private records |
| Update | update ... set ... where ... | .update({...}).eq("id", 1) | the owner, or an admin |
| Delete | delete from ... where ... | .delete().eq("id", 1) | the owner, or an admin |
Whatever tool you use, the same rules apply: identify rows by primary key, never build SQL from raw input (supabase-js and PDO's prepared statements both handle this for you), and grant each kind of access on purpose.
Common mistakes
UPDATEorDELETEwithoutWHERE.- Comparing with
= NULL. UseIS NULL. - Double quotes for text in PostgreSQL.
"BSCS"means a column named BSCS; text uses single quotes:'BSCS'. - Putting the secret key in browser code or in a public repository.
- Turning RLS off to "make it work". Write a policy instead.
- Forgetting the foreign key and storing names instead of ids in linked tables.
Summary
- Tables have typed columns; primary keys identify rows, and foreign keys link tables in one-to-many and many-to-many relationships.
SELECT ... FROM ... WHERE ... ORDER BY ... LIMITreads data;JOIN ... ONcombines tables;GROUP BYsummarizes.INSERT,UPDATE ... WHERE, andDELETE ... WHEREchange data; PostgreSQL'sRETURNINGhands back the changed rows.- Supabase is hosted PostgreSQL with a Table Editor, a SQL Editor, and a Data API. The publishable key is public; the secret key is server-only.
- Row level security policies decide what each request may see and change.
Next lesson: API fundamentals: HTTP methods, status codes, JSON, consuming and building APIs, and Git branches.