🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Web & Software Development › SQL and PostgreSQL Database Development › Lesson 4
TEC-WEB46-04 · Lesson 4 · 13 clock hours · lab

Data Manipulation Language: INSERT, UPDATE, DELETE, and SELECT Basics

Objective. Students will write correct DML statements to insert, update, delete, and retrieve rows, using WHERE clauses and comparison operators accurately.

⚠ Pending professional review

This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.

VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.

What Is Data Manipulation Language?

Data Manipulation Language (DML) is the subset of SQL used to read and change the actual rows stored in a database table. The four core DML statements are INSERT, UPDATE, DELETE, and SELECT. Every web and software application you build will rely on these statements constantly — a user registering an account triggers an INSERT, editing a profile triggers an UPDATE, deleting a post triggers a DELETE, and loading any page almost always triggers a SELECT. Mastering DML is therefore a foundational skill for this trade.

DML statements operate on data only, not on the structure of the database. Statements that create or alter tables belong to a different category called Data Definition Language (DDL). Keep that distinction clear.

INSERT — Adding Rows

Use INSERT to add one or more new rows to a table. Always provide an explicit column list so your code is readable and protected against future table changes.

```sql

INSERT INTO books (title, author_id, genre, published_year, available)

VALUES ('The Great Gatsby', 4, 'Fiction', 1925, TRUE);

```

Rules to remember:

UPDATE — Changing Existing Rows

Use UPDATE to change values in rows that already exist. The WHERE clause controls which rows are affected.

```sql

UPDATE books

SET available = FALSE, last_checked_out = CURRENT_DATE

WHERE book_id = 112;

```

Critical safety rule: Always write and test your WHERE clause with a SELECT first before running UPDATE or DELETE. If you omit the WHERE clause, PostgreSQL will apply the change to every row in the table — this is almost never what you want, and recovery requires a backup. In a production environment, wrapping destructive statements in a transaction (BEGIN … COMMIT / ROLLBACK) gives you a chance to verify results before making them permanent.

You can update multiple columns in one statement by separating assignments with commas in the SET clause.

DELETE — Removing Rows

Use DELETE to remove rows from a table.

```sql

DELETE FROM patrons

WHERE patron_id = 305;

```

The same WHERE-clause safety rule applies: verify with SELECT first. A DELETE without a WHERE clause removes all rows from the table while leaving the table structure intact. Use the before-and-after row count pattern — run SELECT COUNT(*) before and after — to confirm exactly how many rows were affected.

Note: If the row you are deleting is referenced by a foreign key in another table, PostgreSQL will refuse the delete and report a foreign key violation error. You must delete or update the referencing rows first, or the schema must define CASCADE behavior.

SELECT — Retrieving Rows

SELECT is the most-used DML statement. The basic structure is:

```sql

SELECT column1, column2

FROM table_name

WHERE condition

ORDER BY column1 ASC;

```

Useful WHERE clause operators:

| Operator | Purpose | Example |

|---|---|---|

| =, <>, <, > | Comparison | genre = 'Mystery' |

| AND, OR, NOT | Combine conditions | available = TRUE AND genre = 'Fiction' |

| BETWEEN | Inclusive range | published_year BETWEEN 1900 AND 1999 |

| IN | Match a list | genre IN ('Fiction', 'History') |

| LIKE | Pattern match | title LIKE 'The%' |

| IS NULL / IS NOT NULL | Test for missing data | return_date IS NULL |

ORDER BY sorts results; ASC (ascending) is the default. Add DESC for descending order. Always use ORDER BY when row sequence matters to your application.

Reading PostgreSQL Error Messages

PostgreSQL error messages follow a consistent format: an error code, a brief message, and often a DETAIL or HINT line. Common DML errors include:

Train yourself to read the full error message rather than guessing. The message almost always names the table, column, or constraint involved.

Work Habits and Data Integrity

In this lab environment, mistakes are expected and recoverable. Develop these habits now so they become automatic in professional settings:

1. Preview with SELECT before running UPDATE or DELETE.

2. Check row counts before and after with SELECT COUNT(*).

3. Use transactions for multi-step changes during practice.

4. Never hard-code passwords or sensitive data into SQL scripts you share or commit to version control.

These habits protect data integrity, which is a professional and ethical responsibility for anyone who works with databases holding real personal information.

Key terms8

Data Manipulation Language (DML)The subset of SQL that reads and modifies data rows: INSERT, UPDATE, DELETE, and SELECT.
INSERTA DML statement that adds one or more new rows to a specified table.
UPDATEA DML statement that changes column values in existing rows, typically limited by a WHERE clause.
DELETEA DML statement that removes rows from a table; omitting the WHERE clause removes all rows.
WHERE clauseAn optional clause in SELECT, UPDATE, and DELETE that filters which rows are affected or returned, using comparison and logical operators.
LIKE operatorA WHERE clause operator that matches string patterns using % (any sequence of characters) and _ (any single character).
IS NULLA WHERE clause condition that tests whether a column contains no value (NULL); you cannot use = NULL for this test.
Foreign key violationA PostgreSQL error (23503) raised when a DML statement would break a referential integrity constraint between two tables.
In class: Load a provided seed SQL script (500-row sample dataset for a library database) into a lab schema and verify row counts using SELECT COUNT(*); troubleshoot any import errors by reading PostgreSQL error messages. · Complete a 30-item DML exercise set: write INSERT statements with explicit column lists, UPDATE statements with precise WHERE conditions, and DELETE statements, checking before-and-after row counts to confirm correct execution. · Write 15 SELECT queries of increasing complexity using WHERE, AND, OR, NOT, BETWEEN, IN, LIKE, IS NULL, and ORDER BY; compare results against an instructor answer key and debug any discrepancies.
Materials: Library sample dataset seed script (instructor-provided), psql, pgAdmin, DML exercise worksheet, PostgreSQL DML documentation chapter
Check: Students pass a timed 20-query practical check: each query must return the exact result set shown in the answer key; pass = 16/20 queries producing correct output.

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

Database fundamentals / DML
1. A developer runs the following statement without a WHERE clause: UPDATE books SET available = FALSE; What is the result?
Database fundamentals / DML
2. Which INSERT statement correctly adds a row to a patrons table that has columns (patron_id SERIAL, last_name VARCHAR, first_name VARCHAR, email VARCHAR)?
Database fundamentals / DML
3. You need to find all books published between 1950 and 1975, inclusive. Which WHERE clause is correct?
Database fundamentals / DML
4. A query should return all patrons whose email address ends with '.edu'. Which LIKE pattern is correct?
Database fundamentals / DML
5. Before running a DELETE statement, you want to confirm how many rows will be removed. What is the best practice?
Database fundamentals / DML
6. PostgreSQL returns error code 23503. What does this indicate?
Database fundamentals / DML
7. Which SELECT query returns all columns for books where the return_date has not been recorded (is missing)?
Database fundamentals / DML
8. A student writes this UPDATE statement: UPDATE patrons SET email = 'new@library.org' WHERE last_name = 'Garcia' AND first_name = 'Luis'; The query executes without error but SELECT COUNT(*) shows the same count before and after. What is the most likely explanation?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.