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
);
INTEGERis a whole number.TEXTis text.REALis a number with decimals.PRIMARY KEYmarks the column that identifies each row. It is never repeated.NOT NULLmeans 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.
UPDATEandDELETEwithout aWHEREclause change every row in the table. Always write theWHEREclause first, and run aSELECTwith the sameWHEREclause 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
Task 1, not checked yet. Create a table named
readerswith two columns:id(typeINTEGER, the primary key) andname(typeTEXT, not null).Task 2, not checked yet. Add two rows to
readers:1and'Ana', and2and'Ben'. Use oneINSERT INTOstatement.Task 3, not checked yet. Add a book to
books: id9, title'Slow Rivers', author'Noor Haddad', genre'Non-fiction', year2023, price18.00.Task 4, not checked yet. Change the price of the book
'Copper Hill'to12.50. UseUPDATE. Change only that one book.Task 5, not checked yet. Lower the price of every Fantasy book by 10%. Set
pricetoprice * 0.9for the rows wheregenreis'Fantasy'.Task 6, not checked yet. Delete the books that were published before
2015. UseDELETE.Task 7, not checked yet. Write a query that selects the
id,title, andpriceof every book, in order ofid.
Task 1 of 7
Create a table named readers with two columns: id (type INTEGER, the primary key) and name (type TEXT, not null).