TalentJR

🗄️ SQL for beginners · Class 12 · Lesson 3 of 18 · Free

PostgreSQL Pro – CTEs, RETURNING, UPSERT and What PostgreSQL Adds

⏱ About 35 minutes · ▶ run real SQL here — nothing to install · no sign-in

In this lesson you will

  • Read PostgreSQL-only syntax: SERIAL, :: casts, ILIKE and BOOLEAN
  • Write a CTE with WITH to split a query into readable steps
  • Use RETURNING, UPSERT (ON CONFLICT) and string and date functions

Your school canteen app starts small, on SQLite. Then 2,000 students start ordering tiffin at 1 pm, and the team moves to PostgreSQL, a database server built for many users at once. Good news: most of your SQL moves with you. This lesson shows what stays the same and what changes.

What is PostgreSQL and how is its SQL different?

PostgreSQL (often called Postgres) is a free, open-source database server. Many people and programs can use one PostgreSQL database at the same time, over a network. SQLite, which runs on this page, keeps the whole database in one file inside one app.

This box is PostgreSQL code. It does not run here, because this page has SQLite, not PostgreSQL. Read it line by line:

SERIAL makes an auto-numbered id (1, 2, 3 …). BOOLEAN stores true or false. NUMERIC(6, 2) stores exact money like 60.00. price::INTEGER is PostgreSQL's short way to change a type (a cast). ILIKE is LIKE that ignores upper and lower case.

Newer PostgreSQL code often writes id INTEGER GENERATED ALWAYS AS IDENTITY instead of SERIAL. Both give auto numbers.

📄 Example to read — PostgreSQL syntax — shown, not run here
CREATE TABLE tiffin_orders (
    id         SERIAL PRIMARY KEY,
    student    VARCHAR(50) NOT NULL,
    item       TEXT NOT NULL,
    price      NUMERIC(6, 2) NOT NULL,
    delivered  BOOLEAN DEFAULT FALSE,
    ordered_on DATE DEFAULT CURRENT_DATE
);

INSERT INTO tiffin_orders (student, item, price)
VALUES ('Riya', 'Veg Pulao', 60.00), ('Aman', 'Idli Sambar', 45.50);

SELECT id, student, price::INTEGER AS rupees
FROM tiffin_orders
WHERE item ILIKE '%PULAO%' AND NOT delivered;

How do you write the same table in SQLite?

Here is the same idea in SQLite, and this one runs. INTEGER PRIMARY KEY numbers new rows by itself, so it does the job of SERIAL. MySQL uses AUTO_INCREMENT for the same job.

SQLite has no separate BOOLEAN type: it stores 1 for true and 0 for false. Types are flexible in SQLite, so VARCHAR(50) would also be accepted. PostgreSQL checks types strictly.

CAST(price AS INTEGER) is the standard way to write a cast. It works in PostgreSQL too. One difference: SQLite's CAST cuts off the decimals (45.50 becomes 45), while PostgreSQL rounds (46).

SQLite's LIKE already ignores case, so it has no ILIKE. Try it: change '%PULAO%' to '%idli%' and run again.

🗄️ SQL — you can edit this query
Result
Table tiffin_orders created.

2 rows inserted.

┌────┬─────────┬────────┐
│ id │ student │ rupees │
├────┼─────────┼────────┤
│ 1  │ Riya    │ 60     │
└────┴─────────┴────────┘
(1 row)

What is a CTE (WITH clause) in SQL?

A CTE (Common Table Expression) is a named, temporary result that lives only inside one query. You write WITH name AS (a query), then use name like a table.

CTEs turn one big, confusing query into small steps with clear names. They work the same way in PostgreSQL, SQLite and MySQL 8.

Below, step 1 (toppers) finds every mark of 90 or more. Step 2 joins those rows to students and subjects to show names, like the JOIN preview in Lesson 2.

Try it: change 90 to 85 and see who joins the list.

