Basic SQL Queries

The four core commands (SELECT, INSERT, UPDATE, DELETE) for reading and changing data.

What is it?

SQL (Structured Query Language) is the language almost every relational database understands. It's built around four core operations, known as CRUD (Create, Read, Update, Delete):

  • SELECT: read existing rows
  • INSERT: add a new row
  • UPDATE: change values in existing rows
  • DELETE: remove rows

These four, plus ways to filter which rows they touch, cover most everyday database work.

Explain like I'm 10

Think of a table as a shared notebook. SELECT is reading a page. INSERT is writing a new entry on a fresh line. UPDATE is crossing out part of an entry and writing a correction. DELETE is tearing an entry out.

Examples

All four operations on a users table

-- Read every user
SELECT * FROM users;

-- Add a new user
INSERT INTO users (name, email) VALUES ('Amara', 'amara@example.com');

-- Change an existing user's email
UPDATE users SET email = 'amara@newmail.com' WHERE id = 1;

-- Remove a user
DELETE FROM users WHERE id = 1;

Each statement is a complete command, usually one operation at a time, ending in a semicolon.

Selecting specific columns

SELECT name, email FROM users;

UPDATE users SET age = age + 1 WHERE id = 3;

SELECT can list just the columns you need. UPDATE can compute a new value from the current one, like adding 1 to age.

How it works

The database parses each SQL statement into a plan: which table to touch, which rows match, and what to do with them.

SELECT only reads; it never changes data. INSERT, UPDATE, and DELETE change the table. Without a WHERE clause, UPDATE and DELETE apply to every row, which is why forgetting WHERE is one of the most dangerous mistakes in SQL.

Why does it exist?

SQL means you don't write custom code for every read or change. You describe what you want ("all users older than 30") and the database works out how to get it. The same standard language works across almost every relational database.

When to use it

  • SELECT: whenever you need to read data.
  • INSERT: when new data is created (a signup, an order).
  • UPDATE: when existing data changes (a new address, a status change).
  • DELETE: when data should be removed for good.

When not to use it

For huge one-time loads (millions of rows), many databases offer faster bulk-loading tools than individual INSERTs. For data you might need to recover, consider a "soft delete" (marking a row inactive) instead of a real DELETE.

Common mistakes

  • Running UPDATE or DELETE without a WHERE clause, which changes every row in the table.

  • Forgetting that SELECT * fetches every column, even unneeded ones, wasting bandwidth on large tables.

  • Thinking INSERT must list every column. Columns with defaults or that allow empty values can often be left out.

Practice exercises

  1. Easy:

    Write a SELECT that gets the name and email of every row in a users table.

  2. Medium:

    Write an INSERT that adds a product with a name and price to a products table, then an UPDATE that changes its price.

  3. Hard:

    Explain step by step what happens if you run DELETE FROM users; with no WHERE clause, and why that's dangerous.

Interview questions

What do the four basic SQL commands SELECT, INSERT, UPDATE, and DELETE each do?

SELECT reads rows, INSERT adds a new row, UPDATE modifies values in existing rows, and DELETE removes rows.

What happens if you run an UPDATE statement with no WHERE clause?

It applies the change to every row in the table, not just one — which is a common and dangerous mistake.

Does SELECT ever modify the underlying data?

No — SELECT only reads and returns data; it never changes what's stored.

How do you insert multiple new rows using a single INSERT statement?

List several value groups after VALUES, separated by commas. For example, INSERT INTO products (name, price_cents) VALUES ('Pen', 150), ('Notebook', 300), ('Eraser', 50); inserts three rows.

Why is a single multi-row INSERT generally more efficient than the same number of single-row INSERT statements?

One statement is sent and parsed instead of many, so the database can batch the work. That means fewer round trips and often less repeated bookkeeping like index updates, which matters when inserting many rows.

What does adding `RETURNING *` (or specific columns) to an INSERT statement do?

It returns the row as stored, including values the database generated (like an auto-incremented id or default timestamp), in the same round trip. No separate SELECT needed.

Why is RETURNING especially useful after an INSERT that relies on an auto-generated primary key?

Your app doesn't know the generated id in advance. Without RETURNING, you'd need a second query and some other unique detail to find the new row. RETURNING gives you the id right away.

Is RETURNING part of every SQL database's basic dialect?

No. Support varies by database, so check your database's documentation instead of assuming it works the same everywhere.

Can RETURNING be used with UPDATE and DELETE statements too, not just INSERT?

Yes, where supported. UPDATE ... RETURNING gives the row's new values; DELETE ... RETURNING gives the row's values just before it was removed.

