This episode is about the basic statements needed to create, read, update and delete data in a database system.
Let’s assume we work as a data scientist for Knight Industries. We want to help the Foundation of Law and Government to keep track of our operatives.
We decide to use a classic relational database management system or RDBMS. In order to explore Database Management Systems we can either install one locally or we can use an online tool like SQLFiddle.
To interact with RDBMS we use SQL – the Structured Query Language.
As the name says SQL (speak either S-Q-L or Sequel) is used to write structured queries. Think of “conversations” when You think of “queries”.
So, let’s fire up SQLFiddle.
At first we have an empty database, so we create a table named operatives with the following columns: id, name and birthday
CREATE TABLE operatives (id INTEGER, name TEXT, birthday DATE);
So we learned our first SQL statement: CREATE TABLE. It does exactly what its name suggest: create a table in a database.
We add Michael Arthur Long to our operatives:
INSERT INTO operatives (id, name, birthday) VALUES (1, "Michael Arthur Long", "1949-01-09");
Good practice: Although You could insert the first record into the database without repeating the column names it is considered a good practice to state the names of the columns you want to insert your data into.
We add three more of our employees to the operatives table.
INSERT INTO operatives (id, name, birthday)VALUES (2, "Devon Miles", "1942-07-12");
INSERT INTO operatives (id, name, birthday)VALUES (3, "Dr. Bonnie Barstow", "1954-11-24");
INSERT INTO operatives (id, name, birthday)VALUES (4, "Reginald Cornelius III", "1952-05-04");
Michael Arthur Long gets his new name: Michael Knight. We update his record in our database.
UPDATE operatives SET name = "Michael Knight" WHERE id = 1;
We want to track the different occupations of the team members and add a new column to operatives table.
ALTER TABLE operatives ADD COLUMN occupation TEXT;
Update the occupation of all operatives
UPDATE operatives SET occupation = "Field Agent" WHERE id = 1; UPDATE operatives SET occupation = "Head of Operations" WHERE id = 2; UPDATE operatives SET occupation = "Technician" WHERE id = 3; UPDATE operatives SET occupation = "Truck Driver" WHERE id = 4;
Bonnie left in 1983 to pursue graduate studies. We remove her from operatives.
DELETE FROM operatives WHERE id = 3;
We add April Curtis as Head of Design Team.
INSERT INTO operatives VALUES (5, "April Curtis", "1952-05-04", "Senior Design Officer");
To evaluate ebery step of our implementation we can always use:
SELECT * FROM operatives;