SQL
SQL - Structured query language.
Creating and Using a Database
CREATE DATABASE database_name;
USE travel;
- CREATE DATABASE: Creates a new database.
- USE: Selects the database to work with.
Creating Tabels
CREATE TABLE planes (num INTEGER PRIMARY KEY,country_start VARCHAR(25),country_arrival VARCHAR(25));
- planes table stores flight routes.
- num is the unique identifier (Primary Key).
- country_start and country_arrival represent the departure and arrival countries.
CREATE TABLE ftypes (num INTEGER PRIMARY KEY,flight_type CHAR(25),food_on_plane CHAR(25),plane_num INTEGER,FOREIGN KEY (plane_num) REFERENCES planes(num));
- ftypes table stores flight types (e.g. Direct, 1 stop).
- plane_num is a foreign key linking to planes.num.
Inserting Data
INSERT INTO planes VALUES (5 , 'France', 'USA');
INSERT INTO ftypes VALUES (1, 'Direct', 'yes', 5);
- Adds records (rows) into tables.
Selecting Data
SELECT * FROM planes;
SELECT country_start AS 'start' FROM planes;
SELECT num, country_start FROM planes;
SELECT country_start AS 'flying from', country_arrival AS 'flying to' FROM planes ORDER BY country_start;
- SELECT retrieves data.
- AS gives columns an alias (friendly name).
- ORDER BY sorts results.
Filtering Results
SELECT * FROM planes WHERE country_start LIKE '%an%';
SELECT * FROM ftypes WHERE num >= 2;
SELECT * FROM ftypes WHERE food_on_plane LIKE '%y%' AND flight_type LIKE '%di%';
SELECT * FROM planes WHERE country_start LIKE '%ca%' OR country_arrival LIKE '%ja%';
WHEREfilters rows.
LIKEis used for pattern matching (e.g.,%an%means “contains 'an'”).
AND/ORcombine conditions.
Updating Data
UPDATE ftypes SET food_on_plane = 'yes' WHERE num = 2;
- UPDATE modifies existing records.
- Only rows where num = 2 are updated.
DELETE FROM ftypes WHERE num = 4;
DELETE removes rows.
Using BETWEEN
SELECT * FROM ftypes WHERE num BETWEEN 1 AND 2;
BETWEEN filters values in a range (inclusive).
Joins
Use of joins combine data between tables
LEFT JOIN
-
Returns all rows from
planes, with matching rows fromftypes. -
If no match,
NULLvalues appear forftypes.
🡺 RIGHT JOIN
-
Returns all rows from
ftypes, with matching rows fromplanes.
🪢 INNER JOIN
-
Returns only rows where there's a match in both tables.
