17 janeiro 2014

SQL: Learning it the hard way

I'm current reading Learn SQL The Hard Way, It's the first book from "learncodethehardway" that I read. I really liked their teaching approach, they don't waste time, the entire book is really practical. If you want to learn some SQL, I suggest you to read THIS book.
Here is some basic SQL operations you'll learn in the beginning of the book:

Creating basic tables:
CREATE TABLE person (
  id INTEGER PRIMARY KEY,
  first_name TEXT,
  last_name TEXT,
  age INTEGER
);

CREATE TABLE pet (
  id INTEGER PRIMARY KEY,
  name TEXT,
  breed TEXT,
  age INTEGER,
  dead INTEGER
);
Creating a relation table between person and pet:
CREATE TABLE person_pet (
  person_id INTEGER,
  pet_id INTEGER
);
Inserting data:
INSERT INTO person (id, first_name, last_name, age) VALUES (0, 'bernardo', 'fire', 17);
INSERT INTO pet (id, name, breed, age, dead) VALUES (0, 'zeus', 'dog', 6, 0);
Inserting referential data:
INSERT INTO person_pet (person_id, pet_id) VALUES (0, 0);
Selecting Data:
SELECT * FROM person;
SELECT name, breed FROM pet;
SELECT name FROM pet WHERE breed = "unicorn";
SELECT * FROM pet WHERE dead = 0;
Select Across Many Table:
SELECT pet.id, pet.name, pet.age, pet.dead
    FROM pet, person_pet, person
    WHERE
    pet.id = person_pet.pet_id AND
    person_pet.person_id = person.id AND
    person.first_name = "bernardo";
Deleting Data:
DELETE FROM pet WHERE first_name = 'bernardo';
Droping table:
DROP TABLE person;
Deleting using other tables:
DELETE FROM pet WHERE id IN (
    SELECT pet.id
    FROM pet, person_pet, person
    WHERE
    pet.id = person_pet.pet_id AND
    person_pet.person_id = person.id AND
    person.first_name = "bernardo"
);
Removing the relation table since the pet doesn't longer exist.
DELETE FROM person_pet WHERE pet.id NOT IN (
    SELECT id FROM pet
);