📋 Tables in this example: students, subjects, teachers, marks, fees — tap to see how they are made
-- TalentJR practice school (made-up data for SQL lessons)
CREATE TABLE students (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  class   INTEGER NOT NULL,
  section TEXT NOT NULL,
  city    TEXT,
  joined  TEXT NOT NULL
);
INSERT INTO students VALUES
 (1, 'Riya Sharma', 12, 'A', 'Pune', '2019-06-10'),
 (2, 'Aman Verma', 12, 'A', 'Mumbai', '2020-06-15'),
 (3, 'Sara Khan', 12, 'B', 'Pune', '2019-06-10'),
 (4, 'Dev Patil', 11, 'A', 'Nagpur', '2021-06-14'),
 (5, 'Meera Iyer', 11, 'B', 'Chennai', '2021-06-14'),
 (6, 'Kabir Singh', 12, 'B', 'Delhi', '2022-07-01'),
 (7, 'Anaya Joshi', 11, 'A', 'Pune', '2023-06-12'),
 (8, 'Rohan Das', 12, 'A', NULL, '2023-06-12');
CREATE TABLE subjects (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL UNIQUE
);
INSERT INTO subjects VALUES (1, 'Maths'), (2, 'Physics'), (3, 'Chemistry'), (4, 'Computer Science'), (5, 'English');
CREATE TABLE teachers (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  subject_id INTEGER REFERENCES subjects(id)
);
INSERT INTO teachers VALUES (1, 'Mrs. Kulkarni', 1), (2, 'Mr. Rao', 2), (3, 'Ms. Fernandes', 4), (4, 'Mr. Gupta', 5), (5, 'Mrs. Nair', NULL);
CREATE TABLE marks (
  student_id INTEGER NOT NULL REFERENCES students(id),
  subject_id INTEGER NOT NULL REFERENCES subjects(id),
  marks      INTEGER NOT NULL CHECK (marks BETWEEN 0 AND 100),
  PRIMARY KEY (student_id, subject_id)
);
INSERT INTO marks VALUES
 (1,1,92),(1,2,88),(1,3,79),(1,4,95),(1,5,84),
 (2,1,75),(2,2,68),(2,3,72),(2,4,81),(2,5,90),
 (3,1,81),(3,2,77),(3,3,85),(3,4,70),(3,5,88),
 (4,1,64),(4,2,58),(4,4,88),(4,5,71),
 (5,1,95),(5,2,91),(5,3,89),(5,4,93),(5,5,86),
 (6,1,55),(6,2,62),(6,3,49),(6,5,67),
 (7,1,73),(7,4,99),(7,5,80);
CREATE TABLE fees (
  student_id INTEGER NOT NULL REFERENCES students(id),
  month      TEXT NOT NULL,
  amount     INTEGER NOT NULL,
  paid       INTEGER NOT NULL DEFAULT 0
);
INSERT INTO fees VALUES
 (1,'2026-06',4500,1),(1,'2026-07',4500,1),(2,'2026-06',4500,1),(2,'2026-07',4500,0),
 (3,'2026-06',4500,1),(4,'2026-06',4000,1),(4,'2026-07',4000,0),(5,'2026-06',4000,1),
 (6,'2026-06',4500,0),(7,'2026-06',4000,1),(8,'2026-06',4500,1);
🗄️ SQL — you can edit this query
Result
┌─────────────┬──────────────────┬───────┐
│ name        │ subject          │ marks │
├─────────────┼──────────────────┼───────┤
│ Anaya Joshi │ Computer Science │ 99    │
│ Meera Iyer  │ Maths            │ 95    │
│ Riya Sharma │ Computer Science │ 95    │
│ Meera Iyer  │ Computer Science │ 93    │
│ Riya Sharma │ Maths            │ 92    │
│ Meera Iyer  │ Physics          │ 91    │
│ Aman Verma  │ English          │ 90    │
└─────────────┴──────────────────┴───────┘
(7 rows)

How does RETURNING work in PostgreSQL and SQLite?

INSERT adds a row and UPDATE changes rows (Lesson 6 covers both in detail). Normally they show no result. RETURNING asks the database to send back the rows it just changed.

This is very useful in apps. After adding a new student, the app needs the new id that the database chose. RETURNING gives it in the same step.

PostgreSQL has had RETURNING for years. SQLite added it in version 3.35, and this page runs 3.54. MySQL does not have it.

Try it: change the name and city of the new student, or change student_id = 2 to 4 in the UPDATE.