Running `INSERT INTO users (name) VALUES ('Amara');` fails, and `email` is declared NOT NULL with no default. Why?

You can leave a column out of an INSERT only if it has a DEFAULT or allows NULL. email has neither, so the insert is rejected.

If you supply an explicit column list in an INSERT, like `INSERT INTO users (email, name) VALUES ('a@x.com', 'Amara');`, does the order of those columns need to match the table's declared column order?

No. With a column list, values match columns by position in that list, so email before name is fine. Without a column list, VALUES must follow the table's declared column order.

What's the difference between `UPDATE products SET price_cents = 500` and `UPDATE products SET price_cents = price_cents + 100`?

The first sets every matching row to exactly 500. The second adds 100 to each row's current price, so results differ by starting price.

If an UPDATE or DELETE's WHERE clause matches zero rows, is that an error?

No. The statement succeeds and changes zero rows. Most databases report a rows-affected count of 0.

What's the difference between `DELETE FROM orders;` with no WHERE and `TRUNCATE TABLE orders;`?

Both remove every row. DELETE removes rows one by one and accepts a WHERE clause. TRUNCATE resets the whole table at once: often faster, but it can't take a WHERE clause and may treat things like auto-increment counters differently depending on the database.

Can a SELECT return a computed value that isn't stored as an actual column?

Yes. SELECT can include expressions. SELECT price_cents * quantity AS line_total FROM order_items; computes a value per row and names it line_total.

What does `AS` do in a statement like `SELECT price_cents * quantity AS line_total`?

It gives an expression (or column) an alias: the name used for it in the results. Handy for expressions that would otherwise have no meaningful name.

What's the difference between `INSERT INTO ... VALUES (...)` and `INSERT INTO ... SELECT ...`?

VALUES inserts rows you write out literally. INSERT INTO ... SELECT inserts whatever rows a query returns, which is useful for copying or transforming data between tables without pulling it into the app.

If a multi-row INSERT includes one row that violates a constraint, like a duplicate primary key, what typically happens to the other, valid rows in that statement?

In most databases the whole statement fails and no rows are inserted. The statement is atomic, so one bad row rolls back the batch instead of leaving partial results.

Could `UPDATE users SET status = 'active' WHERE last_login > '2026-01-01';` ever match more than one row?

Yes, easily. WHERE only guarantees one row when filtering on a unique column like a primary key. A non-unique column like last_login can match any number of rows, and all get updated.

After running an UPDATE or DELETE, how do you find out how many rows were actually affected?

Most drivers and clients report a rows-affected count with the result. Checking it confirms the statement hit the row you expected and didn't silently match zero.

Why might using `SELECT *` in application code be riskier than listing exact column names?

If columns are later added, removed, or reordered, code using SELECT * can silently get different data. Naming columns keeps the query stable through schema changes and avoids fetching data you don't need.

Is `WHERE id = 1` guaranteed to behave the same as `WHERE id = '1'` if id is an INTEGER column?

Many databases convert '1' to a number and still match, but don't rely on it. Some databases are stricter, and in others the conversion can silently stop an index being used. Match the literal's type to the column's type.

Explain what happens, step by step, if you run `DELETE FROM users;` with no WHERE clause.

No WHERE means no filter, so the database deletes every row in users, not just the one you meant. There's no built-in way to pick out 'the one I meant' afterward, which makes this one of the most dangerous SQL mistakes.

You want to update a row and immediately see its new value, like an updated_at timestamp the database sets automatically. What's the advantage of `UPDATE ... RETURNING updated_at` over a separate SELECT afterward?

RETURNING gives the post-update value in the same round trip and the same atomic operation. A follow-up SELECT is an extra query, and another process could change or delete the row in between. RETURNING avoids that race.

Write a single statement that inserts three new products, each with a name and price_cents.

INSERT INTO products (name, price_cents) VALUES ('Pen', 150), ('Notebook', 300), ('Folder', 220);: one INSERT, three value groups, committed together.

Why do INSERT, UPDATE, and DELETE each count as a single atomic operation, even when they affect many rows at once?

The database guarantees the statement either takes effect on every matching row or on none. It never fails partway with only some rows changed. That's why the rows-affected count (0 or the full expected count) is a safe way to judge the outcome.

A developer runs `UPDATE orders SET status = 'shipped' WHERE order_date = '2026-01-01';` intending to update one specific order, but several rows change. What went wrong?

order_date isn't unique; many orders can share a date. So WHERE matched every order from that day. Filtering by the order's id would have hit exactly one row.