CRUD Operations, Done Well, in a Small Inventory App

CRUD means Create, Read, Update and Delete. This page shows what doing each one well looks like in a hypothetical inventory app for a school club's equipment cupboard. It is a model to learn from, not a real project or testimonial.

The table

CREATE TABLE items (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  quantity INTEGER NOT NULL CHECK (quantity >= 0),
  location TEXT,
  updated_on TEXT NOT NULL
);

Already good: a primary key, required fields marked NOT NULL, and a CHECK rule so quantity can never go below zero.

Create, done well

INSERT INTO items (name, quantity, location, updated_on)
VALUES (?, ?, ?, ?);

Read, done well

SELECT id, name, quantity FROM items WHERE location = ? ORDER BY name;

For a single item page, the app reads by primary key: WHERE id = ?.

Update, done well

When someone takes two footballs out of the cupboard:

UPDATE items SET quantity = quantity - 2, updated_on = ? WHERE id = ?;

Delete, done well

The four, side by side

OperationGood habitMistake it avoids
CreateExplicit columns, placeholdersBroken inserts, SQL injection
ReadSelect needed columns, filter in SQLSlow pages, wasted memory
UpdateCalculate in SQL, target by idLost updates, changing wrong rows
DeleteConfirm, target by id, foreign keysAccidental mass deletes, orphan rows

Extras that make the app pleasant

Compare with your own project

Pick one table in your app and check each CRUD operation against the table above. Our long read on create, read, update and delete explains each statement in more depth, and troubleshooting an UPDATE or DELETE that changed the wrong rows covers what to do when things go wrong.

A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.

Illustrative example: the organisations, people, projects and results described on this page are hypothetical. They do not describe a real client or engagement, and no consulting services are offered here.