📋 Tables in this example: students, subjects, teachers, marks, fees — tap to see how they are made
-- TalentJR practice school (made-up data for SQL lessons)
CREATE TABLE students (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  class   INTEGER NOT NULL,
  section TEXT NOT NULL,
  city    TEXT,
  joined  TEXT NOT NULL
);
INSERT INTO students VALUES
 (1, 'Riya Sharma', 12, 'A', 'Pune', '2019-06-10'),
 (2, 'Aman Verma', 12, 'A', 'Mumbai', '2020-06-15'),
 (3, 'Sara Khan', 12, 'B', 'Pune', '2019-06-10'),
 (4, 'Dev Patil', 11, 'A', 'Nagpur', '2021-06-14'),
 (5, 'Meera Iyer', 11, 'B', 'Chennai', '2021-06-14'),
 (6, 'Kabir Singh', 12, 'B', 'Delhi', '2022-07-01'),
 (7, 'Anaya Joshi', 11, 'A', 'Pune', '2023-06-12'),
 (8, 'Rohan Das', 12, 'A', NULL, '2023-06-12');
CREATE TABLE subjects (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL UNIQUE
);
INSERT INTO subjects VALUES (1, 'Maths'), (2, 'Physics'), (3, 'Chemistry'), (4, 'Computer Science'), (5, 'English');
CREATE TABLE teachers (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  subject_id INTEGER REFERENCES subjects(id)
);
INSERT INTO teachers VALUES (1, 'Mrs. Kulkarni', 1), (2, 'Mr. Rao', 2), (3, 'Ms. Fernandes', 4), (4, 'Mr. Gupta', 5), (5, 'Mrs. Nair', NULL);
CREATE TABLE marks (
  student_id INTEGER NOT NULL REFERENCES students(id),
  subject_id INTEGER NOT NULL REFERENCES subjects(id),
  marks      INTEGER NOT NULL CHECK (marks BETWEEN 0 AND 100),
  PRIMARY KEY (student_id, subject_id)
);
INSERT INTO marks VALUES
 (1,1,92),(1,2,88),(1,3,79),(1,4,95),(1,5,84),
 (2,1,75),(2,2,68),(2,3,72),(2,4,81),(2,5,90),
 (3,1,81),(3,2,77),(3,3,85),(3,4,70),(3,5,88),
 (4,1,64),(4,2,58),(4,4,88),(4,5,71),
 (5,1,95),(5,2,91),(5,3,89),(5,4,93),(5,5,86),
 (6,1,55),(6,2,62),(6,3,49),(6,5,67),
 (7,1,73),(7,4,99),(7,5,80);
CREATE TABLE fees (
  student_id INTEGER NOT NULL REFERENCES students(id),
  month      TEXT NOT NULL,
  amount     INTEGER NOT NULL,
  paid       INTEGER NOT NULL DEFAULT 0
);
INSERT INTO fees VALUES
 (1,'2026-06',4500,1),(1,'2026-07',4500,1),(2,'2026-06',4500,1),(2,'2026-07',4500,0),
 (3,'2026-06',4500,1),(4,'2026-06',4000,1),(4,'2026-07',4000,0),(5,'2026-06',4000,1),
 (6,'2026-06',4500,0),(7,'2026-06',4000,1),(8,'2026-06',4500,1);
🗄️ SQL — you can edit this query
Result
┌────┬──────────────┐
│ id │ name         │
├────┼──────────────┤
│ 9  │ Ishaan Mehta │
└────┴──────────────┘
(1 row)

┌────────────┬─────────┬──────┐
│ student_id │ month   │ paid │
├────────────┼─────────┼──────┤
│ 2          │ 2026-07 │ 1    │
└────────────┴─────────┴──────┘
(1 row)

What is UPSERT (INSERT ON CONFLICT) in SQL?

A kirana shop gets new stock. If the item is already in the table, the quantity should go up. If it is new, a row should be added. Doing "insert, or update if it exists" in one statement is called an UPSERT.

ON CONFLICT (item) says: if this insert would break the PRIMARY KEY on item, do something else. DO UPDATE then changes the old row. excluded.qty means "the qty you tried to insert".

This exact syntax works in PostgreSQL and in SQLite. MySQL writes it as ON DUPLICATE KEY UPDATE.

Try it: add ('salt', 6) to the VALUES list and run again. Salt is new, so it is inserted.

