SQL

Lesson 7 of 10

Lesson ยท 14 min

Change data

Queries that change the database

Until now, you only read data. SQL can also change it. A statement that changes data does not give a result table. Absolute Path shows a short message, such as OK. 1 row changed.

The changes last only for the run. Each time you press Run, the database starts again from the start, and your whole file runs from the top.

CREATE TABLE

CREATE TABLE makes a new table. You give each column a name and a type.

CREATE TABLE pets (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  age INTEGER
);
  • INTEGER is a whole number. TEXT is text. REAL is a number with decimals.
  • PRIMARY KEY marks the column that identifies each row. It is never repeated.
  • NOT NULL means that the column must always have a value.

INSERT

INSERT INTO adds rows. Write the column names, and then the values in the same order.

INSERT INTO pets (id, name, age) VALUES (1, 'Biscuit', 4);
INSERT INTO pets (id, name, age) VALUES (2, 'Pepper', 2), (3, 'Moss', 7);

UPDATE

UPDATE changes the rows that match the WHERE clause.

UPDATE pets SET age = 5 WHERE name = 'Biscuit';

Be careful. UPDATE and DELETE without a WHERE clause change every row in the table. Always write the WHERE clause first, and run a SELECT with the same WHERE clause to see which rows it finds.

DELETE

DELETE removes the rows that match the WHERE clause.

DELETE FROM pets WHERE age > 10;

Your turn

The table books has the same eight books as before. Do the seven tasks in order, and write the statements one after the other in the editor. The checker looks at the state of the database after your whole file has run.

Tasks

7 to do

  1. Task 1, not checked yet. Create a table named readers with two columns: id (type INTEGER, the primary key) and name (type TEXT, not null).

  2. Task 2, not checked yet. Add two rows to readers: 1 and 'Ana', and 2 and 'Ben'. Use one INSERT INTO statement.

  3. Task 3, not checked yet. Add a book to books: id 9, title 'Slow Rivers', author 'Noor Haddad', genre 'Non-fiction', year 2023, price 18.00.

  4. Task 4, not checked yet. Change the price of the book 'Copper Hill' to 12.50. Use UPDATE. Change only that one book.

  5. Task 5, not checked yet. Lower the price of every Fantasy book by 10%. Set price to price * 0.9 for the rows where genre is 'Fantasy'.

  6. Task 6, not checked yet. Delete the books that were published before 2015. Use DELETE.

  7. Task 7, not checked yet. Write a query that selects the id, title, and price of every book, in order of id.

Task 1 of 7

Create a table named readers with two columns: id (type INTEGER, the primary key) and name (type TEXT, not null).

All tasks

query.sql

Ctrl+Enter runs your code. Ctrl+Shift+Enter checks it. Press Esc, then Tab, to leave the editor.

Output

Press Run to see your result

Your output shows here. Press Run to try your code.