How databases work: tables, rows and SQL
The few SQL commands that cover most work: create a table, insert, select with where and order by, update, delete, count and group by.
The few SQL commands that cover most work: create a table, insert, select with where and order by, update, delete, count and group by.
In plain words
A table is a grid. Each column has a name and a kind of value; each row is one thing. SQL is the language you use to talk to the filing clerk: "add this row", "show me the rows where the word is hello", "change this one", "throw that away".
Try it yourself
Practice in psql against your own database (PGPASSWORD=app psql -h localhost -U app -d appdb). Try these one at a time and read each answer:
create table trips (id serial primary key, city text not null, days int);
insert into trips (city, days) values ('Athens', 3), ('Rhodes', 5), ('Athens', 2);
select * from trips;
select city, days from trips where city = 'Athens' order by days;
update trips set days = 4 where id = 1;
select count(*) from trips;
select city, sum(days) from trips group by city;
delete from trips where id = 3;
Inside psql, \dt lists tables, \d trips describes one, and \q quits.
A step further
Read select ... where ... order by as a sentence: show these columns, from this table, only the rows like this, in this order. group by makes one row per group, and sum or count work on each group.
The most important habit: update and delete without where change every row. Run the matching select ... where ... first and check which rows it shows.
Design exercise: what tables would a trip planner need (trips, people, hotels)? What links them? That link is a foreign key.
How it works in real projects
Data you cannot afford to lose lives in a database with backups, and applications talk to it only through code that uses parameters. SQL is the same language in PostgreSQL, MySQL and most others, so what you learn here travels.