📋 Tables in this example: stock — tap to see how they are made
CREATE TABLE stock (
    item TEXT PRIMARY KEY,
    qty  INTEGER NOT NULL
);
INSERT INTO stock VALUES ('rice', 10), ('sugar', 4), ('tea', 2);
🗄️ SQL — you can edit this query
Result
2 rows inserted or updated.

┌───────┬─────┐
│ item  │ qty │
├───────┼─────┤
│ dal   │ 8   │
│ rice  │ 15  │
│ sugar │ 4   │
│ tea   │ 2   │
└───────┴─────┘
(4 rows)

💡 The message counts every row the statement touched: dal was inserted and rice was updated.

Which string and date functions can you use in SQL?

upper() and lower() change case. length() counts characters. substr(text, start, count) cuts out a piece; counting starts at 1. || joins text, in both SQLite and PostgreSQL (MySQL uses CONCAT()).

SQLite stores dates as 'YYYY-MM-DD' text. date(d, '+30 days') moves a date, and strftime('%Y', d) pulls out the year. julianday() turns a date into a day number, so subtracting two of them gives days between dates.

PostgreSQL has a real DATE type with its own functions, for example joined + 30 and EXTRACT(YEAR FROM joined). The ideas are the same; the spelling differs.

Try it: change '+30 days' to '+1 month'.

📋 Tables in this example: students, subjects, teachers, marks, fees — tap to see how they are made
-- TalentJR practice school (made-up data for SQL lessons)
CREATE TABLE students (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  class   INTEGER NOT NULL,
  section TEXT NOT NULL,
  city    TEXT,
  joined  TEXT NOT NULL
);
INSERT INTO students VALUES
 (1, 'Riya Sharma', 12, 'A', 'Pune', '2019-06-10'),
 (2, 'Aman Verma', 12, 'A', 'Mumbai', '2020-06-15'),
 (3, 'Sara Khan', 12, 'B', 'Pune', '2019-06-10'),
 (4, 'Dev Patil', 11, 'A', 'Nagpur', '2021-06-14'),
 (5, 'Meera Iyer', 11, 'B', 'Chennai', '2021-06-14'),
 (6, 'Kabir Singh', 12, 'B', 'Delhi', '2022-07-01'),
 (7, 'Anaya Joshi', 11, 'A', 'Pune', '2023-06-12'),
 (8, 'Rohan Das', 12, 'A', NULL, '2023-06-12');
CREATE TABLE subjects (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL UNIQUE
);
INSERT INTO subjects VALUES (1, 'Maths'), (2, 'Physics'), (3, 'Chemistry'), (4, 'Computer Science'), (5, 'English');
CREATE TABLE teachers (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  subject_id INTEGER REFERENCES subjects(id)
);
INSERT INTO teachers VALUES (1, 'Mrs. Kulkarni', 1), (2, 'Mr. Rao', 2), (3, 'Ms. Fernandes', 4), (4, 'Mr. Gupta', 5), (5, 'Mrs. Nair', NULL);
CREATE TABLE marks (
  student_id INTEGER NOT NULL REFERENCES students(id),
  subject_id INTEGER NOT NULL REFERENCES subjects(id),
  marks      INTEGER NOT NULL CHECK (marks BETWEEN 0 AND 100),
  PRIMARY KEY (student_id, subject_id)
);
INSERT INTO marks VALUES
 (1,1,92),(1,2,88),(1,3,79),(1,4,95),(1,5,84),
 (2,1,75),(2,2,68),(2,3,72),(2,4,81),(2,5,90),
 (3,1,81),(3,2,77),(3,3,85),(3,4,70),(3,5,88),
 (4,1,64),(4,2,58),(4,4,88),(4,5,71),
 (5,1,95),(5,2,91),(5,3,89),(5,4,93),(5,5,86),
 (6,1,55),(6,2,62),(6,3,49),(6,5,67),
 (7,1,73),(7,4,99),(7,5,80);
