Stop 13 · Databases, JDBC & JPATopics · 2/12

SQL CRUD (SELECT, INSERT, UPDATE, DELETE)

Part of the Java Roadmap

In short

Four commands do most of the work in any backend: SELECT, INSERT, UPDATE and DELETE. Get these right and you can build the data side of almost any app.

Four commands cover most database work: SELECT reads rows, INSERT adds them, UPDATE changes them and DELETE removes them. WHERE decides which rows each command touches.

The blob writes in a kirana credit notebook behind a shop counter.

Think of it like this

The kirana khata

Sharma uncle's credit notebook works the same way. New customer? Write a line (INSERT). Who still owes money? Read down the page (SELECT). Paid half? Fix the amount (UPDATE). Moved away? Strike the line out (DELETE).

Watch it happen

A day in the khata table

API
PostgreSQL

INSERT INTO khata …

1/6A new customer, Aman, buys on credit. The API adds one row for him.

The big ideas

What you need to know

INSERT adds rows

List the columns, then the values. Leave out id and the database fills it in for you.

SELECT reads rows

Pick columns, filter with WHERE, sort with ORDER BY, cap with LIMIT. Ask only for what you need.

UPDATE changes rows

SET the new values, and always add WHERE. Without it, every single row changes.

DELETE removes rows

Same rule: WHERE first. Many teams soft-delete instead, by setting a deleted_at time.

See it in code

Walk through the code

sql
1INSERT INTO khata (name, due) VALUES ('Aman', 400);2 3SELECT name, due4FROM khata5WHERE due > 06ORDER BY due DESC7LIMIT 10;8 9UPDATE khata SET due = 200 WHERE id = 3;10 11DELETE FROM khata WHERE id = 3;

1/4Add Aman with 400 rupees due. The id is filled in for you.

Try these in psql or any online Postgres playground. Run your WHERE as a SELECT first to preview which rows you'd hit.

Save yourself the pain

Common mistakes

Oops

Running UPDATE khata SET due = 0; and forgetting the WHERE.

Do this instead

Write the WHERE first, or run the same filter as a SELECT to check the rows before changing them.

Oops

Using SELECT * everywhere in app code.

Do this instead

Name the columns you need. It sends less data and won't surprise you when someone adds a column.

Your mission

Run your own khata

~15 min

Quick check

What happens if you run UPDATE khata SET due = 0; with no WHERE?

Go deeper

  1. 1Create a students table and insert ten rows.
  2. 2Write SELECT queries with WHERE, ORDER BY and LIMIT.
  3. 3Always run a SELECT with the same WHERE before an UPDATE or DELETE.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge