Start learning free

LESSON 52 OF 173 · BACKEND: SQL

Remove Rows with DELETE in JavaScript

Practice

DELETE FROM removes rows from a table. It always removes whole rows: to change one value in a row that stays, you use UPDATE instead.

WHERE picks the rows to remove, just like in a SELECT. For example, this removes the products that cost more than 40, which is only the gift card:

DELETE FROM products
WHERE price > 40;

Without a WHERE, DELETE removes every row: the table is still there, but it is empty. A safe habit: before a DELETE, run a SELECT with the same WHERE to see which rows will go. The rows that stay keep their ids.

The check runs your statement, then prints the id, name and stock of every product left. It must print:

id | name | stock
1 | Mug | 10
3 | Lamp | 1
4 | Pen | 120
5 | Plant | 6
6 | Teapot | 4
7 | Stapler | 15
8 | Gift card | 999
(7 rows)

Your task: in query, remove the products that have no stock: the rows whose stock is 0. Every other product stays.


Assignment
Follow the Coding Tutorial to write the DELETE statement in query, one clause per line.


Hint
Without a WHERE, the check finds an empty table. The WHERE compares the stock column with the number 0 using =; numbers need no quotes. Old orders still mention the notebook, and Node's DatabaseSync normally refuses to delete a row that other tables point at. The starting code opens the database with enableForeignKeyConstraints: false, so you see what DELETE does on its own; a later lesson is about that protection.


STEP 1 OF 2
    Ctrl + Enter to check

    Sql Delete in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free