CREATE TABLE fees (
  student_id INTEGER NOT NULL REFERENCES students(id),
  month      TEXT NOT NULL,
  amount     INTEGER NOT NULL,
  paid       INTEGER NOT NULL DEFAULT 0
);
INSERT INTO fees VALUES
 (1,'2026-06',4500,1),(1,'2026-07',4500,1),(2,'2026-06',4500,1),(2,'2026-07',4500,0),
 (3,'2026-06',4500,1),(4,'2026-06',4000,1),(4,'2026-07',4000,0),(5,'2026-06',4000,1),
 (6,'2026-06',4500,0),(7,'2026-06',4000,1),(8,'2026-06',4500,1);
🗄️ SQL — you can edit this query
Result
┌─────────────┬─────────┬───────┐
│ shout       │ letters │ login │
├─────────────┼─────────┼───────┤
│ DEV PATIL   │ 9       │ dev4  │
│ MEERA IYER  │ 10      │ mee5  │
│ ANAYA JOSHI │ 11      │ ana7  │
└─────────────┴─────────┴───────┘
(3 rows)

┌─────────────┬───────────┬─────────────┬────────────────┐
│ name        │ join_year │ id_card_due │ days_in_school │
├─────────────┼───────────┼─────────────┼────────────────┤
│ Riya Sharma │ 2019      │ 2019-07-10  │ 2548           │
│ Sara Khan   │ 2019      │ 2019-07-10  │ 2548           │
│ Anaya Joshi │ 2023      │ 2023-07-12  │ 1085           │
└─────────────┴───────────┴─────────────┴────────────────┘
(3 rows)

💡 date('now') gives today's date, so its result changes every day. We use fixed dates here.

🤔 Predict the output

Think like SQL: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this query return?

📋 The tables (tap to see them)
-- TalentJR practice school (made-up data for SQL lessons)
CREATE TABLE students (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  class   INTEGER NOT NULL,
  section TEXT NOT NULL,
  city    TEXT,
  joined  TEXT NOT NULL
);
INSERT INTO students VALUES
 (1, 'Riya Sharma', 12, 'A', 'Pune', '2019-06-10'),
 (2, 'Aman Verma', 12, 'A', 'Mumbai', '2020-06-15'),
 (3, 'Sara Khan', 12, 'B', 'Pune', '2019-06-10'),
 (4, 'Dev Patil', 11, 'A', 'Nagpur', '2021-06-14'),
 (5, 'Meera Iyer', 11, 'B', 'Chennai', '2021-06-14'),
 (6, 'Kabir Singh', 12, 'B', 'Delhi', '2022-07-01'),
 (7, 'Anaya Joshi', 11, 'A', 'Pune', '2023-06-12'),
 (8, 'Rohan Das', 12, 'A', NULL, '2023-06-12');
CREATE TABLE subjects (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL UNIQUE
);
INSERT INTO subjects VALUES (1, 'Maths'), (2, 'Physics'), (3, 'Chemistry'), (4, 'Computer Science'), (5, 'English');
CREATE TABLE teachers (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  subject_id INTEGER REFERENCES subjects(id)
);
INSERT INTO teachers VALUES (1, 'Mrs. Kulkarni', 1), (2, 'Mr. Rao', 2), (3, 'Ms. Fernandes', 4), (4, 'Mr. Gupta', 5), (5, 'Mrs. Nair', NULL);
CREATE TABLE marks (
  student_id INTEGER NOT NULL REFERENCES students(id),
  subject_id INTEGER NOT NULL REFERENCES subjects(id),
  marks      INTEGER NOT NULL CHECK (marks BETWEEN 0 AND 100),
  PRIMARY KEY (student_id, subject_id)
);
INSERT INTO marks VALUES
 (1,1,92),(1,2,88),(1,3,79),(1,4,95),(1,5,84),
 (2,1,75),(2,2,68),(2,3,72),(2,4,81),(2,5,90),
 (3,1,81),(3,2,77),(3,3,85),(3,4,70),(3,5,88),
 (4,1,64),(4,2,58),(4,4,88),(4,5,71),
 (5,1,95),(5,2,91),(5,3,89),(5,4,93),(5,5,86),
 (6,1,55),(6,2,62),(6,3,49),(6,5,67),
 (7,1,73),(7,4,99),(7,5,80);
CREATE TABLE fees (
  student_id INTEGER NOT NULL REFERENCES students(id),
  month      TEXT NOT NULL,
  amount     INTEGER NOT NULL,
  paid       INTEGER NOT NULL DEFAULT 0
);
INSERT INTO fees VALUES
 (1,'2026-06',4500,1),(1,'2026-07',4500,1),(2,'2026-06',4500,1),(2,'2026-07',4500,0),
 (3,'2026-06',4500,1),(4,'2026-06',4000,1),(4,'2026-07',4000,0),(5,'2026-06',4000,1),
 (6,'2026-06',4500,0),(7,'2026-06',4000,1),(8,'2026-06',4500,1);
WITH pune AS (
    SELECT id, name FROM students WHERE city = 'Pune'
)
SELECT name FROM pune
WHERE id > 1
ORDER BY name;

Question 2. Rice already has qty 10. What is the result?

📋 The tables (tap to see them)
CREATE TABLE stock (
    item TEXT PRIMARY KEY,
    qty  INTEGER NOT NULL
);
INSERT INTO stock VALUES ('rice', 10), ('sugar', 4), ('tea', 2);
INSERT INTO stock (item, qty)
VALUES ('rice', 5)
ON CONFLICT (item) DO UPDATE
SET qty = stock.qty + excluded.qty;

SELECT qty FROM stock WHERE item = 'rice';

Question 3. What does this return?

SELECT upper(substr('talentjr', 1, 3)) || '-' || length('Pune') AS code;

🧩 Your challenge

Make ID-card labels for class 11. Use a CTE named class11 that keeps only class 11 students. Then show name, a column tag made of the first 3 letters of the city in capitals inside brackets, and join_year (the year they joined). Sort by name. Expected: Anaya Joshi | (PUN) | 2023 Dev Patil | (NAG) | 2021 Meera Iyer | (CHE) | 2021

Expected result :
┌─────────────┬───────┬───────────┐
│ name        │ tag   │ join_year │
├─────────────┼───────┼───────────┤
│ Anaya Joshi │ (PUN) │ 2023      │
│ Dev Patil   │ (NAG) │ 2021      │
│ Meera Iyer  │ (CHE) │ 2021      │
└─────────────┴───────┴───────────┘
(3 rows)
📋 Tables in this example: students, subjects, teachers, marks, fees — tap to see how they are made
-- TalentJR practice school (made-up data for SQL lessons)
CREATE TABLE students (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  class   INTEGER NOT NULL,
  section TEXT NOT NULL,
  city    TEXT,
  joined  TEXT NOT NULL
);
INSERT INTO students VALUES
 (1, 'Riya Sharma', 12, 'A', 'Pune', '2019-06-10'),
 (2, 'Aman Verma', 12, 'A', 'Mumbai', '2020-06-15'),
 (3, 'Sara Khan', 12, 'B', 'Pune', '2019-06-10'),
 (4, 'Dev Patil', 11, 'A', 'Nagpur', '2021-06-14'),
 (5, 'Meera Iyer', 11, 'B', 'Chennai', '2021-06-14'),
 (6, 'Kabir Singh', 12, 'B', 'Delhi', '2022-07-01'),
 (7, 'Anaya Joshi', 11, 'A', 'Pune', '2023-06-12'),
 (8, 'Rohan Das', 12, 'A', NULL, '2023-06-12');
CREATE TABLE subjects (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL UNIQUE
);
INSERT INTO subjects VALUES (1, 'Maths'), (2, 'Physics'), (3, 'Chemistry'), (4, 'Computer Science'), (5, 'English');
CREATE TABLE teachers (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  subject_id INTEGER REFERENCES subjects(id)
);
INSERT INTO teachers VALUES (1, 'Mrs. Kulkarni', 1), (2, 'Mr. Rao', 2), (3, 'Ms. Fernandes', 4), (4, 'Mr. Gupta', 5), (5, 'Mrs. Nair', NULL);
CREATE TABLE marks (
  student_id INTEGER NOT NULL REFERENCES students(id),
  subject_id INTEGER NOT NULL REFERENCES subjects(id),
  marks      INTEGER NOT NULL CHECK (marks BETWEEN 0 AND 100),
  PRIMARY KEY (student_id, subject_id)
);
INSERT INTO marks VALUES
 (1,1,92),(1,2,88),(1,3,79),(1,4,95),(1,5,84),
 (2,1,75),(2,2,68),(2,3,72),(2,4,81),(2,5,90),
 (3,1,81),(3,2,77),(3,3,85),(3,4,70),(3,5,88),
 (4,1,64),(4,2,58),(4,4,88),(4,5,71),
 (5,1,95),(5,2,91),(5,3,89),(5,4,93),(5,5,86),
 (6,1,55),(6,2,62),(6,3,49),(6,5,67),
 (7,1,73),(7,4,99),(7,5,80);
CREATE TABLE fees (
  student_id INTEGER NOT NULL REFERENCES students(id),
  month      TEXT NOT NULL,
  amount     INTEGER NOT NULL,
  paid       INTEGER NOT NULL DEFAULT 0
);
INSERT INTO fees VALUES
 (1,'2026-06',4500,1),(1,'2026-07',4500,1),(2,'2026-06',4500,1),(2,'2026-07',4500,0),
 (3,'2026-06',4500,1),(4,'2026-06',4000,1),(4,'2026-07',4000,0),(5,'2026-06',4000,1),
 (6,'2026-06',4500,0),(7,'2026-06',4000,1),(8,'2026-06',4500,1);
🗄️ SQL — you can edit this query

⚠️ Common mistakes (and how to fix them)

❌ Wrong

SELECT '42'::INTEGER + 1 AS answer;

Error: unrecognized token: ":"

✅ Right

SELECT CAST('42' AS INTEGER) + 1 AS answer;

:: is PostgreSQL-only. Code copied from a PostgreSQL tutorial fails in SQLite and MySQL; CAST(… AS …) works everywhere.

❌ Wrong

CREATE TABLE stock (item TEXT, qty INTEGER);
INSERT INTO stock VALUES ('rice', 10);
INSERT INTO stock VALUES ('rice', 5)
ON CONFLICT (item) DO UPDATE SET qty = stock.qty + excluded.qty;

Error: ON CONFLICT clause does not match any PRIMARY KEY or UNIQUE constraint

✅ Right

CREATE TABLE stock (item TEXT PRIMARY KEY, qty INTEGER);
INSERT INTO stock VALUES ('rice', 10);
INSERT INTO stock VALUES ('rice', 5)
ON CONFLICT (item) DO UPDATE SET qty = stock.qty + excluded.qty;

A conflict can only happen on a PRIMARY KEY or UNIQUE column. Without one, the database cannot know which row clashes.

❌ Wrong

WITH pune AS (SELECT name FROM students WHERE city = 'Pune');
SELECT name FROM pune;

Error: near ";": syntax error

✅ Right

WITH pune AS (SELECT name FROM students WHERE city = 'Pune')
SELECT name FROM pune;

A CTE belongs to the one statement right after it. The semicolon ends the statement too early, so the CTE has no query to belong to.

📌 Remember

  • PostgreSQL is a free database server for many users; SQLite is a database in one file.
  • PostgreSQL-only syntax: SERIAL, BOOLEAN, :: casts and ILIKE. CAST(… AS …) works everywhere.
  • A CTE (WITH name AS (…)) names a step of a query and makes long queries readable.
  • RETURNING sends back the rows an INSERT or UPDATE changed, such as a new id.
  • INSERT … ON CONFLICT … DO UPDATE is an UPSERT: insert, or update if the key exists.
  • Strings: upper, lower, length, substr, ||. Dates in SQLite: date(), strftime(), julianday().

Finished the quiz and the challenge?

Questions students ask

Is PostgreSQL free?

Yes. PostgreSQL is open source under the PostgreSQL License, so anyone can use it for free, even in big commercial apps.

What is the difference between PostgreSQL and MySQL?

Both are free database servers that speak SQL. PostgreSQL is stricter about types and has extra features such as RETURNING and rich JSON support. MySQL is also very popular for websites. The core SELECT, WHERE, JOIN and GROUP BY are the same in both.

Can I run PostgreSQL code on this page?

No. The boxes on this page run SQLite in your browser, so PostgreSQL-only code is shown read-only. To run it, install PostgreSQL on a computer and use its psql tool or a free desktop client.

Does SQLite support CTEs, RETURNING and ON CONFLICT?

Yes. SQLite has supported CTEs since 3.8.3, UPSERT (ON CONFLICT … DO UPDATE) since 3.24 and RETURNING since 3.35. This page runs SQLite 3.54.